blob: 78c44d1788761c57a663791086c5984b21f8d9dc [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
92bool
93ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
94 bool Complain) {
95 return First->ReadTargetOptions(TargetOpts, Complain) ||
96 Second->ReadTargetOptions(TargetOpts, Complain);
97}
98bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000099 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000100 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
101 Second->ReadDiagnosticOptions(DiagOpts, Complain);
102}
103bool
104ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
105 bool Complain) {
106 return First->ReadFileSystemOptions(FSOpts, Complain) ||
107 Second->ReadFileSystemOptions(FSOpts, Complain);
108}
109
110bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000111 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
112 bool Complain) {
113 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
114 Complain) ||
115 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000117}
118bool ChainedASTReaderListener::ReadPreprocessorOptions(
119 const PreprocessorOptions &PPOpts, bool Complain,
120 std::string &SuggestedPredefines) {
121 return First->ReadPreprocessorOptions(PPOpts, Complain,
122 SuggestedPredefines) ||
123 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
124}
125void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
126 unsigned Value) {
127 First->ReadCounter(M, Value);
128 Second->ReadCounter(M, Value);
129}
130bool ChainedASTReaderListener::needsInputFileVisitation() {
131 return First->needsInputFileVisitation() ||
132 Second->needsInputFileVisitation();
133}
134bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
135 return First->needsSystemInputFileVisitation() ||
136 Second->needsSystemInputFileVisitation();
137}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000138void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
139 First->visitModuleFile(Filename);
140 Second->visitModuleFile(Filename);
141}
Ben Langmuircb69b572014-03-07 06:40:32 +0000142bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000143 bool isSystem,
144 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000145 bool Continue = false;
146 if (First->needsInputFileVisitation() &&
147 (!isSystem || First->needsSystemInputFileVisitation()))
148 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
149 if (Second->needsInputFileVisitation() &&
150 (!isSystem || Second->needsSystemInputFileVisitation()))
151 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
152 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000153}
154
Guy Benyei11169dd2012-12-18 14:30:41 +0000155//===----------------------------------------------------------------------===//
156// PCH validator implementation
157//===----------------------------------------------------------------------===//
158
159ASTReaderListener::~ASTReaderListener() {}
160
161/// \brief Compare the given set of language options against an existing set of
162/// language options.
163///
164/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000165/// \param AllowCompatibleDifferences If true, differences between compatible
166/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000167///
168/// \returns true if the languagae options mis-match, false otherwise.
169static bool checkLanguageOptions(const LangOptions &LangOpts,
170 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000171 DiagnosticsEngine *Diags,
172 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000173#define LANGOPT(Name, Bits, Default, Description) \
174 if (ExistingLangOpts.Name != LangOpts.Name) { \
175 if (Diags) \
176 Diags->Report(diag::err_pch_langopt_mismatch) \
177 << Description << LangOpts.Name << ExistingLangOpts.Name; \
178 return true; \
179 }
180
181#define VALUE_LANGOPT(Name, Bits, Default, Description) \
182 if (ExistingLangOpts.Name != LangOpts.Name) { \
183 if (Diags) \
184 Diags->Report(diag::err_pch_langopt_value_mismatch) \
185 << Description; \
186 return true; \
187 }
188
189#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
190 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
191 if (Diags) \
192 Diags->Report(diag::err_pch_langopt_value_mismatch) \
193 << Description; \
194 return true; \
195 }
196
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000197#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
198 if (!AllowCompatibleDifferences) \
199 LANGOPT(Name, Bits, Default, Description)
200
201#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
202 if (!AllowCompatibleDifferences) \
203 ENUM_LANGOPT(Name, Bits, Default, Description)
204
Guy Benyei11169dd2012-12-18 14:30:41 +0000205#define BENIGN_LANGOPT(Name, Bits, Default, Description)
206#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
207#include "clang/Basic/LangOptions.def"
208
209 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
210 if (Diags)
211 Diags->Report(diag::err_pch_langopt_value_mismatch)
212 << "target Objective-C runtime";
213 return true;
214 }
215
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000216 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
217 LangOpts.CommentOpts.BlockCommandNames) {
218 if (Diags)
219 Diags->Report(diag::err_pch_langopt_value_mismatch)
220 << "block command names";
221 return true;
222 }
223
Guy Benyei11169dd2012-12-18 14:30:41 +0000224 return false;
225}
226
227/// \brief Compare the given set of target options against an existing set of
228/// target options.
229///
230/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
231///
232/// \returns true if the target options mis-match, false otherwise.
233static bool checkTargetOptions(const TargetOptions &TargetOpts,
234 const TargetOptions &ExistingTargetOpts,
235 DiagnosticsEngine *Diags) {
236#define CHECK_TARGET_OPT(Field, Name) \
237 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
238 if (Diags) \
239 Diags->Report(diag::err_pch_targetopt_mismatch) \
240 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
241 return true; \
242 }
243
244 CHECK_TARGET_OPT(Triple, "target");
245 CHECK_TARGET_OPT(CPU, "target CPU");
246 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000247#undef CHECK_TARGET_OPT
248
249 // Compare feature sets.
250 SmallVector<StringRef, 4> ExistingFeatures(
251 ExistingTargetOpts.FeaturesAsWritten.begin(),
252 ExistingTargetOpts.FeaturesAsWritten.end());
253 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
254 TargetOpts.FeaturesAsWritten.end());
255 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
256 std::sort(ReadFeatures.begin(), ReadFeatures.end());
257
258 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
259 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
260 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
261 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
262 ++ExistingIdx;
263 ++ReadIdx;
264 continue;
265 }
266
267 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
268 if (Diags)
269 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
270 << false << ReadFeatures[ReadIdx];
271 return true;
272 }
273
274 if (Diags)
275 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
276 << true << ExistingFeatures[ExistingIdx];
277 return true;
278 }
279
280 if (ExistingIdx < ExistingN) {
281 if (Diags)
282 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
283 << true << ExistingFeatures[ExistingIdx];
284 return true;
285 }
286
287 if (ReadIdx < ReadN) {
288 if (Diags)
289 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
290 << false << ReadFeatures[ReadIdx];
291 return true;
292 }
293
294 return false;
295}
296
297bool
298PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000299 bool Complain,
300 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 const LangOptions &ExistingLangOpts = PP.getLangOpts();
302 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000303 Complain ? &Reader.Diags : nullptr,
304 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000305}
306
307bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
308 bool Complain) {
309 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
310 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000311 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314namespace {
315 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
316 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000317 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
318 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
Ben Langmuirb92de022014-04-29 16:25:26 +0000321static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
322 DiagnosticsEngine &Diags,
323 bool Complain) {
324 typedef DiagnosticsEngine::Level Level;
325
326 // Check current mappings for new -Werror mappings, and the stored mappings
327 // for cases that were explicitly mapped to *not* be errors that are now
328 // errors because of options like -Werror.
329 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
330
331 for (DiagnosticsEngine *MappingSource : MappingSources) {
332 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
333 diag::kind DiagID = DiagIDMappingPair.first;
334 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
335 if (CurLevel < DiagnosticsEngine::Error)
336 continue; // not significant
337 Level StoredLevel =
338 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
339 if (StoredLevel < DiagnosticsEngine::Error) {
340 if (Complain)
341 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
342 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
343 return true;
344 }
345 }
346 }
347
348 return false;
349}
350
Alp Tokerac4e8e52014-06-22 21:58:33 +0000351static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
352 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
353 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
354 return true;
355 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000356}
357
358static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
359 DiagnosticsEngine &Diags,
360 bool IsSystem, bool Complain) {
361 // Top-level options
362 if (IsSystem) {
363 if (Diags.getSuppressSystemWarnings())
364 return false;
365 // If -Wsystem-headers was not enabled before, be conservative
366 if (StoredDiags.getSuppressSystemWarnings()) {
367 if (Complain)
368 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
369 return true;
370 }
371 }
372
373 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
376 return true;
377 }
378
379 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
380 !StoredDiags.getEnableAllWarnings()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
383 return true;
384 }
385
386 if (isExtHandlingFromDiagsError(Diags) &&
387 !isExtHandlingFromDiagsError(StoredDiags)) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
390 return true;
391 }
392
393 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
394}
395
396bool PCHValidator::ReadDiagnosticOptions(
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
398 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
399 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000401 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000402 // This should never fail, because we would have processed these options
403 // before writing them to an ASTFile.
404 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
405
406 ModuleManager &ModuleMgr = Reader.getModuleManager();
407 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
408
409 // If the original import came from a file explicitly generated by the user,
410 // don't check the diagnostic mappings.
411 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000412 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
414 // the transitive closure of its imports, since unrelated modules cannot be
415 // imported until after this module finishes validation.
416 ModuleFile *TopImport = *ModuleMgr.rbegin();
417 while (!TopImport->ImportedBy.empty())
418 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000419 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 return false;
421
422 StringRef ModuleName = TopImport->ModuleName;
423 assert(!ModuleName.empty() && "diagnostic options read before module name");
424
425 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
426 assert(M && "missing module");
427
428 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
429 // contains the union of their flags.
430 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
431}
432
Guy Benyei11169dd2012-12-18 14:30:41 +0000433/// \brief Collect the macro definitions provided by the given preprocessor
434/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000435static void
436collectMacroDefinitions(const PreprocessorOptions &PPOpts,
437 MacroDefinitionsMap &Macros,
438 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
440 StringRef Macro = PPOpts.Macros[I].first;
441 bool IsUndef = PPOpts.Macros[I].second;
442
443 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
444 StringRef MacroName = MacroPair.first;
445 StringRef MacroBody = MacroPair.second;
446
447 // For an #undef'd macro, we only care about the name.
448 if (IsUndef) {
449 if (MacroNames && !Macros.count(MacroName))
450 MacroNames->push_back(MacroName);
451
452 Macros[MacroName] = std::make_pair("", true);
453 continue;
454 }
455
456 // For a #define'd macro, figure out the actual definition.
457 if (MacroName.size() == Macro.size())
458 MacroBody = "1";
459 else {
460 // Note: GCC drops anything following an end-of-line character.
461 StringRef::size_type End = MacroBody.find_first_of("\n\r");
462 MacroBody = MacroBody.substr(0, End);
463 }
464
465 if (MacroNames && !Macros.count(MacroName))
466 MacroNames->push_back(MacroName);
467 Macros[MacroName] = std::make_pair(MacroBody, false);
468 }
469}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471/// \brief Check the preprocessor options deserialized from the control block
472/// against the preprocessor options in an existing preprocessor.
473///
474/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
475static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
476 const PreprocessorOptions &ExistingPPOpts,
477 DiagnosticsEngine *Diags,
478 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000479 std::string &SuggestedPredefines,
480 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 // Check macro definitions.
482 MacroDefinitionsMap ASTFileMacros;
483 collectMacroDefinitions(PPOpts, ASTFileMacros);
484 MacroDefinitionsMap ExistingMacros;
485 SmallVector<StringRef, 4> ExistingMacroNames;
486 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
487
488 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
489 // Dig out the macro definition in the existing preprocessor options.
490 StringRef MacroName = ExistingMacroNames[I];
491 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
492
493 // Check whether we know anything about this macro name or not.
494 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
495 = ASTFileMacros.find(MacroName);
496 if (Known == ASTFileMacros.end()) {
497 // FIXME: Check whether this identifier was referenced anywhere in the
498 // AST file. If so, we should reject the AST file. Unfortunately, this
499 // information isn't in the control block. What shall we do about it?
500
501 if (Existing.second) {
502 SuggestedPredefines += "#undef ";
503 SuggestedPredefines += MacroName.str();
504 SuggestedPredefines += '\n';
505 } else {
506 SuggestedPredefines += "#define ";
507 SuggestedPredefines += MacroName.str();
508 SuggestedPredefines += ' ';
509 SuggestedPredefines += Existing.first.str();
510 SuggestedPredefines += '\n';
511 }
512 continue;
513 }
514
515 // If the macro was defined in one but undef'd in the other, we have a
516 // conflict.
517 if (Existing.second != Known->second.second) {
518 if (Diags) {
519 Diags->Report(diag::err_pch_macro_def_undef)
520 << MacroName << Known->second.second;
521 }
522 return true;
523 }
524
525 // If the macro was #undef'd in both, or if the macro bodies are identical,
526 // it's fine.
527 if (Existing.second || Existing.first == Known->second.first)
528 continue;
529
530 // The macro bodies differ; complain.
531 if (Diags) {
532 Diags->Report(diag::err_pch_macro_def_conflict)
533 << MacroName << Known->second.first << Existing.first;
534 }
535 return true;
536 }
537
538 // Check whether we're using predefines.
539 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
540 if (Diags) {
541 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
542 }
543 return true;
544 }
545
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000546 // Detailed record is important since it is used for the module cache hash.
547 if (LangOpts.Modules &&
548 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
549 if (Diags) {
550 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
551 }
552 return true;
553 }
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Compute the #include and #include_macros lines we need.
556 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
557 StringRef File = ExistingPPOpts.Includes[I];
558 if (File == ExistingPPOpts.ImplicitPCHInclude)
559 continue;
560
561 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
562 != PPOpts.Includes.end())
563 continue;
564
565 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000566 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 SuggestedPredefines += "\"\n";
568 }
569
570 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
571 StringRef File = ExistingPPOpts.MacroIncludes[I];
572 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
573 File)
574 != PPOpts.MacroIncludes.end())
575 continue;
576
577 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n##\n";
580 }
581
582 return false;
583}
584
585bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
586 bool Complain,
587 std::string &SuggestedPredefines) {
588 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
589
590 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000591 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000593 SuggestedPredefines,
594 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595}
596
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000597/// Check the header search options deserialized from the control block
598/// against the header search options in an existing preprocessor.
599///
600/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
601static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
602 StringRef SpecificModuleCachePath,
603 StringRef ExistingModuleCachePath,
604 DiagnosticsEngine *Diags,
605 const LangOptions &LangOpts) {
606 if (LangOpts.Modules) {
607 if (SpecificModuleCachePath != ExistingModuleCachePath) {
608 if (Diags)
609 Diags->Report(diag::err_pch_modulecache_mismatch)
610 << SpecificModuleCachePath << ExistingModuleCachePath;
611 return true;
612 }
613 }
614
615 return false;
616}
617
618bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
619 StringRef SpecificModuleCachePath,
620 bool Complain) {
621 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
622 PP.getHeaderSearchInfo().getModuleCachePath(),
623 Complain ? &Reader.Diags : nullptr,
624 PP.getLangOpts());
625}
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
628 PP.setCounterValue(Value);
629}
630
631//===----------------------------------------------------------------------===//
632// AST reader implementation
633//===----------------------------------------------------------------------===//
634
Nico Weber824285e2014-05-08 04:26:47 +0000635void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
636 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000638 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639}
640
641
642
643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
646
647
648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 using namespace llvm::support;
651 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
652 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000660 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
661 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
662 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 Args.push_back(Reader.getLocalIdentifier(
672 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
674 return SelTable.getSelector(N, Args.data());
675}
676
677ASTSelectorLookupTrait::data_type
678ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
679 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000680 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000681
682 data_type Result;
683
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 Result.ID = Reader.getGlobalSelectorID(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000686 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
688 Result.InstanceBits = FullInstanceBits & 0x3;
689 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
690 Result.FactoryBits = FullFactoryBits & 0x3;
691 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
692 unsigned NumInstanceMethods = FullInstanceBits >> 3;
693 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000694
695 // Load instance methods
696 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
698 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Result.Instance.push_back(Method);
700 }
701
702 // Load factory methods
703 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Factory.push_back(Method);
707 }
708
709 return Result;
710}
711
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000712unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
713 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714}
715
716std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000717ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 using namespace llvm::support;
719 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
720 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return std::make_pair(KeyLen, DataLen);
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::internal_key_type
725ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000727 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728}
729
Douglas Gregordcf25082013-02-11 18:16:18 +0000730/// \brief Whether the given identifier is "interesting".
731static bool isInterestingIdentifier(IdentifierInfo &II) {
732 return II.isPoisoned() ||
733 II.isExtensionToken() ||
734 II.getObjCOrBuiltinID() ||
735 II.hasRevertedTokenIDToIdentifier() ||
736 II.hadMacroDefinition() ||
737 II.getFETokenInfo<void>();
738}
739
Guy Benyei11169dd2012-12-18 14:30:41 +0000740IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
741 const unsigned char* d,
742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 using namespace llvm::support;
744 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 bool IsInteresting = RawID & 0x01;
746
747 // Wipe out the "is interesting" bit.
748 RawID = RawID >> 1;
749
750 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
751 if (!IsInteresting) {
752 // For uninteresting identifiers, just build the IdentifierInfo
753 // and associate it with the persistent ID.
754 IdentifierInfo *II = KnownII;
755 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000756 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 KnownII = II;
758 }
759 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 if (!II->isFromAST()) {
761 bool WasInteresting = isInterestingIdentifier(*II);
762 II->setIsFromAST();
763 if (WasInteresting)
764 II->setChangedSinceDeserialization();
765 }
766 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 return II;
768 }
769
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 bool CPlusPlusOperatorKeyword = Bits & 0x01;
773 Bits >>= 1;
774 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
775 Bits >>= 1;
776 bool Poisoned = Bits & 0x01;
777 Bits >>= 1;
778 bool ExtensionToken = Bits & 0x01;
779 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 bool hasSubmoduleMacros = Bits & 0x01;
781 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 bool hadMacroDefinition = Bits & 0x01;
783 Bits >>= 1;
784
785 assert(Bits == 0 && "Extra bits in the identifier?");
786 DataLen -= 8;
787
788 // Build the IdentifierInfo itself and link the identifier ID with
789 // the new IdentifierInfo.
790 IdentifierInfo *II = KnownII;
791 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000792 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 KnownII = II;
794 }
795 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000796 if (!II->isFromAST()) {
797 bool WasInteresting = isInterestingIdentifier(*II);
798 II->setIsFromAST();
799 if (WasInteresting)
800 II->setChangedSinceDeserialization();
801 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000802
803 // Set or check the various bits in the IdentifierInfo structure.
804 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000805 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000806 II->RevertTokenIDToIdentifier();
807 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
808 assert(II->isExtensionToken() == ExtensionToken &&
809 "Incorrect extension token flag");
810 (void)ExtensionToken;
811 if (Poisoned)
812 II->setIsPoisoned(true);
813 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
814 "Incorrect C++ operator keyword flag");
815 (void)CPlusPlusOperatorKeyword;
816
817 // If this identifier is a macro, deserialize the macro
818 // definition.
819 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 uint32_t MacroDirectivesOffset =
821 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000822 DataLen -= 4;
823 SmallVector<uint32_t, 8> LocalMacroIDs;
824 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000825 while (true) {
826 uint32_t LocalMacroID =
827 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000829 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 LocalMacroIDs.push_back(LocalMacroID);
831 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000832 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000833
Richard Smithe842a472014-10-22 02:05:46 +0000834 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000835 // Macro definitions are stored from newest to oldest, so reverse them
836 // before registering them.
837 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000838 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000839 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
840 unsigned Size = 1;
841
842 static const uint32_t HasOverridesFlag = 0x80000000U;
843 if (I + 1 != E && (I[1] & HasOverridesFlag))
844 Size += 1 + (I[1] & ~HasOverridesFlag);
845
846 MacroSizes.push_back(Size);
847 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000848 }
Richard Smith49f906a2014-03-01 00:08:04 +0000849
850 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
851 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
852 SE = MacroSizes.rend();
853 SI != SE; ++SI) {
854 I -= *SI;
855
856 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000857 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000858 if (*SI != 1)
859 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
860 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
861 }
862 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000863 } else {
864 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
865 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 }
867
868 Reader.SetIdentifierInfo(ID, II);
869
870 // Read all of the declarations visible at global scope with this
871 // name.
872 if (DataLen > 0) {
873 SmallVector<uint32_t, 4> DeclIDs;
874 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000875 DeclIDs.push_back(Reader.getGlobalDeclID(
876 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 Reader.SetGloballyVisibleDecls(II, DeclIDs);
878 }
879
880 return II;
881}
882
883unsigned
884ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
885 llvm::FoldingSetNodeID ID;
886 ID.AddInteger(Key.Kind);
887
888 switch (Key.Kind) {
889 case DeclarationName::Identifier:
890 case DeclarationName::CXXLiteralOperatorName:
891 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
892 break;
893 case DeclarationName::ObjCZeroArgSelector:
894 case DeclarationName::ObjCOneArgSelector:
895 case DeclarationName::ObjCMultiArgSelector:
896 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
897 break;
898 case DeclarationName::CXXOperatorName:
899 ID.AddInteger((OverloadedOperatorKind)Key.Data);
900 break;
901 case DeclarationName::CXXConstructorName:
902 case DeclarationName::CXXDestructorName:
903 case DeclarationName::CXXConversionFunctionName:
904 case DeclarationName::CXXUsingDirective:
905 break;
906 }
907
908 return ID.ComputeHash();
909}
910
911ASTDeclContextNameLookupTrait::internal_key_type
912ASTDeclContextNameLookupTrait::GetInternalKey(
913 const external_key_type& Name) const {
914 DeclNameKey Key;
915 Key.Kind = Name.getNameKind();
916 switch (Name.getNameKind()) {
917 case DeclarationName::Identifier:
918 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
919 break;
920 case DeclarationName::ObjCZeroArgSelector:
921 case DeclarationName::ObjCOneArgSelector:
922 case DeclarationName::ObjCMultiArgSelector:
923 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
924 break;
925 case DeclarationName::CXXOperatorName:
926 Key.Data = Name.getCXXOverloadedOperator();
927 break;
928 case DeclarationName::CXXLiteralOperatorName:
929 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
930 break;
931 case DeclarationName::CXXConstructorName:
932 case DeclarationName::CXXDestructorName:
933 case DeclarationName::CXXConversionFunctionName:
934 case DeclarationName::CXXUsingDirective:
935 Key.Data = 0;
936 break;
937 }
938
939 return Key;
940}
941
942std::pair<unsigned, unsigned>
943ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
945 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
946 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 return std::make_pair(KeyLen, DataLen);
948}
949
950ASTDeclContextNameLookupTrait::internal_key_type
951ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000952 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953
954 DeclNameKey Key;
955 Key.Kind = (DeclarationName::NameKind)*d++;
956 switch (Key.Kind) {
957 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 Key.Data = (uint64_t)Reader.getLocalIdentifier(
959 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 case DeclarationName::ObjCZeroArgSelector:
962 case DeclarationName::ObjCOneArgSelector:
963 case DeclarationName::ObjCMultiArgSelector:
964 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000965 (uint64_t)Reader.getLocalSelector(
966 F, endian::readNext<uint32_t, little, unaligned>(
967 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 break;
969 case DeclarationName::CXXOperatorName:
970 Key.Data = *d++; // OverloadedOperatorKind
971 break;
972 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000973 Key.Data = (uint64_t)Reader.getLocalIdentifier(
974 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 break;
976 case DeclarationName::CXXConstructorName:
977 case DeclarationName::CXXDestructorName:
978 case DeclarationName::CXXConversionFunctionName:
979 case DeclarationName::CXXUsingDirective:
980 Key.Data = 0;
981 break;
982 }
983
984 return Key;
985}
986
987ASTDeclContextNameLookupTrait::data_type
988ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
989 const unsigned char* d,
990 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000991 using namespace llvm::support;
992 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000993 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
994 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 return std::make_pair(Start, Start + NumDecls);
996}
997
998bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000999 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 const std::pair<uint64_t, uint64_t> &Offsets,
1001 DeclContextInfo &Info) {
1002 SavedStreamPosition SavedPosition(Cursor);
1003 // First the lexical decls.
1004 if (Offsets.first != 0) {
1005 Cursor.JumpToBit(Offsets.first);
1006
1007 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001008 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001010 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 if (RecCode != DECL_CONTEXT_LEXICAL) {
1012 Error("Expected lexical block");
1013 return true;
1014 }
1015
Chris Lattner0e6c9402013-01-20 02:38:54 +00001016 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
1017 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 }
1019
1020 // Now the lookup table.
1021 if (Offsets.second != 0) {
1022 Cursor.JumpToBit(Offsets.second);
1023
1024 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001025 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001027 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 if (RecCode != DECL_CONTEXT_VISIBLE) {
1029 Error("Expected visible lookup table block");
1030 return true;
1031 }
Justin Bognerda4e6502014-04-14 16:34:29 +00001032 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1033 (const unsigned char *)Blob.data() + Record[0],
1034 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1035 (const unsigned char *)Blob.data(),
1036 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 }
1038
1039 return false;
1040}
1041
1042void ASTReader::Error(StringRef Msg) {
1043 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001044 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1045 Diag(diag::note_module_cache_path)
1046 << PP.getHeaderSearchInfo().getModuleCachePath();
1047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
1050void ASTReader::Error(unsigned DiagID,
1051 StringRef Arg1, StringRef Arg2) {
1052 if (Diags.isDiagnosticInFlight())
1053 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1054 else
1055 Diag(DiagID) << Arg1 << Arg2;
1056}
1057
1058//===----------------------------------------------------------------------===//
1059// Source Manager Deserialization
1060//===----------------------------------------------------------------------===//
1061
1062/// \brief Read the line table in the source manager block.
1063/// \returns true if there was an error.
1064bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001065 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 unsigned Idx = 0;
1067 LineTableInfo &LineTable = SourceMgr.getLineTable();
1068
1069 // Parse the file names
1070 std::map<int, int> FileIDs;
1071 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1072 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001073 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1075 }
1076
1077 // Parse the line entries
1078 std::vector<LineEntry> Entries;
1079 while (Idx < Record.size()) {
1080 int FID = Record[Idx++];
1081 assert(FID >= 0 && "Serialized line entries for non-local file.");
1082 // Remap FileID from 1-based old view.
1083 FID += F.SLocEntryBaseID - 1;
1084
1085 // Extract the line entries
1086 unsigned NumEntries = Record[Idx++];
1087 assert(NumEntries && "Numentries is 00000");
1088 Entries.clear();
1089 Entries.reserve(NumEntries);
1090 for (unsigned I = 0; I != NumEntries; ++I) {
1091 unsigned FileOffset = Record[Idx++];
1092 unsigned LineNo = Record[Idx++];
1093 int FilenameID = FileIDs[Record[Idx++]];
1094 SrcMgr::CharacteristicKind FileKind
1095 = (SrcMgr::CharacteristicKind)Record[Idx++];
1096 unsigned IncludeOffset = Record[Idx++];
1097 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1098 FileKind, IncludeOffset));
1099 }
1100 LineTable.AddEntry(FileID::get(FID), Entries);
1101 }
1102
1103 return false;
1104}
1105
1106/// \brief Read a source manager block
1107bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1108 using namespace SrcMgr;
1109
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001110 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001111
1112 // Set the source-location entry cursor to the current position in
1113 // the stream. This cursor will be used to read the contents of the
1114 // source manager block initially, and then lazily read
1115 // source-location entries as needed.
1116 SLocEntryCursor = F.Stream;
1117
1118 // The stream itself is going to skip over the source manager block.
1119 if (F.Stream.SkipBlock()) {
1120 Error("malformed block record in AST file");
1121 return true;
1122 }
1123
1124 // Enter the source manager block.
1125 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1126 Error("malformed source manager block record in AST file");
1127 return true;
1128 }
1129
1130 RecordData Record;
1131 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001132 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1133
1134 switch (E.Kind) {
1135 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1136 case llvm::BitstreamEntry::Error:
1137 Error("malformed block record in AST file");
1138 return true;
1139 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001141 case llvm::BitstreamEntry::Record:
1142 // The interesting case.
1143 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001145
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001148 StringRef Blob;
1149 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 default: // Default behavior: ignore.
1151 break;
1152
1153 case SM_SLOC_FILE_ENTRY:
1154 case SM_SLOC_BUFFER_ENTRY:
1155 case SM_SLOC_EXPANSION_ENTRY:
1156 // Once we hit one of the source location entries, we're done.
1157 return false;
1158 }
1159 }
1160}
1161
1162/// \brief If a header file is not found at the path that we expect it to be
1163/// and the PCH file was moved from its original location, try to resolve the
1164/// file by assuming that header+PCH were moved together and the header is in
1165/// the same place relative to the PCH.
1166static std::string
1167resolveFileRelativeToOriginalDir(const std::string &Filename,
1168 const std::string &OriginalDir,
1169 const std::string &CurrDir) {
1170 assert(OriginalDir != CurrDir &&
1171 "No point trying to resolve the file if the PCH dir didn't change");
1172 using namespace llvm::sys;
1173 SmallString<128> filePath(Filename);
1174 fs::make_absolute(filePath);
1175 assert(path::is_absolute(OriginalDir));
1176 SmallString<128> currPCHPath(CurrDir);
1177
1178 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1179 fileDirE = path::end(path::parent_path(filePath));
1180 path::const_iterator origDirI = path::begin(OriginalDir),
1181 origDirE = path::end(OriginalDir);
1182 // Skip the common path components from filePath and OriginalDir.
1183 while (fileDirI != fileDirE && origDirI != origDirE &&
1184 *fileDirI == *origDirI) {
1185 ++fileDirI;
1186 ++origDirI;
1187 }
1188 for (; origDirI != origDirE; ++origDirI)
1189 path::append(currPCHPath, "..");
1190 path::append(currPCHPath, fileDirI, fileDirE);
1191 path::append(currPCHPath, path::filename(Filename));
1192 return currPCHPath.str();
1193}
1194
1195bool ASTReader::ReadSLocEntry(int ID) {
1196 if (ID == 0)
1197 return false;
1198
1199 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1200 Error("source location entry ID out-of-range for AST file");
1201 return true;
1202 }
1203
1204 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1205 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001206 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 unsigned BaseOffset = F->SLocEntryBaseOffset;
1208
1209 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001210 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1211 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 Error("incorrectly-formatted source location entry in AST file");
1213 return true;
1214 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001217 StringRef Blob;
1218 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 default:
1220 Error("incorrectly-formatted source location entry in AST file");
1221 return true;
1222
1223 case SM_SLOC_FILE_ENTRY: {
1224 // We will detect whether a file changed and return 'Failure' for it, but
1225 // we will also try to fail gracefully by setting up the SLocEntry.
1226 unsigned InputID = Record[4];
1227 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001228 const FileEntry *File = IF.getFile();
1229 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001230
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001231 // Note that we only check if a File was returned. If it was out-of-date
1232 // we have complained but we will continue creating a FileID to recover
1233 // gracefully.
1234 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 return true;
1236
1237 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1238 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1239 // This is the module's main file.
1240 IncludeLoc = getImportLocation(F);
1241 }
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1245 ID, BaseOffset + Record[0]);
1246 SrcMgr::FileInfo &FileInfo =
1247 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1248 FileInfo.NumCreatedFIDs = Record[5];
1249 if (Record[3])
1250 FileInfo.setHasLineDirectives();
1251
1252 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1253 unsigned NumFileDecls = Record[7];
1254 if (NumFileDecls) {
1255 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1256 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1257 NumFileDecls));
1258 }
1259
1260 const SrcMgr::ContentCache *ContentCache
1261 = SourceMgr.getOrCreateContentCache(File,
1262 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1263 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1264 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1265 unsigned Code = SLocEntryCursor.ReadCode();
1266 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001267 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001268
1269 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1270 Error("AST record has invalid code");
1271 return true;
1272 }
1273
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001274 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001275 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001276 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 }
1278
1279 break;
1280 }
1281
1282 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001283 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 unsigned Offset = Record[0];
1285 SrcMgr::CharacteristicKind
1286 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1287 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001288 if (IncludeLoc.isInvalid() &&
1289 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001290 IncludeLoc = getImportLocation(F);
1291 }
1292 unsigned Code = SLocEntryCursor.ReadCode();
1293 Record.clear();
1294 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001295 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001296
1297 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1298 Error("AST record has invalid code");
1299 return true;
1300 }
1301
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001302 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1303 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001304 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001305 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 break;
1307 }
1308
1309 case SM_SLOC_EXPANSION_ENTRY: {
1310 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1311 SourceMgr.createExpansionLoc(SpellingLoc,
1312 ReadSourceLocation(*F, Record[2]),
1313 ReadSourceLocation(*F, Record[3]),
1314 Record[4],
1315 ID,
1316 BaseOffset + Record[0]);
1317 break;
1318 }
1319 }
1320
1321 return false;
1322}
1323
1324std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1325 if (ID == 0)
1326 return std::make_pair(SourceLocation(), "");
1327
1328 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1329 Error("source location entry ID out-of-range for AST file");
1330 return std::make_pair(SourceLocation(), "");
1331 }
1332
1333 // Find which module file this entry lands in.
1334 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001335 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return std::make_pair(SourceLocation(), "");
1337
1338 // FIXME: Can we map this down to a particular submodule? That would be
1339 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001340 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001341}
1342
1343/// \brief Find the location where the module F is imported.
1344SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1345 if (F->ImportLoc.isValid())
1346 return F->ImportLoc;
1347
1348 // Otherwise we have a PCH. It's considered to be "imported" at the first
1349 // location of its includer.
1350 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001351 // Main file is the importer.
1352 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1353 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 return F->ImportedBy[0]->FirstLoc;
1356}
1357
1358/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1359/// specified cursor. Read the abbreviations that are at the top of the block
1360/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 if (Cursor.EnterSubBlock(BlockID)) {
1363 Error("malformed block record in AST file");
1364 return Failure;
1365 }
1366
1367 while (true) {
1368 uint64_t Offset = Cursor.GetCurrentBitNo();
1369 unsigned Code = Cursor.ReadCode();
1370
1371 // We expect all abbrevs to be at the start of the block.
1372 if (Code != llvm::bitc::DEFINE_ABBREV) {
1373 Cursor.JumpToBit(Offset);
1374 return false;
1375 }
1376 Cursor.ReadAbbrevRecord();
1377 }
1378}
1379
Richard Smithe40f2ba2013-08-07 21:41:30 +00001380Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001381 unsigned &Idx) {
1382 Token Tok;
1383 Tok.startToken();
1384 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1385 Tok.setLength(Record[Idx++]);
1386 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1387 Tok.setIdentifierInfo(II);
1388 Tok.setKind((tok::TokenKind)Record[Idx++]);
1389 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1390 return Tok;
1391}
1392
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001393MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001394 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395
1396 // Keep track of where we are in the stream, then jump back there
1397 // after reading this macro.
1398 SavedStreamPosition SavedPosition(Stream);
1399
1400 Stream.JumpToBit(Offset);
1401 RecordData Record;
1402 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001403 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001404
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 // Advance to the next record, but if we get to the end of the block, don't
1407 // pop it (removing all the abbreviations from the cursor) since we want to
1408 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001409 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001410 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1411
1412 switch (Entry.Kind) {
1413 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1414 case llvm::BitstreamEntry::Error:
1415 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001417 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001418 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001419 case llvm::BitstreamEntry::Record:
1420 // The interesting case.
1421 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 }
1423
1424 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 Record.clear();
1426 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001427 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 case PP_MACRO_DIRECTIVE_HISTORY:
1430 return Macro;
1431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 case PP_MACRO_OBJECT_LIKE:
1433 case PP_MACRO_FUNCTION_LIKE: {
1434 // If we already have a macro, that means that we've hit the end
1435 // of the definition of the macro we were looking for. We're
1436 // done.
1437 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001438 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001439
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001440 unsigned NextIndex = 1; // Skip identifier ID.
1441 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001444 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001446 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1449 // Decode function-like macro info.
1450 bool isC99VarArgs = Record[NextIndex++];
1451 bool isGNUVarArgs = Record[NextIndex++];
1452 bool hasCommaPasting = Record[NextIndex++];
1453 MacroArgs.clear();
1454 unsigned NumArgs = Record[NextIndex++];
1455 for (unsigned i = 0; i != NumArgs; ++i)
1456 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1457
1458 // Install function-like macro info.
1459 MI->setIsFunctionLike();
1460 if (isC99VarArgs) MI->setIsC99Varargs();
1461 if (isGNUVarArgs) MI->setIsGNUVarargs();
1462 if (hasCommaPasting) MI->setHasCommaPasting();
1463 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1464 PP.getPreprocessorAllocator());
1465 }
1466
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 // Remember that we saw this macro last so that we add the tokens that
1468 // form its body to it.
1469 Macro = MI;
1470
1471 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1472 Record[NextIndex]) {
1473 // We have a macro definition. Register the association
1474 PreprocessedEntityID
1475 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1476 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001477 PreprocessingRecord::PPEntityID
1478 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1479 MacroDefinition *PPDef =
1480 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1481 if (PPDef)
1482 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 }
1484
1485 ++NumMacrosRead;
1486 break;
1487 }
1488
1489 case PP_TOKEN: {
1490 // If we see a TOKEN before a PP_MACRO_*, then the file is
1491 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001492 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
John McCallf413f5e2013-05-03 00:10:13 +00001494 unsigned Idx = 0;
1495 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 Macro->AddTokenToBody(Tok);
1497 break;
1498 }
1499 }
1500 }
1501}
1502
1503PreprocessedEntityID
1504ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1505 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1506 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1507 assert(I != M.PreprocessedEntityRemap.end()
1508 && "Invalid index into preprocessed entity index remap");
1509
1510 return LocalID + I->second;
1511}
1512
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1514 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001515}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1519 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001520 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return ikey;
1522}
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1525 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 return false;
1527
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528 if (llvm::sys::path::is_absolute(a.Filename) &&
1529 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001530 return true;
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001533 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001534 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1535 if (!Key.Imported)
1536 return FileMgr.getFile(Key.Filename);
1537
1538 std::string Resolved = Key.Filename;
1539 Reader.ResolveImportedPath(M, Resolved);
1540 return FileMgr.getFile(Resolved);
1541 };
1542
1543 const FileEntry *FEA = GetFile(a);
1544 const FileEntry *FEB = GetFile(b);
1545 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001546}
1547
1548std::pair<unsigned, unsigned>
1549HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 using namespace llvm::support;
1551 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001554}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555
1556HeaderFileInfoTrait::internal_key_type
1557HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001559 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1561 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001562 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001563 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001564 return ikey;
1565}
1566
Guy Benyei11169dd2012-12-18 14:30:41 +00001567HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001568HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 unsigned DataLen) {
1570 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001571 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 HeaderFileInfo HFI;
1573 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001574 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1575 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 HFI.isImport = (Flags >> 5) & 0x01;
1577 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1578 HFI.DirInfo = (Flags >> 2) & 0x03;
1579 HFI.Resolved = (Flags >> 1) & 0x01;
1580 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1582 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1583 M, endian::readNext<uint32_t, little, unaligned>(d));
1584 if (unsigned FrameworkOffset =
1585 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 // The framework offset is 1 greater than the actual offset,
1587 // since 0 is used as an indicator for "no framework name".
1588 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1589 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1590 }
1591
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001592 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001593 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001594 if (LocalSMID) {
1595 // This header is part of a module. Associate it with the module to enable
1596 // implicit module import.
1597 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1598 Module *Mod = Reader.getSubmodule(GlobalSMID);
1599 HFI.isModuleHeader = true;
1600 FileManager &FileMgr = Reader.getFileManager();
1601 ModuleMap &ModMap =
1602 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001603 // FIXME: This information should be propagated through the
1604 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001605 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001606 std::string Filename = key.Filename;
1607 if (key.Imported)
1608 Reader.ResolveImportedPath(M, Filename);
1609 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001610 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001611 }
1612 }
1613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1615 (void)End;
1616
1617 // This HeaderFileInfo was externally loaded.
1618 HFI.External = true;
1619 return HFI;
1620}
1621
Richard Smith49f906a2014-03-01 00:08:04 +00001622void
1623ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1624 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001625 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001627 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001628 if (!Overrides.empty()) {
1629 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1630 OverrideData[0] = Overrides.size();
1631 for (unsigned I = 0; I != Overrides.size(); ++I)
1632 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1633 }
1634 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001635}
1636
1637void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1638 ModuleFile *M,
1639 uint64_t MacroDirectivesOffset) {
1640 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1641 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001642}
1643
1644void ASTReader::ReadDefinedMacros() {
1645 // Note that we are loading defined macros.
1646 Deserializing Macros(this);
1647
1648 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1649 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001650 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
1652 // If there was no preprocessor block, skip this file.
1653 if (!MacroCursor.getBitStreamReader())
1654 continue;
1655
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001656 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 Cursor.JumpToBit((*I)->MacroStartOffset);
1658
1659 RecordData Record;
1660 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001661 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1662
1663 switch (E.Kind) {
1664 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1665 case llvm::BitstreamEntry::Error:
1666 Error("malformed block record in AST file");
1667 return;
1668 case llvm::BitstreamEntry::EndBlock:
1669 goto NextCursor;
1670
1671 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001672 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001673 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001674 default: // Default behavior: ignore.
1675 break;
1676
1677 case PP_MACRO_OBJECT_LIKE:
1678 case PP_MACRO_FUNCTION_LIKE:
1679 getLocalIdentifier(**I, Record[0]);
1680 break;
1681
1682 case PP_TOKEN:
1683 // Ignore tokens.
1684 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 break;
1687 }
1688 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001689 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 }
1691}
1692
1693namespace {
1694 /// \brief Visitor class used to look up identifirs in an AST file.
1695 class IdentifierLookupVisitor {
1696 StringRef Name;
1697 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001698 unsigned &NumIdentifierLookups;
1699 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1704 unsigned &NumIdentifierLookups,
1705 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001707 NumIdentifierLookups(NumIdentifierLookups),
1708 NumIdentifierLookupHits(NumIdentifierLookupHits),
1709 Found()
1710 {
1711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001712
1713 static bool visit(ModuleFile &M, void *UserData) {
1714 IdentifierLookupVisitor *This
1715 = static_cast<IdentifierLookupVisitor *>(UserData);
1716
1717 // If we've already searched this module file, skip it now.
1718 if (M.Generation <= This->PriorGeneration)
1719 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 ASTIdentifierLookupTable *IdTable
1722 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1723 if (!IdTable)
1724 return false;
1725
1726 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1727 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001728 ++This->NumIdentifierLookups;
1729 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 if (Pos == IdTable->end())
1731 return false;
1732
1733 // Dereferencing the iterator has the effect of building the
1734 // IdentifierInfo node and populating it with the various
1735 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001736 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737 This->Found = *Pos;
1738 return true;
1739 }
1740
1741 // \brief Retrieve the identifier info found within the module
1742 // files.
1743 IdentifierInfo *getIdentifierInfo() const { return Found; }
1744 };
1745}
1746
1747void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1748 // Note that we are loading an identifier.
1749 Deserializing AnIdentifier(this);
1750
1751 unsigned PriorGeneration = 0;
1752 if (getContext().getLangOpts().Modules)
1753 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001754
1755 // If there is a global index, look there first to determine which modules
1756 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001757 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001758 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001759 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001760 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1761 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001762 }
1763 }
1764
Douglas Gregor7211ac12013-01-25 23:32:03 +00001765 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001766 NumIdentifierLookups,
1767 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001768 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 markIdentifierUpToDate(&II);
1770}
1771
1772void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1773 if (!II)
1774 return;
1775
1776 II->setOutOfDate(false);
1777
1778 // Update the generation for this identifier.
1779 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001780 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001781}
1782
Richard Smith49f906a2014-03-01 00:08:04 +00001783struct ASTReader::ModuleMacroInfo {
1784 SubmoduleID SubModID;
1785 MacroInfo *MI;
1786 SubmoduleID *Overrides;
1787 // FIXME: Remove this.
1788 ModuleFile *F;
1789
1790 bool isDefine() const { return MI; }
1791
1792 SubmoduleID getSubmoduleID() const { return SubModID; }
1793
Craig Topper00bbdcf2014-06-28 23:22:23 +00001794 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001795 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001796 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001797 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1798 }
1799
Richard Smithdaa69e02014-07-25 04:40:03 +00001800 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001801 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001802 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1803 getOverriddenSubmodules());
1804 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1805 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001806 }
1807};
1808
1809ASTReader::ModuleMacroInfo *
1810ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1811 ModuleMacroInfo Info;
1812
1813 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1814 if (ID & 1) {
1815 // Macro undefinition.
1816 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001817 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001818 } else {
1819 // Macro definition.
1820 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1821 assert(GMacID);
1822
1823 // If this macro has already been loaded, don't do so again.
1824 // FIXME: This is highly dubious. Multiple macro definitions can have the
1825 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1826 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001827 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001828
1829 Info.MI = getMacro(GMacID);
1830 Info.SubModID = Info.MI->getOwningModuleID();
1831 }
1832 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1833 Info.F = PMInfo.M;
1834
1835 return new (Context) ModuleMacroInfo(Info);
1836}
1837
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001838void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1839 const PendingMacroInfo &PMInfo) {
1840 assert(II);
1841
Richard Smithe842a472014-10-22 02:05:46 +00001842 if (PMInfo.M->Kind != MK_ImplicitModule &&
1843 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844 installPCHMacroDirectives(II, *PMInfo.M,
1845 PMInfo.PCHMacroData.MacroDirectivesOffset);
1846 return;
1847 }
Richard Smith49f906a2014-03-01 00:08:04 +00001848
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849 // Module Macro.
1850
Richard Smith49f906a2014-03-01 00:08:04 +00001851 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1852 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001853 return;
1854
Richard Smith49f906a2014-03-01 00:08:04 +00001855 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1856 if (Owner && Owner->NameVisibility == Module::Hidden) {
1857 // Macros in the owning module are hidden. Just remember this macro to
1858 // install if we make this module visible.
1859 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1860 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001861 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863}
1864
1865void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1866 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001867 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001868
1869 BitstreamCursor &Cursor = M.MacroCursor;
1870 SavedStreamPosition SavedPosition(Cursor);
1871 Cursor.JumpToBit(Offset);
1872
1873 llvm::BitstreamEntry Entry =
1874 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1875 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1876 Error("malformed block record in AST file");
1877 return;
1878 }
1879
1880 RecordData Record;
1881 PreprocessorRecordTypes RecType =
1882 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1883 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1884 Error("malformed block record in AST file");
1885 return;
1886 }
1887
1888 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001889 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001890 unsigned Idx = 0, N = Record.size();
1891 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001892 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001893 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001894 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1895 switch (K) {
1896 case MacroDirective::MD_Define: {
1897 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1898 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001899 SubmoduleID ImportedFrom = Record[Idx++];
1900 bool IsAmbiguous = Record[Idx++];
1901 llvm::SmallVector<unsigned, 4> Overrides;
1902 if (ImportedFrom) {
1903 Overrides.insert(Overrides.end(),
1904 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1905 Idx += Overrides.size() + 1;
1906 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001907 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001908 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1909 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001910 MD = DefMD;
1911 break;
1912 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001913 case MacroDirective::MD_Undefine: {
1914 SubmoduleID ImportedFrom = Record[Idx++];
1915 llvm::SmallVector<unsigned, 4> Overrides;
1916 if (ImportedFrom) {
1917 Overrides.insert(Overrides.end(),
1918 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1919 Idx += Overrides.size() + 1;
1920 }
1921 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001922 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001923 }
1924 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001925 bool isPublic = Record[Idx++];
1926 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1927 break;
1928 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001929
1930 if (!Latest)
1931 Latest = MD;
1932 if (Earliest)
1933 Earliest->setPrevious(MD);
1934 Earliest = MD;
1935 }
1936
1937 PP.setLoadedMacroDirective(II, Latest);
1938}
1939
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001940/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001941/// modules.
1942static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001943 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001944 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001945 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001946 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1947 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001948 SourceManager &SrcMgr = Reader.getSourceManager();
1949 bool PrevInSystem
1950 = PrevOwner? PrevOwner->IsSystem
1951 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1952 bool NewInSystem
1953 = NewOwner? NewOwner->IsSystem
1954 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1955 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001956 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001957 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001958}
1959
Richard Smith49f906a2014-03-01 00:08:04 +00001960void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001961 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001962 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001963 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001964 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1965 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001966
Richard Smith49f906a2014-03-01 00:08:04 +00001967 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001968 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001969 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001970 auto HiddenIt = HiddenNamesMap.find(Owner);
1971 if (HiddenIt != HiddenNamesMap.end()) {
1972 HiddenNames &Hidden = HiddenIt->second;
1973 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1974 if (HI != Hidden.HiddenMacros.end()) {
1975 // Register the macro now so we don't lose it when we re-export.
1976 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001977
Richard Smithbb853c72014-08-13 01:23:33 +00001978 auto SubOverrides = HI->second->getOverriddenSubmodules();
1979 Hidden.HiddenMacros.erase(HI);
1980 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1981 }
Richard Smith49f906a2014-03-01 00:08:04 +00001982 }
1983
1984 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001985 Ambig.erase(
1986 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1987 return MD->getInfo()->getOwningModuleID() == OwnerID;
1988 }),
1989 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001990 }
1991}
1992
1993ASTReader::AmbiguousMacros *
1994ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001995 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001996 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001997 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001998 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001999 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002000
Craig Toppera13603a2014-05-22 05:54:18 +00002001 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
2002 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002003 if (PrevDef && PrevDef->isAmbiguous()) {
2004 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
2005 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
2006 Ambig.push_back(PrevDef);
2007
Richard Smithdaa69e02014-07-25 04:40:03 +00002008 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002009
2010 if (!Ambig.empty())
2011 return &Ambig;
2012
2013 AmbiguousMacroDefs.erase(II);
2014 } else {
2015 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00002016 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00002017 if (PrevDef)
2018 Ambig.push_back(PrevDef);
2019
Richard Smithdaa69e02014-07-25 04:40:03 +00002020 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002021
2022 if (!Ambig.empty()) {
2023 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00002024 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00002025 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002026 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002027 }
Richard Smith49f906a2014-03-01 00:08:04 +00002028
2029 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00002030 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002031}
2032
2033void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002034 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002035 assert(II && Owner);
2036
2037 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002038 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002039 // FIXME: If we made macros from this module visible but didn't provide a
2040 // source location for the import, we don't have a location for the macro.
2041 // Use the location at which the containing module file was first imported
2042 // for now.
2043 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002044 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002045 }
2046
Benjamin Kramer834652a2014-05-03 18:44:26 +00002047 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002048 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002049
Richard Smith49f906a2014-03-01 00:08:04 +00002050 // Create a synthetic macro definition corresponding to the import (or null
2051 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002052 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2053 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002054
2055 // If there's no ambiguity, just install the macro.
2056 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002057 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002058 return;
2059 }
2060 assert(!Prev->empty());
2061
2062 if (!MD) {
2063 // We imported a #undef that didn't remove all prior definitions. The most
2064 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002065 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002066 MacroInfo *NewMI = Prev->back()->getInfo();
2067 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002068 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2069
2070 // Install our #undef first so that we don't lose track of it. We'll replace
2071 // this with whichever macro definition ends up winning.
2072 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002073 }
2074
2075 // We're introducing a macro definition that creates or adds to an ambiguity.
2076 // We can resolve that ambiguity if this macro is token-for-token identical to
2077 // all of the existing definitions.
2078 MacroInfo *NewMI = MD->getInfo();
2079 assert(NewMI && "macro definition with no MacroInfo?");
2080 while (!Prev->empty()) {
2081 MacroInfo *PrevMI = Prev->back()->getInfo();
2082 assert(PrevMI && "macro definition with no MacroInfo?");
2083
2084 // Before marking the macros as ambiguous, check if this is a case where
2085 // both macros are in system headers. If so, we trust that the system
2086 // did not get it wrong. This also handles cases where Clang's own
2087 // headers have a different spelling of certain system macros:
2088 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2089 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2090 //
2091 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2092 // overrides the system limits.h's macros, so there's no conflict here.
2093 if (NewMI != PrevMI &&
2094 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2095 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2096 break;
2097
2098 // The previous definition is the same as this one (or both are defined in
2099 // system modules so we can assume they're equivalent); we don't need to
2100 // track it any more.
2101 Prev->pop_back();
2102 }
2103
2104 if (!Prev->empty())
2105 MD->setAmbiguous(true);
2106
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002107 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002108}
2109
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002110ASTReader::InputFileInfo
2111ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002112 // Go find this input file.
2113 BitstreamCursor &Cursor = F.InputFilesCursor;
2114 SavedStreamPosition SavedPosition(Cursor);
2115 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2116
2117 unsigned Code = Cursor.ReadCode();
2118 RecordData Record;
2119 StringRef Blob;
2120
2121 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2122 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2123 "invalid record type for input file");
2124 (void)Result;
2125
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002126 std::string Filename;
2127 off_t StoredSize;
2128 time_t StoredTime;
2129 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002130
Ben Langmuir198c1682014-03-07 07:27:49 +00002131 assert(Record[0] == ID && "Bogus stored ID or offset");
2132 StoredSize = static_cast<off_t>(Record[1]);
2133 StoredTime = static_cast<time_t>(Record[2]);
2134 Overridden = static_cast<bool>(Record[3]);
2135 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002136 ResolveImportedPath(F, Filename);
2137
Hans Wennborg73945142014-03-14 17:45:06 +00002138 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2139 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002140}
2141
2142std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002143 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002144}
2145
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002146InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 // If this ID is bogus, just return an empty input file.
2148 if (ID == 0 || ID > F.InputFilesLoaded.size())
2149 return InputFile();
2150
2151 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002152 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 return F.InputFilesLoaded[ID-1];
2154
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002155 if (F.InputFilesLoaded[ID-1].isNotFound())
2156 return InputFile();
2157
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002159 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002160 SavedStreamPosition SavedPosition(Cursor);
2161 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2162
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002163 InputFileInfo FI = readInputFileInfo(F, ID);
2164 off_t StoredSize = FI.StoredSize;
2165 time_t StoredTime = FI.StoredTime;
2166 bool Overridden = FI.Overridden;
2167 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002168
Ben Langmuir198c1682014-03-07 07:27:49 +00002169 const FileEntry *File
2170 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2171 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2172
2173 // If we didn't find the file, resolve it relative to the
2174 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002175 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002176 F.OriginalDir != CurrentDir) {
2177 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2178 F.OriginalDir,
2179 CurrentDir);
2180 if (!Resolved.empty())
2181 File = FileMgr.getFile(Resolved);
2182 }
2183
2184 // For an overridden file, create a virtual file with the stored
2185 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002186 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2188 }
2189
Craig Toppera13603a2014-05-22 05:54:18 +00002190 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002191 if (Complain) {
2192 std::string ErrorStr = "could not find file '";
2193 ErrorStr += Filename;
2194 ErrorStr += "' referenced by AST file";
2195 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002197 // Record that we didn't find the file.
2198 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2199 return InputFile();
2200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002201
Ben Langmuir198c1682014-03-07 07:27:49 +00002202 // Check if there was a request to override the contents of the file
2203 // that was part of the precompiled header. Overridding such a file
2204 // can lead to problems when lexing using the source locations from the
2205 // PCH.
2206 SourceManager &SM = getSourceManager();
2207 if (!Overridden && SM.isFileOverridden(File)) {
2208 if (Complain)
2209 Error(diag::err_fe_pch_file_overridden, Filename);
2210 // After emitting the diagnostic, recover by disabling the override so
2211 // that the original file will be used.
2212 SM.disableFileContentsOverride(File);
2213 // The FileEntry is a virtual file entry with the size of the contents
2214 // that would override the original contents. Set it to the original's
2215 // size/time.
2216 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2217 StoredSize, StoredTime);
2218 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002219
Ben Langmuir198c1682014-03-07 07:27:49 +00002220 bool IsOutOfDate = false;
2221
2222 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002223 if (!Overridden && //
2224 (StoredSize != File->getSize() ||
2225#if defined(LLVM_ON_WIN32)
2226 false
2227#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002228 // In our regression testing, the Windows file system seems to
2229 // have inconsistent modification times that sometimes
2230 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002231 //
2232 // This also happens in networked file systems, so disable this
2233 // check if validation is disabled or if we have an explicitly
2234 // built PCM file.
2235 //
2236 // FIXME: Should we also do this for PCH files? They could also
2237 // reasonably get shared across a network during a distributed build.
2238 (StoredTime != File->getModificationTime() && !DisableValidation &&
2239 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002240#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002241 )) {
2242 if (Complain) {
2243 // Build a list of the PCH imports that got us here (in reverse).
2244 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2245 while (ImportStack.back()->ImportedBy.size() > 0)
2246 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002247
Ben Langmuir198c1682014-03-07 07:27:49 +00002248 // The top-level PCH is stale.
2249 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2250 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002251
Ben Langmuir198c1682014-03-07 07:27:49 +00002252 // Print the import stack.
2253 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2254 Diag(diag::note_pch_required_by)
2255 << Filename << ImportStack[0]->FileName;
2256 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002257 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002258 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002259 }
2260
Ben Langmuir198c1682014-03-07 07:27:49 +00002261 if (!Diags.isDiagnosticInFlight())
2262 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 }
2264
Ben Langmuir198c1682014-03-07 07:27:49 +00002265 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 }
2267
Ben Langmuir198c1682014-03-07 07:27:49 +00002268 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2269
2270 // Note that we've loaded this input file.
2271 F.InputFilesLoaded[ID-1] = IF;
2272 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002273}
2274
Richard Smith7ed1bc92014-12-05 22:42:13 +00002275/// \brief If we are loading a relocatable PCH or module file, and the filename
2276/// is not an absolute path, add the system or module root to the beginning of
2277/// the file name.
2278void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2279 // Resolve relative to the base directory, if we have one.
2280 if (!M.BaseDirectory.empty())
2281 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002282}
2283
Richard Smith7ed1bc92014-12-05 22:42:13 +00002284void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2286 return;
2287
Richard Smith7ed1bc92014-12-05 22:42:13 +00002288 SmallString<128> Buffer;
2289 llvm::sys::path::append(Buffer, Prefix, Filename);
2290 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002291}
2292
2293ASTReader::ASTReadResult
2294ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002295 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002296 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002298 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002299
2300 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2301 Error("malformed block record in AST file");
2302 return Failure;
2303 }
2304
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002305 // Should we allow the configuration of the module file to differ from the
2306 // configuration of the current translation unit in a compatible way?
2307 //
2308 // FIXME: Allow this for files explicitly specified with -include-pch too.
2309 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2310
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 // Read all of the records and blocks in the control block.
2312 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002313 unsigned NumInputs = 0;
2314 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002315 while (1) {
2316 llvm::BitstreamEntry Entry = Stream.advance();
2317
2318 switch (Entry.Kind) {
2319 case llvm::BitstreamEntry::Error:
2320 Error("malformed block record in AST file");
2321 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002322 case llvm::BitstreamEntry::EndBlock: {
2323 // Validate input files.
2324 const HeaderSearchOptions &HSOpts =
2325 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002326
Richard Smitha1825302014-10-23 22:18:29 +00002327 // All user input files reside at the index range [0, NumUserInputs), and
2328 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002329 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002331
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002332 // If we are reading a module, we will create a verification timestamp,
2333 // so we verify all input files. Otherwise, verify only user input
2334 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002335
2336 unsigned N = NumUserInputs;
2337 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002338 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002339 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002340 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002341 N = NumInputs;
2342
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002343 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002344 InputFile IF = getInputFile(F, I+1, Complain);
2345 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002347 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002349
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002350 if (Listener)
2351 Listener->visitModuleFile(F.FileName);
2352
Ben Langmuircb69b572014-03-07 06:40:32 +00002353 if (Listener && Listener->needsInputFileVisitation()) {
2354 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2355 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002356 for (unsigned I = 0; I < N; ++I) {
2357 bool IsSystem = I >= NumUserInputs;
2358 InputFileInfo FI = readInputFileInfo(F, I+1);
2359 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2360 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002361 }
2362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002364 }
2365
Chris Lattnere7b154b2013-01-19 21:39:22 +00002366 case llvm::BitstreamEntry::SubBlock:
2367 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 case INPUT_FILES_BLOCK_ID:
2369 F.InputFilesCursor = Stream;
2370 if (Stream.SkipBlock() || // Skip with the main cursor
2371 // Read the abbreviations
2372 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2373 Error("malformed block record in AST file");
2374 return Failure;
2375 }
2376 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002377
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002379 if (Stream.SkipBlock()) {
2380 Error("malformed block record in AST file");
2381 return Failure;
2382 }
2383 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385
2386 case llvm::BitstreamEntry::Record:
2387 // The interesting case.
2388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 }
2390
2391 // Read and process a record.
2392 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002393 StringRef Blob;
2394 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 case METADATA: {
2396 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2397 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002398 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2399 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 return VersionMismatch;
2401 }
2402
2403 bool hasErrors = Record[5];
2404 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2405 Diag(diag::err_pch_with_compiler_errors);
2406 return HadErrors;
2407 }
2408
2409 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002410 // Relative paths in a relocatable PCH are relative to our sysroot.
2411 if (F.RelocatablePCH)
2412 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413
2414 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002415 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2417 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002418 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 return VersionMismatch;
2420 }
2421 break;
2422 }
2423
Ben Langmuir487ea142014-10-23 18:05:36 +00002424 case SIGNATURE:
2425 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2426 F.Signature = Record[0];
2427 break;
2428
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 case IMPORTS: {
2430 // Load each of the imported PCH files.
2431 unsigned Idx = 0, N = Record.size();
2432 while (Idx < N) {
2433 // Read information about the AST file.
2434 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2435 // The import location will be the local one for now; we will adjust
2436 // all import locations of module imports after the global source
2437 // location info are setup.
2438 SourceLocation ImportLoc =
2439 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002440 off_t StoredSize = (off_t)Record[Idx++];
2441 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002442 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002443 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002444
2445 // Load the AST file.
2446 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002447 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 ClientLoadCapabilities)) {
2449 case Failure: return Failure;
2450 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002451 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 case OutOfDate: return OutOfDate;
2453 case VersionMismatch: return VersionMismatch;
2454 case ConfigurationMismatch: return ConfigurationMismatch;
2455 case HadErrors: return HadErrors;
2456 case Success: break;
2457 }
2458 }
2459 break;
2460 }
2461
2462 case LANGUAGE_OPTIONS: {
2463 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002464 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002466 ParseLanguageOptions(Record, Complain, *Listener,
2467 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002468 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 return ConfigurationMismatch;
2470 break;
2471 }
2472
2473 case TARGET_OPTIONS: {
2474 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2475 if (Listener && &F == *ModuleMgr.begin() &&
2476 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002477 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 return ConfigurationMismatch;
2479 break;
2480 }
2481
2482 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002483 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002485 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002487 !DisableValidation)
2488 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 break;
2490 }
2491
2492 case FILE_SYSTEM_OPTIONS: {
2493 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2494 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002495 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002497 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 return ConfigurationMismatch;
2499 break;
2500 }
2501
2502 case HEADER_SEARCH_OPTIONS: {
2503 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2504 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002505 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002507 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 return ConfigurationMismatch;
2509 break;
2510 }
2511
2512 case PREPROCESSOR_OPTIONS: {
2513 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2514 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002515 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 ParsePreprocessorOptions(Record, Complain, *Listener,
2517 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002518 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 return ConfigurationMismatch;
2520 break;
2521 }
2522
2523 case ORIGINAL_FILE:
2524 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002525 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002527 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 break;
2529
2530 case ORIGINAL_FILE_ID:
2531 F.OriginalSourceFileID = FileID::get(Record[0]);
2532 break;
2533
2534 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002535 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 break;
2537
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002538 case MODULE_NAME:
2539 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002540 if (Listener)
2541 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002542 break;
2543
Richard Smith223d3f22014-12-06 03:21:08 +00002544 case MODULE_DIRECTORY: {
2545 assert(!F.ModuleName.empty() &&
2546 "MODULE_DIRECTORY found before MODULE_NAME");
2547 // If we've already loaded a module map file covering this module, we may
2548 // have a better path for it (relative to the current build).
2549 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2550 if (M && M->Directory) {
2551 // If we're implicitly loading a module, the base directory can't
2552 // change between the build and use.
2553 if (F.Kind != MK_ExplicitModule) {
2554 const DirectoryEntry *BuildDir =
2555 PP.getFileManager().getDirectory(Blob);
2556 if (!BuildDir || BuildDir != M->Directory) {
2557 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2558 Diag(diag::err_imported_module_relocated)
2559 << F.ModuleName << Blob << M->Directory->getName();
2560 return OutOfDate;
2561 }
2562 }
2563 F.BaseDirectory = M->Directory->getName();
2564 } else {
2565 F.BaseDirectory = Blob;
2566 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002567 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002568 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002569
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002570 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002571 if (ASTReadResult Result =
2572 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2573 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002574 break;
2575
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002577 NumInputs = Record[0];
2578 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002579 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002580 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 break;
2582 }
2583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002584}
2585
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586ASTReader::ASTReadResult
2587ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002588 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002589
2590 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2591 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002592 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 }
2594
2595 // Read all of the records and blocks for the AST file.
2596 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002597 while (1) {
2598 llvm::BitstreamEntry Entry = Stream.advance();
2599
2600 switch (Entry.Kind) {
2601 case llvm::BitstreamEntry::Error:
2602 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002603 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002605 // Outside of C++, we do not store a lookup map for the translation unit.
2606 // Instead, mark it as needing a lookup map to be built if this module
2607 // contains any declarations lexically within it (which it always does!).
2608 // This usually has no cost, since we very rarely need the lookup map for
2609 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002611 if (DC->hasExternalLexicalStorage() &&
2612 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002614
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617 case llvm::BitstreamEntry::SubBlock:
2618 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 case DECLTYPES_BLOCK_ID:
2620 // We lazily load the decls block, but we want to set up the
2621 // DeclsCursor cursor to point into it. Clone our current bitcode
2622 // cursor to it, enter the block and read the abbrevs in that block.
2623 // With the main cursor, we just skip over it.
2624 F.DeclsCursor = Stream;
2625 if (Stream.SkipBlock() || // Skip with the main cursor.
2626 // Read the abbrevs.
2627 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2628 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002629 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 }
2631 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002632
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 case PREPROCESSOR_BLOCK_ID:
2634 F.MacroCursor = Stream;
2635 if (!PP.getExternalSource())
2636 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 if (Stream.SkipBlock() ||
2639 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2640 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002641 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
2643 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2644 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002645
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 case PREPROCESSOR_DETAIL_BLOCK_ID:
2647 F.PreprocessorDetailCursor = Stream;
2648 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002649 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002651 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2656
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 if (!PP.getPreprocessingRecord())
2658 PP.createPreprocessingRecord();
2659 if (!PP.getPreprocessingRecord()->getExternalSource())
2660 PP.getPreprocessingRecord()->SetExternalSource(*this);
2661 break;
2662
2663 case SOURCE_MANAGER_BLOCK_ID:
2664 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002665 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002667
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002669 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2670 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002672
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002674 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 if (Stream.SkipBlock() ||
2676 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2677 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002678 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 }
2680 CommentsCursors.push_back(std::make_pair(C, &F));
2681 break;
2682 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002683
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002685 if (Stream.SkipBlock()) {
2686 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002687 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002688 }
2689 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 }
2691 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002692
2693 case llvm::BitstreamEntry::Record:
2694 // The interesting case.
2695 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 }
2697
2698 // Read and process a record.
2699 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002700 StringRef Blob;
2701 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 default: // Default behavior: ignore.
2703 break;
2704
2705 case TYPE_OFFSET: {
2706 if (F.LocalNumTypes != 0) {
2707 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002708 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002710 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 F.LocalNumTypes = Record[0];
2712 unsigned LocalBaseTypeIndex = Record[1];
2713 F.BaseTypeIndex = getTotalNumTypes();
2714
2715 if (F.LocalNumTypes > 0) {
2716 // Introduce the global -> local mapping for types within this module.
2717 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2718
2719 // Introduce the local -> global mapping for types within this module.
2720 F.TypeRemap.insertOrReplace(
2721 std::make_pair(LocalBaseTypeIndex,
2722 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002723
2724 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 }
2726 break;
2727 }
2728
2729 case DECL_OFFSET: {
2730 if (F.LocalNumDecls != 0) {
2731 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002732 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002734 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 F.LocalNumDecls = Record[0];
2736 unsigned LocalBaseDeclID = Record[1];
2737 F.BaseDeclID = getTotalNumDecls();
2738
2739 if (F.LocalNumDecls > 0) {
2740 // Introduce the global -> local mapping for declarations within this
2741 // module.
2742 GlobalDeclMap.insert(
2743 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2744
2745 // Introduce the local -> global mapping for declarations within this
2746 // module.
2747 F.DeclRemap.insertOrReplace(
2748 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2749
2750 // Introduce the global -> local mapping for declarations within this
2751 // module.
2752 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002753
Ben Langmuir52ca6782014-10-20 16:27:32 +00002754 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 break;
2757 }
2758
2759 case TU_UPDATE_LEXICAL: {
2760 DeclContext *TU = Context.getTranslationUnitDecl();
2761 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002762 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002764 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 TU->setHasExternalLexicalStorage(true);
2766 break;
2767 }
2768
2769 case UPDATE_VISIBLE: {
2770 unsigned Idx = 0;
2771 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2772 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002773 ASTDeclContextNameLookupTable::Create(
2774 (const unsigned char *)Blob.data() + Record[Idx++],
2775 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2776 (const unsigned char *)Blob.data(),
2777 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002778 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002779 auto *DC = cast<DeclContext>(D);
2780 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002781 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2782 delete LookupTable;
2783 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 } else
2785 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2786 break;
2787 }
2788
2789 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002790 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002792 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2793 (const unsigned char *)F.IdentifierTableData + Record[0],
2794 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2795 (const unsigned char *)F.IdentifierTableData,
2796 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002797
2798 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2799 }
2800 break;
2801
2802 case IDENTIFIER_OFFSET: {
2803 if (F.LocalNumIdentifiers != 0) {
2804 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002805 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002807 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 F.LocalNumIdentifiers = Record[0];
2809 unsigned LocalBaseIdentifierID = Record[1];
2810 F.BaseIdentifierID = getTotalNumIdentifiers();
2811
2812 if (F.LocalNumIdentifiers > 0) {
2813 // Introduce the global -> local mapping for identifiers within this
2814 // module.
2815 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2816 &F));
2817
2818 // Introduce the local -> global mapping for identifiers within this
2819 // module.
2820 F.IdentifierRemap.insertOrReplace(
2821 std::make_pair(LocalBaseIdentifierID,
2822 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002823
Ben Langmuir52ca6782014-10-20 16:27:32 +00002824 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2825 + F.LocalNumIdentifiers);
2826 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 break;
2828 }
2829
Ben Langmuir332aafe2014-01-31 01:06:56 +00002830 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002832 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 break;
2834
2835 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002836 if (SpecialTypes.empty()) {
2837 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2838 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2839 break;
2840 }
2841
2842 if (SpecialTypes.size() != Record.size()) {
2843 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002844 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002845 }
2846
2847 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2848 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2849 if (!SpecialTypes[I])
2850 SpecialTypes[I] = ID;
2851 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2852 // merge step?
2853 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 break;
2855
2856 case STATISTICS:
2857 TotalNumStatements += Record[0];
2858 TotalNumMacros += Record[1];
2859 TotalLexicalDeclContexts += Record[2];
2860 TotalVisibleDeclContexts += Record[3];
2861 break;
2862
2863 case UNUSED_FILESCOPED_DECLS:
2864 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2865 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2866 break;
2867
2868 case DELEGATING_CTORS:
2869 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2870 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2871 break;
2872
2873 case WEAK_UNDECLARED_IDENTIFIERS:
2874 if (Record.size() % 4 != 0) {
2875 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002876 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 }
2878
2879 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2880 // files. This isn't the way to do it :)
2881 WeakUndeclaredIdentifiers.clear();
2882
2883 // Translate the weak, undeclared identifiers into global IDs.
2884 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2885 WeakUndeclaredIdentifiers.push_back(
2886 getGlobalIdentifierID(F, Record[I++]));
2887 WeakUndeclaredIdentifiers.push_back(
2888 getGlobalIdentifierID(F, Record[I++]));
2889 WeakUndeclaredIdentifiers.push_back(
2890 ReadSourceLocation(F, Record, I).getRawEncoding());
2891 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2892 }
2893 break;
2894
Richard Smith78165b52013-01-10 23:43:47 +00002895 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002897 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 break;
2899
2900 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002901 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 F.LocalNumSelectors = Record[0];
2903 unsigned LocalBaseSelectorID = Record[1];
2904 F.BaseSelectorID = getTotalNumSelectors();
2905
2906 if (F.LocalNumSelectors > 0) {
2907 // Introduce the global -> local mapping for selectors within this
2908 // module.
2909 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2910
2911 // Introduce the local -> global mapping for selectors within this
2912 // module.
2913 F.SelectorRemap.insertOrReplace(
2914 std::make_pair(LocalBaseSelectorID,
2915 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002916
2917 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919 break;
2920 }
2921
2922 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002923 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 if (Record[0])
2925 F.SelectorLookupTable
2926 = ASTSelectorLookupTable::Create(
2927 F.SelectorLookupTableData + Record[0],
2928 F.SelectorLookupTableData,
2929 ASTSelectorLookupTrait(*this, F));
2930 TotalNumMethodPoolEntries += Record[1];
2931 break;
2932
2933 case REFERENCED_SELECTOR_POOL:
2934 if (!Record.empty()) {
2935 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2936 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2937 Record[Idx++]));
2938 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2939 getRawEncoding());
2940 }
2941 }
2942 break;
2943
2944 case PP_COUNTER_VALUE:
2945 if (!Record.empty() && Listener)
2946 Listener->ReadCounter(F, Record[0]);
2947 break;
2948
2949 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002950 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 F.NumFileSortedDecls = Record[0];
2952 break;
2953
2954 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002955 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 F.LocalNumSLocEntries = Record[0];
2957 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002958 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002959 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 SLocSpaceSize);
2961 // Make our entry in the range map. BaseID is negative and growing, so
2962 // we invert it. Because we invert it, though, we need the other end of
2963 // the range.
2964 unsigned RangeStart =
2965 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2966 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2967 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2968
2969 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2970 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2971 GlobalSLocOffsetMap.insert(
2972 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2973 - SLocSpaceSize,&F));
2974
2975 // Initialize the remapping table.
2976 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002977 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002979 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2981
2982 TotalNumSLocEntries += F.LocalNumSLocEntries;
2983 break;
2984 }
2985
2986 case MODULE_OFFSET_MAP: {
2987 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002988 const unsigned char *Data = (const unsigned char*)Blob.data();
2989 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002990
2991 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2992 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2993 F.SLocRemap.insert(std::make_pair(0U, 0));
2994 F.SLocRemap.insert(std::make_pair(2U, 1));
2995 }
2996
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002998 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2999 RemapBuilder;
3000 RemapBuilder SLocRemap(F.SLocRemap);
3001 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3002 RemapBuilder MacroRemap(F.MacroRemap);
3003 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3004 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3005 RemapBuilder SelectorRemap(F.SelectorRemap);
3006 RemapBuilder DeclRemap(F.DeclRemap);
3007 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003008
3009 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00003010 using namespace llvm::support;
3011 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 StringRef Name = StringRef((const char*)Data, Len);
3013 Data += Len;
3014 ModuleFile *OM = ModuleMgr.lookup(Name);
3015 if (!OM) {
3016 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003017 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 }
3019
Justin Bogner57ba0b22014-03-28 22:03:24 +00003020 uint32_t SLocOffset =
3021 endian::readNext<uint32_t, little, unaligned>(Data);
3022 uint32_t IdentifierIDOffset =
3023 endian::readNext<uint32_t, little, unaligned>(Data);
3024 uint32_t MacroIDOffset =
3025 endian::readNext<uint32_t, little, unaligned>(Data);
3026 uint32_t PreprocessedEntityIDOffset =
3027 endian::readNext<uint32_t, little, unaligned>(Data);
3028 uint32_t SubmoduleIDOffset =
3029 endian::readNext<uint32_t, little, unaligned>(Data);
3030 uint32_t SelectorIDOffset =
3031 endian::readNext<uint32_t, little, unaligned>(Data);
3032 uint32_t DeclIDOffset =
3033 endian::readNext<uint32_t, little, unaligned>(Data);
3034 uint32_t TypeIndexOffset =
3035 endian::readNext<uint32_t, little, unaligned>(Data);
3036
Ben Langmuir785180e2014-10-20 16:27:30 +00003037 uint32_t None = std::numeric_limits<uint32_t>::max();
3038
3039 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3040 RemapBuilder &Remap) {
3041 if (Offset != None)
3042 Remap.insert(std::make_pair(Offset,
3043 static_cast<int>(BaseOffset - Offset)));
3044 };
3045 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3046 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3047 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3048 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3049 PreprocessedEntityRemap);
3050 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3051 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3052 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3053 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003054
3055 // Global -> local mappings.
3056 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3057 }
3058 break;
3059 }
3060
3061 case SOURCE_MANAGER_LINE_TABLE:
3062 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003063 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 break;
3065
3066 case SOURCE_LOCATION_PRELOADS: {
3067 // Need to transform from the local view (1-based IDs) to the global view,
3068 // which is based off F.SLocEntryBaseID.
3069 if (!F.PreloadSLocEntries.empty()) {
3070 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003071 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 }
3073
3074 F.PreloadSLocEntries.swap(Record);
3075 break;
3076 }
3077
3078 case EXT_VECTOR_DECLS:
3079 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3080 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3081 break;
3082
3083 case VTABLE_USES:
3084 if (Record.size() % 3 != 0) {
3085 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 }
3088
3089 // Later tables overwrite earlier ones.
3090 // FIXME: Modules will have some trouble with this. This is clearly not
3091 // the right way to do this.
3092 VTableUses.clear();
3093
3094 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3095 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3096 VTableUses.push_back(
3097 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3098 VTableUses.push_back(Record[Idx++]);
3099 }
3100 break;
3101
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 case PENDING_IMPLICIT_INSTANTIATIONS:
3103 if (PendingInstantiations.size() % 2 != 0) {
3104 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003105 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 }
3107
3108 if (Record.size() % 2 != 0) {
3109 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003110 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
3112
3113 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3114 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3115 PendingInstantiations.push_back(
3116 ReadSourceLocation(F, Record, I).getRawEncoding());
3117 }
3118 break;
3119
3120 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003121 if (Record.size() != 2) {
3122 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3126 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3127 break;
3128
3129 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003130 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3131 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3132 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003133
3134 unsigned LocalBasePreprocessedEntityID = Record[0];
3135
3136 unsigned StartingID;
3137 if (!PP.getPreprocessingRecord())
3138 PP.createPreprocessingRecord();
3139 if (!PP.getPreprocessingRecord()->getExternalSource())
3140 PP.getPreprocessingRecord()->SetExternalSource(*this);
3141 StartingID
3142 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003143 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 F.BasePreprocessedEntityID = StartingID;
3145
3146 if (F.NumPreprocessedEntities > 0) {
3147 // Introduce the global -> local mapping for preprocessed entities in
3148 // this module.
3149 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3150
3151 // Introduce the local -> global mapping for preprocessed entities in
3152 // this module.
3153 F.PreprocessedEntityRemap.insertOrReplace(
3154 std::make_pair(LocalBasePreprocessedEntityID,
3155 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3156 }
3157
3158 break;
3159 }
3160
3161 case DECL_UPDATE_OFFSETS: {
3162 if (Record.size() % 2 != 0) {
3163 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003164 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003166 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3167 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3168 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3169
3170 // If we've already loaded the decl, perform the updates when we finish
3171 // loading this block.
3172 if (Decl *D = GetExistingDecl(ID))
3173 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 break;
3176 }
3177
3178 case DECL_REPLACEMENTS: {
3179 if (Record.size() % 3 != 0) {
3180 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003181 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 }
3183 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3184 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3185 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3186 break;
3187 }
3188
3189 case OBJC_CATEGORIES_MAP: {
3190 if (F.LocalNumObjCCategoriesInMap != 0) {
3191 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003192 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
3194
3195 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003196 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 break;
3198 }
3199
3200 case OBJC_CATEGORIES:
3201 F.ObjCCategories.swap(Record);
3202 break;
3203
3204 case CXX_BASE_SPECIFIER_OFFSETS: {
3205 if (F.LocalNumCXXBaseSpecifiers != 0) {
3206 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003207 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 }
3209
3210 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003211 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3213 break;
3214 }
3215
3216 case DIAG_PRAGMA_MAPPINGS:
3217 if (F.PragmaDiagMappings.empty())
3218 F.PragmaDiagMappings.swap(Record);
3219 else
3220 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3221 Record.begin(), Record.end());
3222 break;
3223
3224 case CUDA_SPECIAL_DECL_REFS:
3225 // Later tables overwrite earlier ones.
3226 // FIXME: Modules will have trouble with this.
3227 CUDASpecialDeclRefs.clear();
3228 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3229 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3230 break;
3231
3232 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003233 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 if (Record[0]) {
3236 F.HeaderFileInfoTable
3237 = HeaderFileInfoLookupTable::Create(
3238 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3239 (const unsigned char *)F.HeaderFileInfoTableData,
3240 HeaderFileInfoTrait(*this, F,
3241 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003242 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003243
3244 PP.getHeaderSearchInfo().SetExternalSource(this);
3245 if (!PP.getHeaderSearchInfo().getExternalLookup())
3246 PP.getHeaderSearchInfo().SetExternalLookup(this);
3247 }
3248 break;
3249 }
3250
3251 case FP_PRAGMA_OPTIONS:
3252 // Later tables overwrite earlier ones.
3253 FPPragmaOptions.swap(Record);
3254 break;
3255
3256 case OPENCL_EXTENSIONS:
3257 // Later tables overwrite earlier ones.
3258 OpenCLExtensions.swap(Record);
3259 break;
3260
3261 case TENTATIVE_DEFINITIONS:
3262 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3264 break;
3265
3266 case KNOWN_NAMESPACES:
3267 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3268 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3269 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003270
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003271 case UNDEFINED_BUT_USED:
3272 if (UndefinedButUsed.size() % 2 != 0) {
3273 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003274 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003275 }
3276
3277 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003278 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003279 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003280 }
3281 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003282 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3283 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003284 ReadSourceLocation(F, Record, I).getRawEncoding());
3285 }
3286 break;
3287
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003289 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 // If we aren't loading a module (which has its own exports), make
3291 // all of the imported modules visible.
3292 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003293 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3294 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3295 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3296 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003297 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003298 }
3299 }
3300 break;
3301 }
3302
3303 case LOCAL_REDECLARATIONS: {
3304 F.RedeclarationChains.swap(Record);
3305 break;
3306 }
3307
3308 case LOCAL_REDECLARATIONS_MAP: {
3309 if (F.LocalNumRedeclarationsInMap != 0) {
3310 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003311 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 }
3313
3314 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003315 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 break;
3317 }
3318
3319 case MERGED_DECLARATIONS: {
3320 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3321 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3322 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3323 for (unsigned N = Record[Idx++]; N > 0; --N)
3324 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3325 }
3326 break;
3327 }
3328
3329 case MACRO_OFFSET: {
3330 if (F.LocalNumMacros != 0) {
3331 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003332 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003334 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 F.LocalNumMacros = Record[0];
3336 unsigned LocalBaseMacroID = Record[1];
3337 F.BaseMacroID = getTotalNumMacros();
3338
3339 if (F.LocalNumMacros > 0) {
3340 // Introduce the global -> local mapping for macros within this module.
3341 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3342
3343 // Introduce the local -> global mapping for macros within this module.
3344 F.MacroRemap.insertOrReplace(
3345 std::make_pair(LocalBaseMacroID,
3346 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003347
3348 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003349 }
3350 break;
3351 }
3352
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003353 case MACRO_TABLE: {
3354 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 break;
3356 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003357
3358 case LATE_PARSED_TEMPLATE: {
3359 LateParsedTemplates.append(Record.begin(), Record.end());
3360 break;
3361 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003362
3363 case OPTIMIZE_PRAGMA_OPTIONS:
3364 if (Record.size() != 1) {
3365 Error("invalid pragma optimize record");
3366 return Failure;
3367 }
3368 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3369 break;
Nico Weber72889432014-09-06 01:25:55 +00003370
3371 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3372 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3373 UnusedLocalTypedefNameCandidates.push_back(
3374 getGlobalDeclID(F, Record[I]));
3375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 }
3377 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003378}
3379
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003380ASTReader::ASTReadResult
3381ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3382 const ModuleFile *ImportedBy,
3383 unsigned ClientLoadCapabilities) {
3384 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003385 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003386
Richard Smithe842a472014-10-22 02:05:46 +00003387 if (F.Kind == MK_ExplicitModule) {
3388 // For an explicitly-loaded module, we don't care whether the original
3389 // module map file exists or matches.
3390 return Success;
3391 }
3392
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003393 // Try to resolve ModuleName in the current header search context and
3394 // verify that it is found in the same module map file as we saved. If the
3395 // top-level AST file is a main file, skip this check because there is no
3396 // usable header search context.
3397 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003398 "MODULE_NAME should come before MODULE_MAP_FILE");
3399 if (F.Kind == MK_ImplicitModule &&
3400 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3401 // An implicitly-loaded module file should have its module listed in some
3402 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003403 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003404 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3405 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3406 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 assert(ImportedBy && "top-level import should be verified");
3408 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003409 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3410 << ImportedBy->FileName
3411 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003412 return Missing;
3413 }
3414
Richard Smithe842a472014-10-22 02:05:46 +00003415 assert(M->Name == F.ModuleName && "found module with different name");
3416
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003417 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003418 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003419 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3420 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 assert(ImportedBy && "top-level import should be verified");
3422 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3423 Diag(diag::err_imported_module_modmap_changed)
3424 << F.ModuleName << ImportedBy->FileName
3425 << ModMap->getName() << F.ModuleMapPath;
3426 return OutOfDate;
3427 }
3428
3429 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3430 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3431 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003432 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003433 const FileEntry *F =
3434 FileMgr.getFile(Filename, false, false);
3435 if (F == nullptr) {
3436 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3437 Error("could not find file '" + Filename +"' referenced by AST file");
3438 return OutOfDate;
3439 }
3440 AdditionalStoredMaps.insert(F);
3441 }
3442
3443 // Check any additional module map files (e.g. module.private.modulemap)
3444 // that are not in the pcm.
3445 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3446 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3447 // Remove files that match
3448 // Note: SmallPtrSet::erase is really remove
3449 if (!AdditionalStoredMaps.erase(ModMap)) {
3450 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3451 Diag(diag::err_module_different_modmap)
3452 << F.ModuleName << /*new*/0 << ModMap->getName();
3453 return OutOfDate;
3454 }
3455 }
3456 }
3457
3458 // Check any additional module map files that are in the pcm, but not
3459 // found in header search. Cases that match are already removed.
3460 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3461 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3462 Diag(diag::err_module_different_modmap)
3463 << F.ModuleName << /*not new*/1 << ModMap->getName();
3464 return OutOfDate;
3465 }
3466 }
3467
3468 if (Listener)
3469 Listener->ReadModuleMapFile(F.ModuleMapPath);
3470 return Success;
3471}
3472
3473
Douglas Gregorc1489562013-02-12 23:36:21 +00003474/// \brief Move the given method to the back of the global list of methods.
3475static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3476 // Find the entry for this selector in the method pool.
3477 Sema::GlobalMethodPool::iterator Known
3478 = S.MethodPool.find(Method->getSelector());
3479 if (Known == S.MethodPool.end())
3480 return;
3481
3482 // Retrieve the appropriate method list.
3483 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3484 : Known->second.second;
3485 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003486 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003487 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003488 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003489 Found = true;
3490 } else {
3491 // Keep searching.
3492 continue;
3493 }
3494 }
3495
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003496 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003497 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003498 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003499 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003500 }
3501}
3502
Richard Smithe657bbd2014-07-18 22:13:40 +00003503void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3504 bool FromFinalization) {
3505 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003506 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003507 bool wasHidden = D->Hidden;
3508 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003509
Richard Smith49f906a2014-03-01 00:08:04 +00003510 if (wasHidden && SemaObj) {
3511 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3512 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 }
3515 }
Richard Smith49f906a2014-03-01 00:08:04 +00003516
Richard Smithe657bbd2014-07-18 22:13:40 +00003517 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3518 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003519 for (const auto &Macro : Names.HiddenMacros) {
3520 if (FromFinalization)
3521 PP.appendMacroDirective(Macro.first,
3522 Macro.second->import(PP, SourceLocation()));
3523 else
3524 installImportedMacro(Macro.first, Macro.second, Owner);
3525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003526}
3527
Richard Smith49f906a2014-03-01 00:08:04 +00003528void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003529 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003530 SourceLocation ImportLoc,
3531 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003533 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003534 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003536 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003537
3538 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003539 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 // there is nothing more to do.
3541 continue;
3542 }
Richard Smith49f906a2014-03-01 00:08:04 +00003543
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 if (!Mod->isAvailable()) {
3545 // Modules that aren't available cannot be made visible.
3546 continue;
3547 }
3548
3549 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003550 if (NameVisibility >= Module::MacrosVisible &&
3551 Mod->NameVisibility < Module::MacrosVisible)
3552 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 // If we've already deserialized any names from this module,
3556 // mark them as visible.
3557 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3558 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003559 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003561 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3562 /*FromFinalization*/false);
3563 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3564 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003566
Guy Benyei11169dd2012-12-18 14:30:41 +00003567 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003568 SmallVector<Module *, 16> Exports;
3569 Mod->getExportedModules(Exports);
3570 for (SmallVectorImpl<Module *>::iterator
3571 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3572 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003573 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003574 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003576
3577 // Detect any conflicts.
3578 if (Complain) {
3579 assert(ImportLoc.isValid() && "Missing import location");
3580 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3581 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3582 Diag(ImportLoc, diag::warn_module_conflict)
3583 << Mod->getFullModuleName()
3584 << Mod->Conflicts[I].Other->getFullModuleName()
3585 << Mod->Conflicts[I].Message;
3586 // FIXME: Need note where the other module was imported.
3587 }
3588 }
3589 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 }
3591}
3592
Douglas Gregore060e572013-01-25 01:03:03 +00003593bool ASTReader::loadGlobalIndex() {
3594 if (GlobalIndex)
3595 return false;
3596
3597 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3598 !Context.getLangOpts().Modules)
3599 return true;
3600
3601 // Try to load the global index.
3602 TriedLoadingGlobalIndex = true;
3603 StringRef ModuleCachePath
3604 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3605 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003606 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003607 if (!Result.first)
3608 return true;
3609
3610 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003611 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003612 return false;
3613}
3614
3615bool ASTReader::isGlobalIndexUnavailable() const {
3616 return Context.getLangOpts().Modules && UseGlobalIndex &&
3617 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3618}
3619
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003620static void updateModuleTimestamp(ModuleFile &MF) {
3621 // Overwrite the timestamp file contents so that file's mtime changes.
3622 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003623 std::error_code EC;
3624 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3625 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003626 return;
3627 OS << "Timestamp file\n";
3628}
3629
Guy Benyei11169dd2012-12-18 14:30:41 +00003630ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3631 ModuleKind Type,
3632 SourceLocation ImportLoc,
3633 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003634 llvm::SaveAndRestore<SourceLocation>
3635 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3636
Richard Smithd1c46742014-04-30 02:24:17 +00003637 // Defer any pending actions until we get to the end of reading the AST file.
3638 Deserializing AnASTFile(this);
3639
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003641 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003642
3643 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003644 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003646 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003647 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 ClientLoadCapabilities)) {
3649 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003650 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 case OutOfDate:
3652 case VersionMismatch:
3653 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003654 case HadErrors: {
3655 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3656 for (const ImportedModule &IM : Loaded)
3657 LoadedSet.insert(IM.Mod);
3658
Douglas Gregor7029ce12013-03-19 00:28:20 +00003659 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003660 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003661 Context.getLangOpts().Modules
3662 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003663 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003664
3665 // If we find that any modules are unusable, the global index is going
3666 // to be out-of-date. Just remove it.
3667 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003668 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003670 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 case Success:
3672 break;
3673 }
3674
3675 // Here comes stuff that we only do once the entire chain is loaded.
3676
3677 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003678 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3679 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 M != MEnd; ++M) {
3681 ModuleFile &F = *M->Mod;
3682
3683 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003684 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3685 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003686
3687 // Once read, set the ModuleFile bit base offset and update the size in
3688 // bits of all files we've seen.
3689 F.GlobalBitOffset = TotalModulesSizeInBits;
3690 TotalModulesSizeInBits += F.SizeInBits;
3691 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3692
3693 // Preload SLocEntries.
3694 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3695 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3696 // Load it through the SourceManager and don't call ReadSLocEntry()
3697 // directly because the entry may have already been loaded in which case
3698 // calling ReadSLocEntry() directly would trigger an assertion in
3699 // SourceManager.
3700 SourceMgr.getLoadedSLocEntryByID(Index);
3701 }
3702 }
3703
Douglas Gregor603cd862013-03-22 18:50:14 +00003704 // Setup the import locations and notify the module manager that we've
3705 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003706 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3707 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 M != MEnd; ++M) {
3709 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003710
3711 ModuleMgr.moduleFileAccepted(&F);
3712
3713 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003714 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 if (!M->ImportedBy)
3716 F.ImportLoc = M->ImportLoc;
3717 else
3718 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3719 M->ImportLoc.getRawEncoding());
3720 }
3721
3722 // Mark all of the identifiers in the identifier table as being out of date,
3723 // so that various accessors know to check the loaded modules when the
3724 // identifier is used.
3725 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3726 IdEnd = PP.getIdentifierTable().end();
3727 Id != IdEnd; ++Id)
3728 Id->second->setOutOfDate(true);
3729
3730 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003731 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3732 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3734 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003735
3736 switch (Unresolved.Kind) {
3737 case UnresolvedModuleRef::Conflict:
3738 if (ResolvedMod) {
3739 Module::Conflict Conflict;
3740 Conflict.Other = ResolvedMod;
3741 Conflict.Message = Unresolved.String.str();
3742 Unresolved.Mod->Conflicts.push_back(Conflict);
3743 }
3744 continue;
3745
3746 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 if (ResolvedMod)
3748 Unresolved.Mod->Imports.push_back(ResolvedMod);
3749 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003750
Douglas Gregorfb912652013-03-20 21:10:35 +00003751 case UnresolvedModuleRef::Export:
3752 if (ResolvedMod || Unresolved.IsWildcard)
3753 Unresolved.Mod->Exports.push_back(
3754 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3755 continue;
3756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003758 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003759
3760 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3761 // Might be unnecessary as use declarations are only used to build the
3762 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003763
3764 InitializeContext();
3765
Richard Smith3d8e97e2013-10-18 06:54:39 +00003766 if (SemaObj)
3767 UpdateSema();
3768
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 if (DeserializationListener)
3770 DeserializationListener->ReaderInitialized(this);
3771
3772 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3773 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3774 PrimaryModule.OriginalSourceFileID
3775 = FileID::get(PrimaryModule.SLocEntryBaseID
3776 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3777
3778 // If this AST file is a precompiled preamble, then set the
3779 // preamble file ID of the source manager to the file source file
3780 // from which the preamble was built.
3781 if (Type == MK_Preamble) {
3782 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3783 } else if (Type == MK_MainFile) {
3784 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3785 }
3786 }
3787
3788 // For any Objective-C class definitions we have already loaded, make sure
3789 // that we load any additional categories.
3790 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3791 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3792 ObjCClassesLoaded[I],
3793 PreviousGeneration);
3794 }
Douglas Gregore060e572013-01-25 01:03:03 +00003795
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003796 if (PP.getHeaderSearchInfo()
3797 .getHeaderSearchOpts()
3798 .ModulesValidateOncePerBuildSession) {
3799 // Now we are certain that the module and all modules it depends on are
3800 // up to date. Create or update timestamp files for modules that are
3801 // located in the module cache (not for PCH files that could be anywhere
3802 // in the filesystem).
3803 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3804 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003805 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003806 updateModuleTimestamp(*M.Mod);
3807 }
3808 }
3809 }
3810
Guy Benyei11169dd2012-12-18 14:30:41 +00003811 return Success;
3812}
3813
Ben Langmuir487ea142014-10-23 18:05:36 +00003814static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3815
Guy Benyei11169dd2012-12-18 14:30:41 +00003816ASTReader::ASTReadResult
3817ASTReader::ReadASTCore(StringRef FileName,
3818 ModuleKind Type,
3819 SourceLocation ImportLoc,
3820 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003821 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003822 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003823 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003824 unsigned ClientLoadCapabilities) {
3825 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003827 ModuleManager::AddModuleResult AddResult
3828 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003829 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003830 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003831 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003832
Douglas Gregor7029ce12013-03-19 00:28:20 +00003833 switch (AddResult) {
3834 case ModuleManager::AlreadyLoaded:
3835 return Success;
3836
3837 case ModuleManager::NewlyLoaded:
3838 // Load module file below.
3839 break;
3840
3841 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003842 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003843 // it.
3844 if (ClientLoadCapabilities & ARR_Missing)
3845 return Missing;
3846
3847 // Otherwise, return an error.
3848 {
3849 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3850 + ErrorStr;
3851 Error(Msg);
3852 }
3853 return Failure;
3854
3855 case ModuleManager::OutOfDate:
3856 // We couldn't load the module file because it is out-of-date. If the
3857 // client can handle out-of-date, return it.
3858 if (ClientLoadCapabilities & ARR_OutOfDate)
3859 return OutOfDate;
3860
3861 // Otherwise, return an error.
3862 {
3863 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3864 + ErrorStr;
3865 Error(Msg);
3866 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 return Failure;
3868 }
3869
Douglas Gregor7029ce12013-03-19 00:28:20 +00003870 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003871
3872 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3873 // module?
3874 if (FileName != "-") {
3875 CurrentDir = llvm::sys::path::parent_path(FileName);
3876 if (CurrentDir.empty()) CurrentDir = ".";
3877 }
3878
3879 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003880 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003881 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003882 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3883
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 // Sniff for the signature.
3885 if (Stream.Read(8) != 'C' ||
3886 Stream.Read(8) != 'P' ||
3887 Stream.Read(8) != 'C' ||
3888 Stream.Read(8) != 'H') {
3889 Diag(diag::err_not_a_pch_file) << FileName;
3890 return Failure;
3891 }
3892
3893 // This is used for compatibility with older PCH formats.
3894 bool HaveReadControlBlock = false;
3895
Chris Lattnerefa77172013-01-20 00:00:22 +00003896 while (1) {
3897 llvm::BitstreamEntry Entry = Stream.advance();
3898
3899 switch (Entry.Kind) {
3900 case llvm::BitstreamEntry::Error:
3901 case llvm::BitstreamEntry::EndBlock:
3902 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003903 Error("invalid record at top-level of AST file");
3904 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003905
3906 case llvm::BitstreamEntry::SubBlock:
3907 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 }
3909
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003911 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3913 if (Stream.ReadBlockInfoBlock()) {
3914 Error("malformed BlockInfoBlock in AST file");
3915 return Failure;
3916 }
3917 break;
3918 case CONTROL_BLOCK_ID:
3919 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003920 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 case Success:
3922 break;
3923
3924 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003925 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 case OutOfDate: return OutOfDate;
3927 case VersionMismatch: return VersionMismatch;
3928 case ConfigurationMismatch: return ConfigurationMismatch;
3929 case HadErrors: return HadErrors;
3930 }
3931 break;
3932 case AST_BLOCK_ID:
3933 if (!HaveReadControlBlock) {
3934 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003935 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 return VersionMismatch;
3937 }
3938
3939 // Record that we've loaded this module.
3940 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3941 return Success;
3942
3943 default:
3944 if (Stream.SkipBlock()) {
3945 Error("malformed block record in AST file");
3946 return Failure;
3947 }
3948 break;
3949 }
3950 }
3951
3952 return Success;
3953}
3954
3955void ASTReader::InitializeContext() {
3956 // If there's a listener, notify them that we "read" the translation unit.
3957 if (DeserializationListener)
3958 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3959 Context.getTranslationUnitDecl());
3960
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // FIXME: Find a better way to deal with collisions between these
3962 // built-in types. Right now, we just ignore the problem.
3963
3964 // Load the special types.
3965 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3966 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3967 if (!Context.CFConstantStringTypeDecl)
3968 Context.setCFConstantStringType(GetType(String));
3969 }
3970
3971 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3972 QualType FileType = GetType(File);
3973 if (FileType.isNull()) {
3974 Error("FILE type is NULL");
3975 return;
3976 }
3977
3978 if (!Context.FILEDecl) {
3979 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3980 Context.setFILEDecl(Typedef->getDecl());
3981 else {
3982 const TagType *Tag = FileType->getAs<TagType>();
3983 if (!Tag) {
3984 Error("Invalid FILE type in AST file");
3985 return;
3986 }
3987 Context.setFILEDecl(Tag->getDecl());
3988 }
3989 }
3990 }
3991
3992 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3993 QualType Jmp_bufType = GetType(Jmp_buf);
3994 if (Jmp_bufType.isNull()) {
3995 Error("jmp_buf type is NULL");
3996 return;
3997 }
3998
3999 if (!Context.jmp_bufDecl) {
4000 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4001 Context.setjmp_bufDecl(Typedef->getDecl());
4002 else {
4003 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4004 if (!Tag) {
4005 Error("Invalid jmp_buf type in AST file");
4006 return;
4007 }
4008 Context.setjmp_bufDecl(Tag->getDecl());
4009 }
4010 }
4011 }
4012
4013 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4014 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4015 if (Sigjmp_bufType.isNull()) {
4016 Error("sigjmp_buf type is NULL");
4017 return;
4018 }
4019
4020 if (!Context.sigjmp_bufDecl) {
4021 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4022 Context.setsigjmp_bufDecl(Typedef->getDecl());
4023 else {
4024 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4025 assert(Tag && "Invalid sigjmp_buf type in AST file");
4026 Context.setsigjmp_bufDecl(Tag->getDecl());
4027 }
4028 }
4029 }
4030
4031 if (unsigned ObjCIdRedef
4032 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4033 if (Context.ObjCIdRedefinitionType.isNull())
4034 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4035 }
4036
4037 if (unsigned ObjCClassRedef
4038 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4039 if (Context.ObjCClassRedefinitionType.isNull())
4040 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4041 }
4042
4043 if (unsigned ObjCSelRedef
4044 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4045 if (Context.ObjCSelRedefinitionType.isNull())
4046 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4047 }
4048
4049 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4050 QualType Ucontext_tType = GetType(Ucontext_t);
4051 if (Ucontext_tType.isNull()) {
4052 Error("ucontext_t type is NULL");
4053 return;
4054 }
4055
4056 if (!Context.ucontext_tDecl) {
4057 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4058 Context.setucontext_tDecl(Typedef->getDecl());
4059 else {
4060 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4061 assert(Tag && "Invalid ucontext_t type in AST file");
4062 Context.setucontext_tDecl(Tag->getDecl());
4063 }
4064 }
4065 }
4066 }
4067
4068 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4069
4070 // If there were any CUDA special declarations, deserialize them.
4071 if (!CUDASpecialDeclRefs.empty()) {
4072 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4073 Context.setcudaConfigureCallDecl(
4074 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4075 }
Richard Smith56be7542014-03-21 00:33:59 +00004076
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004078 // FIXME: This does not make macro-only imports visible again. It also doesn't
4079 // make #includes mapped to module imports visible.
4080 for (auto &Import : ImportedModules) {
4081 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004082 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004083 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004084 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 }
4086 ImportedModules.clear();
4087}
4088
4089void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004090 while (!HiddenNamesMap.empty()) {
4091 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4092 HiddenNamesMap.erase(HiddenNamesMap.begin());
4093 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4094 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004096}
4097
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004098/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4099/// cursor into the start of the given block ID, returning false on success and
4100/// true on failure.
4101static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004102 while (1) {
4103 llvm::BitstreamEntry Entry = Cursor.advance();
4104 switch (Entry.Kind) {
4105 case llvm::BitstreamEntry::Error:
4106 case llvm::BitstreamEntry::EndBlock:
4107 return true;
4108
4109 case llvm::BitstreamEntry::Record:
4110 // Ignore top-level records.
4111 Cursor.skipRecord(Entry.ID);
4112 break;
4113
4114 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004115 if (Entry.ID == BlockID) {
4116 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 return true;
4118 // Found it!
4119 return false;
4120 }
4121
4122 if (Cursor.SkipBlock())
4123 return true;
4124 }
4125 }
4126}
4127
Ben Langmuir487ea142014-10-23 18:05:36 +00004128static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4129 BitstreamCursor Stream(StreamFile);
4130 if (Stream.Read(8) != 'C' ||
4131 Stream.Read(8) != 'P' ||
4132 Stream.Read(8) != 'C' ||
4133 Stream.Read(8) != 'H') {
4134 return 0;
4135 }
4136
4137 // Scan for the CONTROL_BLOCK_ID block.
4138 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4139 return 0;
4140
4141 // Scan for SIGNATURE inside the control block.
4142 ASTReader::RecordData Record;
4143 while (1) {
4144 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4145 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4146 Entry.Kind != llvm::BitstreamEntry::Record)
4147 return 0;
4148
4149 Record.clear();
4150 StringRef Blob;
4151 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4152 return Record[0];
4153 }
4154}
4155
Guy Benyei11169dd2012-12-18 14:30:41 +00004156/// \brief Retrieve the name of the original source file name
4157/// directly from the AST file, without actually loading the AST
4158/// file.
4159std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4160 FileManager &FileMgr,
4161 DiagnosticsEngine &Diags) {
4162 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004163 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004165 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4166 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 return std::string();
4168 }
4169
4170 // Initialize the stream
4171 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004172 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4173 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004174 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004175
4176 // Sniff for the signature.
4177 if (Stream.Read(8) != 'C' ||
4178 Stream.Read(8) != 'P' ||
4179 Stream.Read(8) != 'C' ||
4180 Stream.Read(8) != 'H') {
4181 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4182 return std::string();
4183 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004184
Chris Lattnere7b154b2013-01-19 21:39:22 +00004185 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004186 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004187 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4188 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004189 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004190
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004191 // Scan for ORIGINAL_FILE inside the control block.
4192 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004193 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004194 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004195 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4196 return std::string();
4197
4198 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4199 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4200 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004202
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004204 StringRef Blob;
4205 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4206 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004208}
4209
4210namespace {
4211 class SimplePCHValidator : public ASTReaderListener {
4212 const LangOptions &ExistingLangOpts;
4213 const TargetOptions &ExistingTargetOpts;
4214 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004215 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004217
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 public:
4219 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4220 const TargetOptions &ExistingTargetOpts,
4221 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004222 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 FileManager &FileMgr)
4224 : ExistingLangOpts(ExistingLangOpts),
4225 ExistingTargetOpts(ExistingTargetOpts),
4226 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004227 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 FileMgr(FileMgr)
4229 {
4230 }
4231
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004232 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4233 bool AllowCompatibleDifferences) override {
4234 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4235 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004237 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4238 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004239 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004241 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4242 StringRef SpecificModuleCachePath,
4243 bool Complain) override {
4244 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4245 ExistingModuleCachePath,
4246 nullptr, ExistingLangOpts);
4247 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004248 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4249 bool Complain,
4250 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004251 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004252 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 }
4254 };
4255}
4256
4257bool ASTReader::readASTFileControlBlock(StringRef Filename,
4258 FileManager &FileMgr,
4259 ASTReaderListener &Listener) {
4260 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004261 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 if (!Buffer) {
4263 return true;
4264 }
4265
4266 // Initialize the stream
4267 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004268 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4269 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004270 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004271
4272 // Sniff for the signature.
4273 if (Stream.Read(8) != 'C' ||
4274 Stream.Read(8) != 'P' ||
4275 Stream.Read(8) != 'C' ||
4276 Stream.Read(8) != 'H') {
4277 return true;
4278 }
4279
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004280 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004281 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004282 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004283
4284 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004285 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004286 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004287 BitstreamCursor InputFilesCursor;
4288 if (NeedsInputFiles) {
4289 InputFilesCursor = Stream;
4290 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4291 return true;
4292
4293 // Read the abbreviations
4294 while (true) {
4295 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4296 unsigned Code = InputFilesCursor.ReadCode();
4297
4298 // We expect all abbrevs to be at the start of the block.
4299 if (Code != llvm::bitc::DEFINE_ABBREV) {
4300 InputFilesCursor.JumpToBit(Offset);
4301 break;
4302 }
4303 InputFilesCursor.ReadAbbrevRecord();
4304 }
4305 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004306
4307 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004309 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004310 while (1) {
4311 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4312 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4313 return false;
4314
4315 if (Entry.Kind != llvm::BitstreamEntry::Record)
4316 return true;
4317
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004319 StringRef Blob;
4320 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004321 switch ((ControlRecordTypes)RecCode) {
4322 case METADATA: {
4323 if (Record[0] != VERSION_MAJOR)
4324 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004325
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004326 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004327 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004328
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004329 break;
4330 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004331 case MODULE_NAME:
4332 Listener.ReadModuleName(Blob);
4333 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004334 case MODULE_DIRECTORY:
4335 ModuleDir = Blob;
4336 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004337 case MODULE_MAP_FILE: {
4338 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004339 auto Path = ReadString(Record, Idx);
4340 ResolveImportedPath(Path, ModuleDir);
4341 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004342 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004343 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004344 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004345 if (ParseLanguageOptions(Record, false, Listener,
4346 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004347 return true;
4348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004349
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004350 case TARGET_OPTIONS:
4351 if (ParseTargetOptions(Record, false, Listener))
4352 return true;
4353 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004354
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004355 case DIAGNOSTIC_OPTIONS:
4356 if (ParseDiagnosticOptions(Record, false, Listener))
4357 return true;
4358 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004359
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004360 case FILE_SYSTEM_OPTIONS:
4361 if (ParseFileSystemOptions(Record, false, Listener))
4362 return true;
4363 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004364
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004365 case HEADER_SEARCH_OPTIONS:
4366 if (ParseHeaderSearchOptions(Record, false, Listener))
4367 return true;
4368 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004369
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004370 case PREPROCESSOR_OPTIONS: {
4371 std::string IgnoredSuggestedPredefines;
4372 if (ParsePreprocessorOptions(Record, false, Listener,
4373 IgnoredSuggestedPredefines))
4374 return true;
4375 break;
4376 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004378 case INPUT_FILE_OFFSETS: {
4379 if (!NeedsInputFiles)
4380 break;
4381
4382 unsigned NumInputFiles = Record[0];
4383 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004384 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004385 for (unsigned I = 0; I != NumInputFiles; ++I) {
4386 // Go find this input file.
4387 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004388
4389 if (isSystemFile && !NeedsSystemInputFiles)
4390 break; // the rest are system input files
4391
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004392 BitstreamCursor &Cursor = InputFilesCursor;
4393 SavedStreamPosition SavedPosition(Cursor);
4394 Cursor.JumpToBit(InputFileOffs[I]);
4395
4396 unsigned Code = Cursor.ReadCode();
4397 RecordData Record;
4398 StringRef Blob;
4399 bool shouldContinue = false;
4400 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4401 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004402 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004403 std::string Filename = Blob;
4404 ResolveImportedPath(Filename, ModuleDir);
4405 shouldContinue =
4406 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004407 break;
4408 }
4409 if (!shouldContinue)
4410 break;
4411 }
4412 break;
4413 }
4414
Richard Smithd4b230b2014-10-27 23:01:16 +00004415 case IMPORTS: {
4416 if (!NeedsImports)
4417 break;
4418
4419 unsigned Idx = 0, N = Record.size();
4420 while (Idx < N) {
4421 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004422 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004423 std::string Filename = ReadString(Record, Idx);
4424 ResolveImportedPath(Filename, ModuleDir);
4425 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004426 }
4427 break;
4428 }
4429
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004430 default:
4431 // No other validation to perform.
4432 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 }
4434 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004435}
4436
4437
4438bool ASTReader::isAcceptableASTFile(StringRef Filename,
4439 FileManager &FileMgr,
4440 const LangOptions &LangOpts,
4441 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004442 const PreprocessorOptions &PPOpts,
4443 std::string ExistingModuleCachePath) {
4444 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4445 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 return !readASTFileControlBlock(Filename, FileMgr, validator);
4447}
4448
Ben Langmuir2c9af442014-04-10 17:57:43 +00004449ASTReader::ASTReadResult
4450ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 // Enter the submodule block.
4452 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4453 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004454 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 }
4456
4457 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4458 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004459 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 RecordData Record;
4461 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004462 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4463
4464 switch (Entry.Kind) {
4465 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4466 case llvm::BitstreamEntry::Error:
4467 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004468 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004469 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004470 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004471 case llvm::BitstreamEntry::Record:
4472 // The interesting case.
4473 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004475
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004477 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004479 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4480
4481 if ((Kind == SUBMODULE_METADATA) != First) {
4482 Error("submodule metadata record should be at beginning of block");
4483 return Failure;
4484 }
4485 First = false;
4486
4487 // Submodule information is only valid if we have a current module.
4488 // FIXME: Should we error on these cases?
4489 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4490 Kind != SUBMODULE_DEFINITION)
4491 continue;
4492
4493 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 default: // Default behavior: ignore.
4495 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004496
Richard Smith03478d92014-10-23 22:12:14 +00004497 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004498 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004500 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 }
Richard Smith03478d92014-10-23 22:12:14 +00004502
Chris Lattner0e6c9402013-01-20 02:38:54 +00004503 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004504 unsigned Idx = 0;
4505 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4506 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4507 bool IsFramework = Record[Idx++];
4508 bool IsExplicit = Record[Idx++];
4509 bool IsSystem = Record[Idx++];
4510 bool IsExternC = Record[Idx++];
4511 bool InferSubmodules = Record[Idx++];
4512 bool InferExplicitSubmodules = Record[Idx++];
4513 bool InferExportWildcard = Record[Idx++];
4514 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004515
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004516 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004517 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004519
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 // Retrieve this (sub)module from the module map, creating it if
4521 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004522 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004524
4525 // FIXME: set the definition loc for CurrentModule, or call
4526 // ModMap.setInferredModuleAllowedBy()
4527
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4529 if (GlobalIndex >= SubmodulesLoaded.size() ||
4530 SubmodulesLoaded[GlobalIndex]) {
4531 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004532 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004534
Douglas Gregor7029ce12013-03-19 00:28:20 +00004535 if (!ParentModule) {
4536 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4537 if (CurFile != F.File) {
4538 if (!Diags.isDiagnosticInFlight()) {
4539 Diag(diag::err_module_file_conflict)
4540 << CurrentModule->getTopLevelModuleName()
4541 << CurFile->getName()
4542 << F.File->getName();
4543 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004544 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004545 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004546 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004547
4548 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004549 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004550
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 CurrentModule->IsFromModuleFile = true;
4552 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004553 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 CurrentModule->InferSubmodules = InferSubmodules;
4555 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4556 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004557 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 if (DeserializationListener)
4559 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4560
4561 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004562
Douglas Gregorfb912652013-03-20 21:10:35 +00004563 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004564 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004565 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004566 CurrentModule->UnresolvedConflicts.clear();
4567 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 break;
4569 }
4570
4571 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004572 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 if (!CurrentModule->getUmbrellaHeader())
4574 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4575 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004576 // This can be a spurious difference caused by changing the VFS to
4577 // point to a different copy of the file, and it is too late to
4578 // to rebuild safely.
4579 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4580 // after input file validation only real problems would remain and we
4581 // could just error. For now, assume it's okay.
4582 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 }
4584 }
4585 break;
4586 }
4587
Richard Smith202210b2014-10-24 20:23:01 +00004588 case SUBMODULE_HEADER:
4589 case SUBMODULE_EXCLUDED_HEADER:
4590 case SUBMODULE_PRIVATE_HEADER:
4591 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004592 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4593 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004594 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004595
Richard Smith202210b2014-10-24 20:23:01 +00004596 case SUBMODULE_TEXTUAL_HEADER:
4597 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4598 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4599 // them here.
4600 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004601
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004603 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 break;
4605 }
4606
4607 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004609 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 if (!CurrentModule->getUmbrellaDir())
4611 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4612 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004613 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4614 Error("mismatched umbrella directories in submodule");
4615 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 }
4617 }
4618 break;
4619 }
4620
4621 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 F.BaseSubmoduleID = getTotalNumSubmodules();
4623 F.LocalNumSubmodules = Record[0];
4624 unsigned LocalBaseSubmoduleID = Record[1];
4625 if (F.LocalNumSubmodules > 0) {
4626 // Introduce the global -> local mapping for submodules within this
4627 // module.
4628 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4629
4630 // Introduce the local -> global mapping for submodules within this
4631 // module.
4632 F.SubmoduleRemap.insertOrReplace(
4633 std::make_pair(LocalBaseSubmoduleID,
4634 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004635
Ben Langmuir52ca6782014-10-20 16:27:32 +00004636 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 break;
4639 }
4640
4641 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004643 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 Unresolved.File = &F;
4645 Unresolved.Mod = CurrentModule;
4646 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004647 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004649 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 }
4651 break;
4652 }
4653
4654 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004656 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 Unresolved.File = &F;
4658 Unresolved.Mod = CurrentModule;
4659 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004660 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004662 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 }
4664
4665 // Once we've loaded the set of exports, there's no reason to keep
4666 // the parsed, unresolved exports around.
4667 CurrentModule->UnresolvedExports.clear();
4668 break;
4669 }
4670 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004671 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 Context.getTargetInfo());
4673 break;
4674 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004675
4676 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004677 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004678 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004679 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004680
4681 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004682 CurrentModule->ConfigMacros.push_back(Blob.str());
4683 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004684
4685 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004686 UnresolvedModuleRef Unresolved;
4687 Unresolved.File = &F;
4688 Unresolved.Mod = CurrentModule;
4689 Unresolved.ID = Record[0];
4690 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4691 Unresolved.IsWildcard = false;
4692 Unresolved.String = Blob;
4693 UnresolvedModuleRefs.push_back(Unresolved);
4694 break;
4695 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 }
4697 }
4698}
4699
4700/// \brief Parse the record that corresponds to a LangOptions data
4701/// structure.
4702///
4703/// This routine parses the language options from the AST file and then gives
4704/// them to the AST listener if one is set.
4705///
4706/// \returns true if the listener deems the file unacceptable, false otherwise.
4707bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4708 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004709 ASTReaderListener &Listener,
4710 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 LangOptions LangOpts;
4712 unsigned Idx = 0;
4713#define LANGOPT(Name, Bits, Default, Description) \
4714 LangOpts.Name = Record[Idx++];
4715#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4716 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4717#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004718#define SANITIZER(NAME, ID) \
4719 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004720#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004721
4722 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4723 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4724 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4725
4726 unsigned Length = Record[Idx++];
4727 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4728 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004729
4730 Idx += Length;
4731
4732 // Comment options.
4733 for (unsigned N = Record[Idx++]; N; --N) {
4734 LangOpts.CommentOpts.BlockCommandNames.push_back(
4735 ReadString(Record, Idx));
4736 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004737 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004738
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004739 return Listener.ReadLanguageOptions(LangOpts, Complain,
4740 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004741}
4742
4743bool ASTReader::ParseTargetOptions(const RecordData &Record,
4744 bool Complain,
4745 ASTReaderListener &Listener) {
4746 unsigned Idx = 0;
4747 TargetOptions TargetOpts;
4748 TargetOpts.Triple = ReadString(Record, Idx);
4749 TargetOpts.CPU = ReadString(Record, Idx);
4750 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 for (unsigned N = Record[Idx++]; N; --N) {
4752 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4753 }
4754 for (unsigned N = Record[Idx++]; N; --N) {
4755 TargetOpts.Features.push_back(ReadString(Record, Idx));
4756 }
4757
4758 return Listener.ReadTargetOptions(TargetOpts, Complain);
4759}
4760
4761bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4762 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004763 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004765#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004766#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004767 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004768#include "clang/Basic/DiagnosticOptions.def"
4769
Richard Smith3be1cb22014-08-07 00:24:21 +00004770 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004771 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004772 for (unsigned N = Record[Idx++]; N; --N)
4773 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004774
4775 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4776}
4777
4778bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4779 ASTReaderListener &Listener) {
4780 FileSystemOptions FSOpts;
4781 unsigned Idx = 0;
4782 FSOpts.WorkingDir = ReadString(Record, Idx);
4783 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4784}
4785
4786bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4787 bool Complain,
4788 ASTReaderListener &Listener) {
4789 HeaderSearchOptions HSOpts;
4790 unsigned Idx = 0;
4791 HSOpts.Sysroot = ReadString(Record, Idx);
4792
4793 // Include entries.
4794 for (unsigned N = Record[Idx++]; N; --N) {
4795 std::string Path = ReadString(Record, Idx);
4796 frontend::IncludeDirGroup Group
4797 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 bool IsFramework = Record[Idx++];
4799 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004801 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 }
4803
4804 // System header prefixes.
4805 for (unsigned N = Record[Idx++]; N; --N) {
4806 std::string Prefix = ReadString(Record, Idx);
4807 bool IsSystemHeader = Record[Idx++];
4808 HSOpts.SystemHeaderPrefixes.push_back(
4809 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4810 }
4811
4812 HSOpts.ResourceDir = ReadString(Record, Idx);
4813 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004814 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 HSOpts.DisableModuleHash = Record[Idx++];
4816 HSOpts.UseBuiltinIncludes = Record[Idx++];
4817 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4818 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4819 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004820 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004821
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004822 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4823 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004824}
4825
4826bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4827 bool Complain,
4828 ASTReaderListener &Listener,
4829 std::string &SuggestedPredefines) {
4830 PreprocessorOptions PPOpts;
4831 unsigned Idx = 0;
4832
4833 // Macro definitions/undefs
4834 for (unsigned N = Record[Idx++]; N; --N) {
4835 std::string Macro = ReadString(Record, Idx);
4836 bool IsUndef = Record[Idx++];
4837 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4838 }
4839
4840 // Includes
4841 for (unsigned N = Record[Idx++]; N; --N) {
4842 PPOpts.Includes.push_back(ReadString(Record, Idx));
4843 }
4844
4845 // Macro Includes
4846 for (unsigned N = Record[Idx++]; N; --N) {
4847 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4848 }
4849
4850 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004851 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4853 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4854 PPOpts.ObjCXXARCStandardLibrary =
4855 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4856 SuggestedPredefines.clear();
4857 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4858 SuggestedPredefines);
4859}
4860
4861std::pair<ModuleFile *, unsigned>
4862ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4863 GlobalPreprocessedEntityMapType::iterator
4864 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4865 assert(I != GlobalPreprocessedEntityMap.end() &&
4866 "Corrupted global preprocessed entity map");
4867 ModuleFile *M = I->second;
4868 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4869 return std::make_pair(M, LocalIndex);
4870}
4871
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004872llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004873ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4874 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4875 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4876 Mod.NumPreprocessedEntities);
4877
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004878 return llvm::make_range(PreprocessingRecord::iterator(),
4879 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004880}
4881
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004882llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004883ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004884 return llvm::make_range(
4885 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4886 ModuleDeclIterator(this, &Mod,
4887 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004888}
4889
4890PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4891 PreprocessedEntityID PPID = Index+1;
4892 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4893 ModuleFile &M = *PPInfo.first;
4894 unsigned LocalIndex = PPInfo.second;
4895 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4896
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 if (!PP.getPreprocessingRecord()) {
4898 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004899 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 }
4901
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004902 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4903 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4904
4905 llvm::BitstreamEntry Entry =
4906 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4907 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004908 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004909
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 // Read the record.
4911 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4912 ReadSourceLocation(M, PPOffs.End));
4913 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004914 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 RecordData Record;
4916 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004917 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4918 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 switch (RecType) {
4920 case PPD_MACRO_EXPANSION: {
4921 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004922 IdentifierInfo *Name = nullptr;
4923 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 if (isBuiltin)
4925 Name = getLocalIdentifier(M, Record[1]);
4926 else {
4927 PreprocessedEntityID
4928 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4929 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4930 }
4931
4932 MacroExpansion *ME;
4933 if (isBuiltin)
4934 ME = new (PPRec) MacroExpansion(Name, Range);
4935 else
4936 ME = new (PPRec) MacroExpansion(Def, Range);
4937
4938 return ME;
4939 }
4940
4941 case PPD_MACRO_DEFINITION: {
4942 // Decode the identifier info and then check again; if the macro is
4943 // still defined and associated with the identifier,
4944 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4945 MacroDefinition *MD
4946 = new (PPRec) MacroDefinition(II, Range);
4947
4948 if (DeserializationListener)
4949 DeserializationListener->MacroDefinitionRead(PPID, MD);
4950
4951 return MD;
4952 }
4953
4954 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004955 const char *FullFileNameStart = Blob.data() + Record[0];
4956 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004957 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 if (!FullFileName.empty())
4959 File = PP.getFileManager().getFile(FullFileName);
4960
4961 // FIXME: Stable encoding
4962 InclusionDirective::InclusionKind Kind
4963 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4964 InclusionDirective *ID
4965 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004966 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 Record[1], Record[3],
4968 File,
4969 Range);
4970 return ID;
4971 }
4972 }
4973
4974 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4975}
4976
4977/// \brief \arg SLocMapI points at a chunk of a module that contains no
4978/// preprocessed entities or the entities it contains are not the ones we are
4979/// looking for. Find the next module that contains entities and return the ID
4980/// of the first entry.
4981PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4982 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4983 ++SLocMapI;
4984 for (GlobalSLocOffsetMapType::const_iterator
4985 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4986 ModuleFile &M = *SLocMapI->second;
4987 if (M.NumPreprocessedEntities)
4988 return M.BasePreprocessedEntityID;
4989 }
4990
4991 return getTotalNumPreprocessedEntities();
4992}
4993
4994namespace {
4995
4996template <unsigned PPEntityOffset::*PPLoc>
4997struct PPEntityComp {
4998 const ASTReader &Reader;
4999 ModuleFile &M;
5000
5001 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5002
5003 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5004 SourceLocation LHS = getLoc(L);
5005 SourceLocation RHS = getLoc(R);
5006 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5007 }
5008
5009 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5010 SourceLocation LHS = getLoc(L);
5011 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5012 }
5013
5014 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5015 SourceLocation RHS = getLoc(R);
5016 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5017 }
5018
5019 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5020 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5021 }
5022};
5023
5024}
5025
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005026PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5027 bool EndsAfter) const {
5028 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 return getTotalNumPreprocessedEntities();
5030
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005031 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5032 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5034 "Corrupted global sloc offset map");
5035
5036 if (SLocMapI->second->NumPreprocessedEntities == 0)
5037 return findNextPreprocessedEntity(SLocMapI);
5038
5039 ModuleFile &M = *SLocMapI->second;
5040 typedef const PPEntityOffset *pp_iterator;
5041 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5042 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5043
5044 size_t Count = M.NumPreprocessedEntities;
5045 size_t Half;
5046 pp_iterator First = pp_begin;
5047 pp_iterator PPI;
5048
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005049 if (EndsAfter) {
5050 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5051 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5052 } else {
5053 // Do a binary search manually instead of using std::lower_bound because
5054 // The end locations of entities may be unordered (when a macro expansion
5055 // is inside another macro argument), but for this case it is not important
5056 // whether we get the first macro expansion or its containing macro.
5057 while (Count > 0) {
5058 Half = Count / 2;
5059 PPI = First;
5060 std::advance(PPI, Half);
5061 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5062 Loc)) {
5063 First = PPI;
5064 ++First;
5065 Count = Count - Half - 1;
5066 } else
5067 Count = Half;
5068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 }
5070
5071 if (PPI == pp_end)
5072 return findNextPreprocessedEntity(SLocMapI);
5073
5074 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5075}
5076
Guy Benyei11169dd2012-12-18 14:30:41 +00005077/// \brief Returns a pair of [Begin, End) indices of preallocated
5078/// preprocessed entities that \arg Range encompasses.
5079std::pair<unsigned, unsigned>
5080 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5081 if (Range.isInvalid())
5082 return std::make_pair(0,0);
5083 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5084
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005085 PreprocessedEntityID BeginID =
5086 findPreprocessedEntity(Range.getBegin(), false);
5087 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 return std::make_pair(BeginID, EndID);
5089}
5090
5091/// \brief Optionally returns true or false if the preallocated preprocessed
5092/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005093Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 FileID FID) {
5095 if (FID.isInvalid())
5096 return false;
5097
5098 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5099 ModuleFile &M = *PPInfo.first;
5100 unsigned LocalIndex = PPInfo.second;
5101 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5102
5103 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5104 if (Loc.isInvalid())
5105 return false;
5106
5107 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5108 return true;
5109 else
5110 return false;
5111}
5112
5113namespace {
5114 /// \brief Visitor used to search for information about a header file.
5115 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 const FileEntry *FE;
5117
David Blaikie05785d12013-02-20 22:23:23 +00005118 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005119
5120 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005121 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5122 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005123
5124 static bool visit(ModuleFile &M, void *UserData) {
5125 HeaderFileInfoVisitor *This
5126 = static_cast<HeaderFileInfoVisitor *>(UserData);
5127
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 HeaderFileInfoLookupTable *Table
5129 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5130 if (!Table)
5131 return false;
5132
5133 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005134 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 if (Pos == Table->end())
5136 return false;
5137
5138 This->HFI = *Pos;
5139 return true;
5140 }
5141
David Blaikie05785d12013-02-20 22:23:23 +00005142 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 };
5144}
5145
5146HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005147 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005149 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005151
5152 return HeaderFileInfo();
5153}
5154
5155void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5156 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005157 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5159 ModuleFile &F = *(*I);
5160 unsigned Idx = 0;
5161 DiagStates.clear();
5162 assert(!Diag.DiagStates.empty());
5163 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5164 while (Idx < F.PragmaDiagMappings.size()) {
5165 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5166 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5167 if (DiagStateID != 0) {
5168 Diag.DiagStatePoints.push_back(
5169 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5170 FullSourceLoc(Loc, SourceMgr)));
5171 continue;
5172 }
5173
5174 assert(DiagStateID == 0);
5175 // A new DiagState was created here.
5176 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5177 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5178 DiagStates.push_back(NewState);
5179 Diag.DiagStatePoints.push_back(
5180 DiagnosticsEngine::DiagStatePoint(NewState,
5181 FullSourceLoc(Loc, SourceMgr)));
5182 while (1) {
5183 assert(Idx < F.PragmaDiagMappings.size() &&
5184 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5185 if (Idx >= F.PragmaDiagMappings.size()) {
5186 break; // Something is messed up but at least avoid infinite loop in
5187 // release build.
5188 }
5189 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5190 if (DiagID == (unsigned)-1) {
5191 break; // no more diag/map pairs for this location.
5192 }
Alp Tokerc726c362014-06-10 09:31:37 +00005193 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5194 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5195 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 }
5197 }
5198 }
5199}
5200
5201/// \brief Get the correct cursor and offset for loading a type.
5202ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5203 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5204 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5205 ModuleFile *M = I->second;
5206 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5207}
5208
5209/// \brief Read and return the type with the given index..
5210///
5211/// The index is the type ID, shifted and minus the number of predefs. This
5212/// routine actually reads the record corresponding to the type at the given
5213/// location. It is a helper routine for GetType, which deals with reading type
5214/// IDs.
5215QualType ASTReader::readTypeRecord(unsigned Index) {
5216 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005217 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005218
5219 // Keep track of where we are in the stream, then jump back there
5220 // after reading this type.
5221 SavedStreamPosition SavedPosition(DeclsCursor);
5222
5223 ReadingKindTracker ReadingKind(Read_Type, *this);
5224
5225 // Note that we are loading a type record.
5226 Deserializing AType(this);
5227
5228 unsigned Idx = 0;
5229 DeclsCursor.JumpToBit(Loc.Offset);
5230 RecordData Record;
5231 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005232 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case TYPE_EXT_QUAL: {
5234 if (Record.size() != 2) {
5235 Error("Incorrect encoding of extended qualifier type");
5236 return QualType();
5237 }
5238 QualType Base = readType(*Loc.F, Record, Idx);
5239 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5240 return Context.getQualifiedType(Base, Quals);
5241 }
5242
5243 case TYPE_COMPLEX: {
5244 if (Record.size() != 1) {
5245 Error("Incorrect encoding of complex type");
5246 return QualType();
5247 }
5248 QualType ElemType = readType(*Loc.F, Record, Idx);
5249 return Context.getComplexType(ElemType);
5250 }
5251
5252 case TYPE_POINTER: {
5253 if (Record.size() != 1) {
5254 Error("Incorrect encoding of pointer type");
5255 return QualType();
5256 }
5257 QualType PointeeType = readType(*Loc.F, Record, Idx);
5258 return Context.getPointerType(PointeeType);
5259 }
5260
Reid Kleckner8a365022013-06-24 17:51:48 +00005261 case TYPE_DECAYED: {
5262 if (Record.size() != 1) {
5263 Error("Incorrect encoding of decayed type");
5264 return QualType();
5265 }
5266 QualType OriginalType = readType(*Loc.F, Record, Idx);
5267 QualType DT = Context.getAdjustedParameterType(OriginalType);
5268 if (!isa<DecayedType>(DT))
5269 Error("Decayed type does not decay");
5270 return DT;
5271 }
5272
Reid Kleckner0503a872013-12-05 01:23:43 +00005273 case TYPE_ADJUSTED: {
5274 if (Record.size() != 2) {
5275 Error("Incorrect encoding of adjusted type");
5276 return QualType();
5277 }
5278 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5279 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5280 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5281 }
5282
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case TYPE_BLOCK_POINTER: {
5284 if (Record.size() != 1) {
5285 Error("Incorrect encoding of block pointer type");
5286 return QualType();
5287 }
5288 QualType PointeeType = readType(*Loc.F, Record, Idx);
5289 return Context.getBlockPointerType(PointeeType);
5290 }
5291
5292 case TYPE_LVALUE_REFERENCE: {
5293 if (Record.size() != 2) {
5294 Error("Incorrect encoding of lvalue reference type");
5295 return QualType();
5296 }
5297 QualType PointeeType = readType(*Loc.F, Record, Idx);
5298 return Context.getLValueReferenceType(PointeeType, Record[1]);
5299 }
5300
5301 case TYPE_RVALUE_REFERENCE: {
5302 if (Record.size() != 1) {
5303 Error("Incorrect encoding of rvalue reference type");
5304 return QualType();
5305 }
5306 QualType PointeeType = readType(*Loc.F, Record, Idx);
5307 return Context.getRValueReferenceType(PointeeType);
5308 }
5309
5310 case TYPE_MEMBER_POINTER: {
5311 if (Record.size() != 2) {
5312 Error("Incorrect encoding of member pointer type");
5313 return QualType();
5314 }
5315 QualType PointeeType = readType(*Loc.F, Record, Idx);
5316 QualType ClassType = readType(*Loc.F, Record, Idx);
5317 if (PointeeType.isNull() || ClassType.isNull())
5318 return QualType();
5319
5320 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5321 }
5322
5323 case TYPE_CONSTANT_ARRAY: {
5324 QualType ElementType = readType(*Loc.F, Record, Idx);
5325 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5326 unsigned IndexTypeQuals = Record[2];
5327 unsigned Idx = 3;
5328 llvm::APInt Size = ReadAPInt(Record, Idx);
5329 return Context.getConstantArrayType(ElementType, Size,
5330 ASM, IndexTypeQuals);
5331 }
5332
5333 case TYPE_INCOMPLETE_ARRAY: {
5334 QualType ElementType = readType(*Loc.F, Record, Idx);
5335 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5336 unsigned IndexTypeQuals = Record[2];
5337 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5338 }
5339
5340 case TYPE_VARIABLE_ARRAY: {
5341 QualType ElementType = readType(*Loc.F, Record, Idx);
5342 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5343 unsigned IndexTypeQuals = Record[2];
5344 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5345 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5346 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5347 ASM, IndexTypeQuals,
5348 SourceRange(LBLoc, RBLoc));
5349 }
5350
5351 case TYPE_VECTOR: {
5352 if (Record.size() != 3) {
5353 Error("incorrect encoding of vector type in AST file");
5354 return QualType();
5355 }
5356
5357 QualType ElementType = readType(*Loc.F, Record, Idx);
5358 unsigned NumElements = Record[1];
5359 unsigned VecKind = Record[2];
5360 return Context.getVectorType(ElementType, NumElements,
5361 (VectorType::VectorKind)VecKind);
5362 }
5363
5364 case TYPE_EXT_VECTOR: {
5365 if (Record.size() != 3) {
5366 Error("incorrect encoding of extended vector type in AST file");
5367 return QualType();
5368 }
5369
5370 QualType ElementType = readType(*Loc.F, Record, Idx);
5371 unsigned NumElements = Record[1];
5372 return Context.getExtVectorType(ElementType, NumElements);
5373 }
5374
5375 case TYPE_FUNCTION_NO_PROTO: {
5376 if (Record.size() != 6) {
5377 Error("incorrect encoding of no-proto function type");
5378 return QualType();
5379 }
5380 QualType ResultType = readType(*Loc.F, Record, Idx);
5381 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5382 (CallingConv)Record[4], Record[5]);
5383 return Context.getFunctionNoProtoType(ResultType, Info);
5384 }
5385
5386 case TYPE_FUNCTION_PROTO: {
5387 QualType ResultType = readType(*Loc.F, Record, Idx);
5388
5389 FunctionProtoType::ExtProtoInfo EPI;
5390 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5391 /*hasregparm*/ Record[2],
5392 /*regparm*/ Record[3],
5393 static_cast<CallingConv>(Record[4]),
5394 /*produces*/ Record[5]);
5395
5396 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005397
5398 EPI.Variadic = Record[Idx++];
5399 EPI.HasTrailingReturn = Record[Idx++];
5400 EPI.TypeQuals = Record[Idx++];
5401 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005402 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005403 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005404
5405 unsigned NumParams = Record[Idx++];
5406 SmallVector<QualType, 16> ParamTypes;
5407 for (unsigned I = 0; I != NumParams; ++I)
5408 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5409
Jordan Rose5c382722013-03-08 21:51:21 +00005410 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 }
5412
5413 case TYPE_UNRESOLVED_USING: {
5414 unsigned Idx = 0;
5415 return Context.getTypeDeclType(
5416 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5417 }
5418
5419 case TYPE_TYPEDEF: {
5420 if (Record.size() != 2) {
5421 Error("incorrect encoding of typedef type");
5422 return QualType();
5423 }
5424 unsigned Idx = 0;
5425 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5426 QualType Canonical = readType(*Loc.F, Record, Idx);
5427 if (!Canonical.isNull())
5428 Canonical = Context.getCanonicalType(Canonical);
5429 return Context.getTypedefType(Decl, Canonical);
5430 }
5431
5432 case TYPE_TYPEOF_EXPR:
5433 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5434
5435 case TYPE_TYPEOF: {
5436 if (Record.size() != 1) {
5437 Error("incorrect encoding of typeof(type) in AST file");
5438 return QualType();
5439 }
5440 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5441 return Context.getTypeOfType(UnderlyingType);
5442 }
5443
5444 case TYPE_DECLTYPE: {
5445 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5446 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5447 }
5448
5449 case TYPE_UNARY_TRANSFORM: {
5450 QualType BaseType = readType(*Loc.F, Record, Idx);
5451 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5452 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5453 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5454 }
5455
Richard Smith74aeef52013-04-26 16:15:35 +00005456 case TYPE_AUTO: {
5457 QualType Deduced = readType(*Loc.F, Record, Idx);
5458 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005459 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005460 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005462
5463 case TYPE_RECORD: {
5464 if (Record.size() != 2) {
5465 Error("incorrect encoding of record type");
5466 return QualType();
5467 }
5468 unsigned Idx = 0;
5469 bool IsDependent = Record[Idx++];
5470 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5471 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5472 QualType T = Context.getRecordType(RD);
5473 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5474 return T;
5475 }
5476
5477 case TYPE_ENUM: {
5478 if (Record.size() != 2) {
5479 Error("incorrect encoding of enum type");
5480 return QualType();
5481 }
5482 unsigned Idx = 0;
5483 bool IsDependent = Record[Idx++];
5484 QualType T
5485 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5486 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5487 return T;
5488 }
5489
5490 case TYPE_ATTRIBUTED: {
5491 if (Record.size() != 3) {
5492 Error("incorrect encoding of attributed type");
5493 return QualType();
5494 }
5495 QualType modifiedType = readType(*Loc.F, Record, Idx);
5496 QualType equivalentType = readType(*Loc.F, Record, Idx);
5497 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5498 return Context.getAttributedType(kind, modifiedType, equivalentType);
5499 }
5500
5501 case TYPE_PAREN: {
5502 if (Record.size() != 1) {
5503 Error("incorrect encoding of paren type");
5504 return QualType();
5505 }
5506 QualType InnerType = readType(*Loc.F, Record, Idx);
5507 return Context.getParenType(InnerType);
5508 }
5509
5510 case TYPE_PACK_EXPANSION: {
5511 if (Record.size() != 2) {
5512 Error("incorrect encoding of pack expansion type");
5513 return QualType();
5514 }
5515 QualType Pattern = readType(*Loc.F, Record, Idx);
5516 if (Pattern.isNull())
5517 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005518 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 if (Record[1])
5520 NumExpansions = Record[1] - 1;
5521 return Context.getPackExpansionType(Pattern, NumExpansions);
5522 }
5523
5524 case TYPE_ELABORATED: {
5525 unsigned Idx = 0;
5526 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5527 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5528 QualType NamedType = readType(*Loc.F, Record, Idx);
5529 return Context.getElaboratedType(Keyword, NNS, NamedType);
5530 }
5531
5532 case TYPE_OBJC_INTERFACE: {
5533 unsigned Idx = 0;
5534 ObjCInterfaceDecl *ItfD
5535 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5536 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5537 }
5538
5539 case TYPE_OBJC_OBJECT: {
5540 unsigned Idx = 0;
5541 QualType Base = readType(*Loc.F, Record, Idx);
5542 unsigned NumProtos = Record[Idx++];
5543 SmallVector<ObjCProtocolDecl*, 4> Protos;
5544 for (unsigned I = 0; I != NumProtos; ++I)
5545 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5546 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5547 }
5548
5549 case TYPE_OBJC_OBJECT_POINTER: {
5550 unsigned Idx = 0;
5551 QualType Pointee = readType(*Loc.F, Record, Idx);
5552 return Context.getObjCObjectPointerType(Pointee);
5553 }
5554
5555 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5556 unsigned Idx = 0;
5557 QualType Parm = readType(*Loc.F, Record, Idx);
5558 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005559 return Context.getSubstTemplateTypeParmType(
5560 cast<TemplateTypeParmType>(Parm),
5561 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 }
5563
5564 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5565 unsigned Idx = 0;
5566 QualType Parm = readType(*Loc.F, Record, Idx);
5567 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5568 return Context.getSubstTemplateTypeParmPackType(
5569 cast<TemplateTypeParmType>(Parm),
5570 ArgPack);
5571 }
5572
5573 case TYPE_INJECTED_CLASS_NAME: {
5574 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5575 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5576 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5577 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005578 const Type *T = nullptr;
5579 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5580 if (const Type *Existing = DI->getTypeForDecl()) {
5581 T = Existing;
5582 break;
5583 }
5584 }
5585 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005586 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005587 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5588 DI->setTypeForDecl(T);
5589 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005590 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005591 }
5592
5593 case TYPE_TEMPLATE_TYPE_PARM: {
5594 unsigned Idx = 0;
5595 unsigned Depth = Record[Idx++];
5596 unsigned Index = Record[Idx++];
5597 bool Pack = Record[Idx++];
5598 TemplateTypeParmDecl *D
5599 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5600 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5601 }
5602
5603 case TYPE_DEPENDENT_NAME: {
5604 unsigned Idx = 0;
5605 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5606 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5607 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5608 QualType Canon = readType(*Loc.F, Record, Idx);
5609 if (!Canon.isNull())
5610 Canon = Context.getCanonicalType(Canon);
5611 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5612 }
5613
5614 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5615 unsigned Idx = 0;
5616 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5617 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5618 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5619 unsigned NumArgs = Record[Idx++];
5620 SmallVector<TemplateArgument, 8> Args;
5621 Args.reserve(NumArgs);
5622 while (NumArgs--)
5623 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5624 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5625 Args.size(), Args.data());
5626 }
5627
5628 case TYPE_DEPENDENT_SIZED_ARRAY: {
5629 unsigned Idx = 0;
5630
5631 // ArrayType
5632 QualType ElementType = readType(*Loc.F, Record, Idx);
5633 ArrayType::ArraySizeModifier ASM
5634 = (ArrayType::ArraySizeModifier)Record[Idx++];
5635 unsigned IndexTypeQuals = Record[Idx++];
5636
5637 // DependentSizedArrayType
5638 Expr *NumElts = ReadExpr(*Loc.F);
5639 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5640
5641 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5642 IndexTypeQuals, Brackets);
5643 }
5644
5645 case TYPE_TEMPLATE_SPECIALIZATION: {
5646 unsigned Idx = 0;
5647 bool IsDependent = Record[Idx++];
5648 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5649 SmallVector<TemplateArgument, 8> Args;
5650 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5651 QualType Underlying = readType(*Loc.F, Record, Idx);
5652 QualType T;
5653 if (Underlying.isNull())
5654 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5655 Args.size());
5656 else
5657 T = Context.getTemplateSpecializationType(Name, Args.data(),
5658 Args.size(), Underlying);
5659 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5660 return T;
5661 }
5662
5663 case TYPE_ATOMIC: {
5664 if (Record.size() != 1) {
5665 Error("Incorrect encoding of atomic type");
5666 return QualType();
5667 }
5668 QualType ValueType = readType(*Loc.F, Record, Idx);
5669 return Context.getAtomicType(ValueType);
5670 }
5671 }
5672 llvm_unreachable("Invalid TypeCode!");
5673}
5674
Richard Smith564417a2014-03-20 21:47:22 +00005675void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5676 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005677 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005678 const RecordData &Record, unsigned &Idx) {
5679 ExceptionSpecificationType EST =
5680 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005681 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005682 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005683 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005684 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005685 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005686 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005687 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005688 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005689 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5690 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005691 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005692 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005693 }
5694}
5695
Guy Benyei11169dd2012-12-18 14:30:41 +00005696class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5697 ASTReader &Reader;
5698 ModuleFile &F;
5699 const ASTReader::RecordData &Record;
5700 unsigned &Idx;
5701
5702 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5703 unsigned &I) {
5704 return Reader.ReadSourceLocation(F, R, I);
5705 }
5706
5707 template<typename T>
5708 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5709 return Reader.ReadDeclAs<T>(F, Record, Idx);
5710 }
5711
5712public:
5713 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5714 const ASTReader::RecordData &Record, unsigned &Idx)
5715 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5716 { }
5717
5718 // We want compile-time assurance that we've enumerated all of
5719 // these, so unfortunately we have to declare them first, then
5720 // define them out-of-line.
5721#define ABSTRACT_TYPELOC(CLASS, PARENT)
5722#define TYPELOC(CLASS, PARENT) \
5723 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5724#include "clang/AST/TypeLocNodes.def"
5725
5726 void VisitFunctionTypeLoc(FunctionTypeLoc);
5727 void VisitArrayTypeLoc(ArrayTypeLoc);
5728};
5729
5730void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5731 // nothing to do
5732}
5733void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5734 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5735 if (TL.needsExtraLocalData()) {
5736 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5737 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5738 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5739 TL.setModeAttr(Record[Idx++]);
5740 }
5741}
5742void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5743 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5744}
5745void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5746 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5747}
Reid Kleckner8a365022013-06-24 17:51:48 +00005748void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5749 // nothing to do
5750}
Reid Kleckner0503a872013-12-05 01:23:43 +00005751void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5752 // nothing to do
5753}
Guy Benyei11169dd2012-12-18 14:30:41 +00005754void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5755 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5756}
5757void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5758 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5759}
5760void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5761 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5762}
5763void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5764 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5765 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5766}
5767void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5768 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5769 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5770 if (Record[Idx++])
5771 TL.setSizeExpr(Reader.ReadExpr(F));
5772 else
Craig Toppera13603a2014-05-22 05:54:18 +00005773 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774}
5775void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5776 VisitArrayTypeLoc(TL);
5777}
5778void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5779 VisitArrayTypeLoc(TL);
5780}
5781void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5782 VisitArrayTypeLoc(TL);
5783}
5784void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5785 DependentSizedArrayTypeLoc TL) {
5786 VisitArrayTypeLoc(TL);
5787}
5788void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5789 DependentSizedExtVectorTypeLoc TL) {
5790 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5791}
5792void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5793 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5794}
5795void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5796 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5799 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5800 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5801 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5802 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005803 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5804 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 }
5806}
5807void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5808 VisitFunctionTypeLoc(TL);
5809}
5810void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5811 VisitFunctionTypeLoc(TL);
5812}
5813void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5814 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5815}
5816void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5817 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5818}
5819void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5820 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5821 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5822 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5823}
5824void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5825 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5826 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5827 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5828 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5829}
5830void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5831 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5832}
5833void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5834 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5835 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5836 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5837 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5838}
5839void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5840 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5841}
5842void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5843 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5844}
5845void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5846 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5847}
5848void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5849 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5850 if (TL.hasAttrOperand()) {
5851 SourceRange range;
5852 range.setBegin(ReadSourceLocation(Record, Idx));
5853 range.setEnd(ReadSourceLocation(Record, Idx));
5854 TL.setAttrOperandParensRange(range);
5855 }
5856 if (TL.hasAttrExprOperand()) {
5857 if (Record[Idx++])
5858 TL.setAttrExprOperand(Reader.ReadExpr(F));
5859 else
Craig Toppera13603a2014-05-22 05:54:18 +00005860 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 } else if (TL.hasAttrEnumOperand())
5862 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5863}
5864void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5865 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5866}
5867void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5868 SubstTemplateTypeParmTypeLoc TL) {
5869 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5870}
5871void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5872 SubstTemplateTypeParmPackTypeLoc TL) {
5873 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5874}
5875void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5876 TemplateSpecializationTypeLoc TL) {
5877 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5878 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5879 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5880 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5881 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5882 TL.setArgLocInfo(i,
5883 Reader.GetTemplateArgumentLocInfo(F,
5884 TL.getTypePtr()->getArg(i).getKind(),
5885 Record, Idx));
5886}
5887void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5888 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5889 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5890}
5891void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5892 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5893 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5894}
5895void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5896 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5899 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5900 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5901 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5902}
5903void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5904 DependentTemplateSpecializationTypeLoc TL) {
5905 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5906 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5907 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5908 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5909 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5910 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5911 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5912 TL.setArgLocInfo(I,
5913 Reader.GetTemplateArgumentLocInfo(F,
5914 TL.getTypePtr()->getArg(I).getKind(),
5915 Record, Idx));
5916}
5917void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5918 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5919}
5920void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5921 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5922}
5923void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5924 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5925 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5926 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5927 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5928 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5929}
5930void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5931 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5932}
5933void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5934 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5935 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5936 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5937}
5938
5939TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5940 const RecordData &Record,
5941 unsigned &Idx) {
5942 QualType InfoTy = readType(F, Record, Idx);
5943 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005944 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005945
5946 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5947 TypeLocReader TLR(*this, F, Record, Idx);
5948 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5949 TLR.Visit(TL);
5950 return TInfo;
5951}
5952
5953QualType ASTReader::GetType(TypeID ID) {
5954 unsigned FastQuals = ID & Qualifiers::FastMask;
5955 unsigned Index = ID >> Qualifiers::FastWidth;
5956
5957 if (Index < NUM_PREDEF_TYPE_IDS) {
5958 QualType T;
5959 switch ((PredefinedTypeIDs)Index) {
5960 case PREDEF_TYPE_NULL_ID: return QualType();
5961 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5962 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5963
5964 case PREDEF_TYPE_CHAR_U_ID:
5965 case PREDEF_TYPE_CHAR_S_ID:
5966 // FIXME: Check that the signedness of CharTy is correct!
5967 T = Context.CharTy;
5968 break;
5969
5970 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5971 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5972 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5973 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5974 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5975 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5976 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5977 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5978 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5979 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5980 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5981 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5982 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5983 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5984 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5985 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5986 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5987 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5988 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5989 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5990 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5991 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5992 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5993 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5994 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5995 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5996 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5997 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005998 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5999 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
6000 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
6001 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
6002 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
6003 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00006004 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006005 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
6007
6008 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6009 T = Context.getAutoRRefDeductType();
6010 break;
6011
6012 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6013 T = Context.ARCUnbridgedCastTy;
6014 break;
6015
6016 case PREDEF_TYPE_VA_LIST_TAG:
6017 T = Context.getVaListTagType();
6018 break;
6019
6020 case PREDEF_TYPE_BUILTIN_FN:
6021 T = Context.BuiltinFnTy;
6022 break;
6023 }
6024
6025 assert(!T.isNull() && "Unknown predefined type");
6026 return T.withFastQualifiers(FastQuals);
6027 }
6028
6029 Index -= NUM_PREDEF_TYPE_IDS;
6030 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6031 if (TypesLoaded[Index].isNull()) {
6032 TypesLoaded[Index] = readTypeRecord(Index);
6033 if (TypesLoaded[Index].isNull())
6034 return QualType();
6035
6036 TypesLoaded[Index]->setFromAST();
6037 if (DeserializationListener)
6038 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6039 TypesLoaded[Index]);
6040 }
6041
6042 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6043}
6044
6045QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6046 return GetType(getGlobalTypeID(F, LocalID));
6047}
6048
6049serialization::TypeID
6050ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6051 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6052 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6053
6054 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6055 return LocalID;
6056
6057 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6058 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6059 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6060
6061 unsigned GlobalIndex = LocalIndex + I->second;
6062 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6063}
6064
6065TemplateArgumentLocInfo
6066ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6067 TemplateArgument::ArgKind Kind,
6068 const RecordData &Record,
6069 unsigned &Index) {
6070 switch (Kind) {
6071 case TemplateArgument::Expression:
6072 return ReadExpr(F);
6073 case TemplateArgument::Type:
6074 return GetTypeSourceInfo(F, Record, Index);
6075 case TemplateArgument::Template: {
6076 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6077 Index);
6078 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6079 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6080 SourceLocation());
6081 }
6082 case TemplateArgument::TemplateExpansion: {
6083 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6084 Index);
6085 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6086 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6087 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6088 EllipsisLoc);
6089 }
6090 case TemplateArgument::Null:
6091 case TemplateArgument::Integral:
6092 case TemplateArgument::Declaration:
6093 case TemplateArgument::NullPtr:
6094 case TemplateArgument::Pack:
6095 // FIXME: Is this right?
6096 return TemplateArgumentLocInfo();
6097 }
6098 llvm_unreachable("unexpected template argument loc");
6099}
6100
6101TemplateArgumentLoc
6102ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6103 const RecordData &Record, unsigned &Index) {
6104 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6105
6106 if (Arg.getKind() == TemplateArgument::Expression) {
6107 if (Record[Index++]) // bool InfoHasSameExpr.
6108 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6109 }
6110 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6111 Record, Index));
6112}
6113
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006114const ASTTemplateArgumentListInfo*
6115ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6116 const RecordData &Record,
6117 unsigned &Index) {
6118 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6119 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6120 unsigned NumArgsAsWritten = Record[Index++];
6121 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6122 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6123 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6124 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6125}
6126
Guy Benyei11169dd2012-12-18 14:30:41 +00006127Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6128 return GetDecl(ID);
6129}
6130
Richard Smith50895422015-01-31 03:04:55 +00006131template<typename TemplateSpecializationDecl>
6132static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6133 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6134 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6135}
6136
Richard Smith053f6c62014-05-16 23:01:30 +00006137void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006138 if (NumCurrentElementsDeserializing) {
6139 // We arrange to not care about the complete redeclaration chain while we're
6140 // deserializing. Just remember that the AST has marked this one as complete
6141 // but that it's not actually complete yet, so we know we still need to
6142 // complete it later.
6143 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6144 return;
6145 }
6146
Richard Smith053f6c62014-05-16 23:01:30 +00006147 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6148
Richard Smith053f6c62014-05-16 23:01:30 +00006149 // If this is a named declaration, complete it by looking it up
6150 // within its context.
6151 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006152 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006153 // all mergeable entities within it.
6154 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6155 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6156 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6157 auto *II = Name.getAsIdentifierInfo();
6158 if (isa<TranslationUnitDecl>(DC) && II) {
6159 // Outside of C++, we don't have a lookup table for the TU, so update
6160 // the identifier instead. In C++, either way should work fine.
6161 if (II->isOutOfDate())
6162 updateOutOfDateIdentifier(*II);
6163 } else
6164 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006165 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6166 // FIXME: It'd be nice to do something a bit more targeted here.
6167 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006168 }
6169 }
Richard Smith50895422015-01-31 03:04:55 +00006170
6171 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6172 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6173 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6174 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6175 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6176 if (auto *Template = FD->getPrimaryTemplate())
6177 Template->LoadLazySpecializations();
6178 }
Richard Smith053f6c62014-05-16 23:01:30 +00006179}
6180
Richard Smithcd45dbc2014-04-19 03:48:30 +00006181uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6182 const RecordData &Record,
6183 unsigned &Idx) {
6184 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6185 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006187 }
6188
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 unsigned LocalID = Record[Idx++];
6190 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6191}
6192
6193CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6194 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006195 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 SavedStreamPosition SavedPosition(Cursor);
6197 Cursor.JumpToBit(Loc.Offset);
6198 ReadingKindTracker ReadingKind(Read_Decl, *this);
6199 RecordData Record;
6200 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006201 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006203 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006204 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 }
6206
6207 unsigned Idx = 0;
6208 unsigned NumBases = Record[Idx++];
6209 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6210 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6211 for (unsigned I = 0; I != NumBases; ++I)
6212 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6213 return Bases;
6214}
6215
6216serialization::DeclID
6217ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6218 if (LocalID < NUM_PREDEF_DECL_IDS)
6219 return LocalID;
6220
6221 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6222 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6223 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6224
6225 return LocalID + I->second;
6226}
6227
6228bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6229 ModuleFile &M) const {
6230 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6231 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6232 return &M == I->second;
6233}
6234
Douglas Gregor9f782892013-01-21 15:25:38 +00006235ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006236 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006237 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6239 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6240 return I->second;
6241}
6242
6243SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6244 if (ID < NUM_PREDEF_DECL_IDS)
6245 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006246
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6248
6249 if (Index > DeclsLoaded.size()) {
6250 Error("declaration ID out-of-range for AST file");
6251 return SourceLocation();
6252 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006253
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 if (Decl *D = DeclsLoaded[Index])
6255 return D->getLocation();
6256
6257 unsigned RawLocation = 0;
6258 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6259 return ReadSourceLocation(*Rec.F, RawLocation);
6260}
6261
Richard Smithcd45dbc2014-04-19 03:48:30 +00006262Decl *ASTReader::GetExistingDecl(DeclID ID) {
6263 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006264 switch ((PredefinedDeclIDs)ID) {
6265 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006266 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006267
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6269 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006270
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 case PREDEF_DECL_OBJC_ID_ID:
6272 return Context.getObjCIdDecl();
6273
6274 case PREDEF_DECL_OBJC_SEL_ID:
6275 return Context.getObjCSelDecl();
6276
6277 case PREDEF_DECL_OBJC_CLASS_ID:
6278 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006279
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6281 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006282
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 case PREDEF_DECL_INT_128_ID:
6284 return Context.getInt128Decl();
6285
6286 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6287 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006288
Guy Benyei11169dd2012-12-18 14:30:41 +00006289 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6290 return Context.getObjCInstanceTypeDecl();
6291
6292 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6293 return Context.getBuiltinVaListDecl();
6294 }
6295 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006296
Guy Benyei11169dd2012-12-18 14:30:41 +00006297 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6298
6299 if (Index >= DeclsLoaded.size()) {
6300 assert(0 && "declaration ID out-of-range for AST file");
6301 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006302 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006304
6305 return DeclsLoaded[Index];
6306}
6307
6308Decl *ASTReader::GetDecl(DeclID ID) {
6309 if (ID < NUM_PREDEF_DECL_IDS)
6310 return GetExistingDecl(ID);
6311
6312 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6313
6314 if (Index >= DeclsLoaded.size()) {
6315 assert(0 && "declaration ID out-of-range for AST file");
6316 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006317 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006318 }
6319
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 if (!DeclsLoaded[Index]) {
6321 ReadDeclRecord(ID);
6322 if (DeserializationListener)
6323 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6324 }
6325
6326 return DeclsLoaded[Index];
6327}
6328
6329DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6330 DeclID GlobalID) {
6331 if (GlobalID < NUM_PREDEF_DECL_IDS)
6332 return GlobalID;
6333
6334 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6335 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6336 ModuleFile *Owner = I->second;
6337
6338 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6339 = M.GlobalToLocalDeclIDs.find(Owner);
6340 if (Pos == M.GlobalToLocalDeclIDs.end())
6341 return 0;
6342
6343 return GlobalID - Owner->BaseDeclID + Pos->second;
6344}
6345
6346serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6347 const RecordData &Record,
6348 unsigned &Idx) {
6349 if (Idx >= Record.size()) {
6350 Error("Corrupted AST file");
6351 return 0;
6352 }
6353
6354 return getGlobalDeclID(F, Record[Idx++]);
6355}
6356
6357/// \brief Resolve the offset of a statement into a statement.
6358///
6359/// This operation will read a new statement from the external
6360/// source each time it is called, and is meant to be used via a
6361/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6362Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6363 // Switch case IDs are per Decl.
6364 ClearSwitchCaseIDs();
6365
6366 // Offset here is a global offset across the entire chain.
6367 RecordLocation Loc = getLocalBitOffset(Offset);
6368 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6369 return ReadStmtFromStream(*Loc.F);
6370}
6371
6372namespace {
6373 class FindExternalLexicalDeclsVisitor {
6374 ASTReader &Reader;
6375 const DeclContext *DC;
6376 bool (*isKindWeWant)(Decl::Kind);
6377
6378 SmallVectorImpl<Decl*> &Decls;
6379 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6380
6381 public:
6382 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6383 bool (*isKindWeWant)(Decl::Kind),
6384 SmallVectorImpl<Decl*> &Decls)
6385 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6386 {
6387 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6388 PredefsVisited[I] = false;
6389 }
6390
6391 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6392 if (Preorder)
6393 return false;
6394
6395 FindExternalLexicalDeclsVisitor *This
6396 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6397
6398 ModuleFile::DeclContextInfosMap::iterator Info
6399 = M.DeclContextInfos.find(This->DC);
6400 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6401 return false;
6402
6403 // Load all of the declaration IDs
6404 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6405 *IDE = ID + Info->second.NumLexicalDecls;
6406 ID != IDE; ++ID) {
6407 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6408 continue;
6409
6410 // Don't add predefined declarations to the lexical context more
6411 // than once.
6412 if (ID->second < NUM_PREDEF_DECL_IDS) {
6413 if (This->PredefsVisited[ID->second])
6414 continue;
6415
6416 This->PredefsVisited[ID->second] = true;
6417 }
6418
6419 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6420 if (!This->DC->isDeclInLexicalTraversal(D))
6421 This->Decls.push_back(D);
6422 }
6423 }
6424
6425 return false;
6426 }
6427 };
6428}
6429
6430ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6431 bool (*isKindWeWant)(Decl::Kind),
6432 SmallVectorImpl<Decl*> &Decls) {
6433 // There might be lexical decls in multiple modules, for the TU at
6434 // least. Walk all of the modules in the order they were loaded.
6435 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6436 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6437 ++NumLexicalDeclContextsRead;
6438 return ELR_Success;
6439}
6440
6441namespace {
6442
6443class DeclIDComp {
6444 ASTReader &Reader;
6445 ModuleFile &Mod;
6446
6447public:
6448 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6449
6450 bool operator()(LocalDeclID L, LocalDeclID R) const {
6451 SourceLocation LHS = getLocation(L);
6452 SourceLocation RHS = getLocation(R);
6453 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6454 }
6455
6456 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6457 SourceLocation RHS = getLocation(R);
6458 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6459 }
6460
6461 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6462 SourceLocation LHS = getLocation(L);
6463 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6464 }
6465
6466 SourceLocation getLocation(LocalDeclID ID) const {
6467 return Reader.getSourceManager().getFileLoc(
6468 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6469 }
6470};
6471
6472}
6473
6474void ASTReader::FindFileRegionDecls(FileID File,
6475 unsigned Offset, unsigned Length,
6476 SmallVectorImpl<Decl *> &Decls) {
6477 SourceManager &SM = getSourceManager();
6478
6479 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6480 if (I == FileDeclIDs.end())
6481 return;
6482
6483 FileDeclsInfo &DInfo = I->second;
6484 if (DInfo.Decls.empty())
6485 return;
6486
6487 SourceLocation
6488 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6489 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6490
6491 DeclIDComp DIDComp(*this, *DInfo.Mod);
6492 ArrayRef<serialization::LocalDeclID>::iterator
6493 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6494 BeginLoc, DIDComp);
6495 if (BeginIt != DInfo.Decls.begin())
6496 --BeginIt;
6497
6498 // If we are pointing at a top-level decl inside an objc container, we need
6499 // to backtrack until we find it otherwise we will fail to report that the
6500 // region overlaps with an objc container.
6501 while (BeginIt != DInfo.Decls.begin() &&
6502 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6503 ->isTopLevelDeclInObjCContainer())
6504 --BeginIt;
6505
6506 ArrayRef<serialization::LocalDeclID>::iterator
6507 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6508 EndLoc, DIDComp);
6509 if (EndIt != DInfo.Decls.end())
6510 ++EndIt;
6511
6512 for (ArrayRef<serialization::LocalDeclID>::iterator
6513 DIt = BeginIt; DIt != EndIt; ++DIt)
6514 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6515}
6516
6517namespace {
6518 /// \brief ModuleFile visitor used to perform name lookup into a
6519 /// declaration context.
6520 class DeclContextNameLookupVisitor {
6521 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006522 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 DeclarationName Name;
6524 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006525 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006526
6527 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006528 DeclContextNameLookupVisitor(ASTReader &Reader,
6529 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006531 SmallVectorImpl<NamedDecl *> &Decls,
6532 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6533 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6534 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006535
6536 static bool visit(ModuleFile &M, void *UserData) {
6537 DeclContextNameLookupVisitor *This
6538 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6539
6540 // Check whether we have any visible declaration information for
6541 // this context in this module.
6542 ModuleFile::DeclContextInfosMap::iterator Info;
6543 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006544 for (auto *DC : This->Contexts) {
6545 Info = M.DeclContextInfos.find(DC);
6546 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 Info->second.NameLookupTableData) {
6548 FoundInfo = true;
6549 break;
6550 }
6551 }
6552
6553 if (!FoundInfo)
6554 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006555
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006557 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 Info->second.NameLookupTableData;
6559 ASTDeclContextNameLookupTable::iterator Pos
6560 = LookupTable->find(This->Name);
6561 if (Pos == LookupTable->end())
6562 return false;
6563
6564 bool FoundAnything = false;
6565 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6566 for (; Data.first != Data.second; ++Data.first) {
6567 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6568 if (!ND)
6569 continue;
6570
6571 if (ND->getDeclName() != This->Name) {
6572 // A name might be null because the decl's redeclarable part is
6573 // currently read before reading its name. The lookup is triggered by
6574 // building that decl (likely indirectly), and so it is later in the
6575 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006576 // FIXME: This should not happen; deserializing declarations should
6577 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 continue;
6579 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006580
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 // Record this declaration.
6582 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006583 if (This->DeclSet.insert(ND).second)
6584 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 }
6586
6587 return FoundAnything;
6588 }
6589 };
6590}
6591
Douglas Gregor9f782892013-01-21 15:25:38 +00006592/// \brief Retrieve the "definitive" module file for the definition of the
6593/// given declaration context, if there is one.
6594///
6595/// The "definitive" module file is the only place where we need to look to
6596/// find information about the declarations within the given declaration
6597/// context. For example, C++ and Objective-C classes, C structs/unions, and
6598/// Objective-C protocols, categories, and extensions are all defined in a
6599/// single place in the source code, so they have definitive module files
6600/// associated with them. C++ namespaces, on the other hand, can have
6601/// definitions in multiple different module files.
6602///
6603/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6604/// NDEBUG checking.
6605static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6606 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006607 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6608 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006609
Craig Toppera13603a2014-05-22 05:54:18 +00006610 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006611}
6612
Richard Smith9ce12e32013-02-07 03:30:24 +00006613bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006614ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6615 DeclarationName Name) {
6616 assert(DC->hasExternalVisibleStorage() &&
6617 "DeclContext has no visible decls in storage");
6618 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006619 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006620
Richard Smith8c913ec2014-08-14 02:21:01 +00006621 Deserializing LookupResults(this);
6622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006624 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006625
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 // Compute the declaration contexts we need to look into. Multiple such
6627 // declaration contexts occur when two declaration contexts from disjoint
6628 // modules get merged, e.g., when two namespaces with the same name are
6629 // independently defined in separate modules.
6630 SmallVector<const DeclContext *, 2> Contexts;
6631 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006634 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 if (Merged != MergedDecls.end()) {
6636 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6637 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6638 }
6639 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006640
6641 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006642 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006643
6644 // If we can definitively determine which module file to look into,
6645 // only look there. Otherwise, look in all module files.
6646 ModuleFile *Definitive;
6647 if (Contexts.size() == 1 &&
6648 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6649 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6650 } else {
6651 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6652 }
6653 };
6654
6655 LookUpInContexts(Contexts);
6656
6657 // If this might be an implicit special member function, then also search
6658 // all merged definitions of the surrounding class. We need to search them
6659 // individually, because finding an entity in one of them doesn't imply that
6660 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006661 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006662 auto Kind = Name.getNameKind();
6663 if (Kind == DeclarationName::CXXConstructorName ||
6664 Kind == DeclarationName::CXXDestructorName ||
6665 (Kind == DeclarationName::CXXOperatorName &&
6666 Name.getCXXOverloadedOperator() == OO_Equal)) {
6667 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006668 if (Merged != MergedLookups.end()) {
6669 for (unsigned I = 0; I != Merged->second.size(); ++I) {
Daniel Jasperc0b7c802015-02-18 14:13:46 +00006670 const DeclContext *Context = Merged->second[I];
6671 LookUpInContexts(Context);
Richard Smithe0612472014-11-21 05:16:13 +00006672 // We might have just added some more merged lookups. If so, our
6673 // iterator is now invalid, so grab a fresh one before continuing.
6674 Merged = MergedLookups.find(DC);
6675 }
6676 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006677 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006678 }
6679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 ++NumVisibleDeclContextsRead;
6681 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006682 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006683}
6684
6685namespace {
6686 /// \brief ModuleFile visitor used to retrieve all visible names in a
6687 /// declaration context.
6688 class DeclContextAllNamesVisitor {
6689 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006690 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006691 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006692 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006693 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006694
6695 public:
6696 DeclContextAllNamesVisitor(ASTReader &Reader,
6697 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006698 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006699 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006700
6701 static bool visit(ModuleFile &M, void *UserData) {
6702 DeclContextAllNamesVisitor *This
6703 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6704
6705 // Check whether we have any visible declaration information for
6706 // this context in this module.
6707 ModuleFile::DeclContextInfosMap::iterator Info;
6708 bool FoundInfo = false;
6709 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6710 Info = M.DeclContextInfos.find(This->Contexts[I]);
6711 if (Info != M.DeclContextInfos.end() &&
6712 Info->second.NameLookupTableData) {
6713 FoundInfo = true;
6714 break;
6715 }
6716 }
6717
6718 if (!FoundInfo)
6719 return false;
6720
Richard Smith52e3fba2014-03-11 07:17:35 +00006721 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006722 Info->second.NameLookupTableData;
6723 bool FoundAnything = false;
6724 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006725 I = LookupTable->data_begin(), E = LookupTable->data_end();
6726 I != E;
6727 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 ASTDeclContextNameLookupTrait::data_type Data = *I;
6729 for (; Data.first != Data.second; ++Data.first) {
6730 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6731 *Data.first);
6732 if (!ND)
6733 continue;
6734
6735 // Record this declaration.
6736 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006737 if (This->DeclSet.insert(ND).second)
6738 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006739 }
6740 }
6741
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006742 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 }
6744 };
6745}
6746
6747void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6748 if (!DC->hasExternalVisibleStorage())
6749 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006750 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006751
6752 // Compute the declaration contexts we need to look into. Multiple such
6753 // declaration contexts occur when two declaration contexts from disjoint
6754 // modules get merged, e.g., when two namespaces with the same name are
6755 // independently defined in separate modules.
6756 SmallVector<const DeclContext *, 2> Contexts;
6757 Contexts.push_back(DC);
6758
6759 if (DC->isNamespace()) {
6760 MergedDeclsMap::iterator Merged
6761 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6762 if (Merged != MergedDecls.end()) {
6763 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6764 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6765 }
6766 }
6767
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006768 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6769 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6771 ++NumVisibleDeclContextsRead;
6772
Craig Topper79be4cd2013-07-05 04:33:53 +00006773 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006774 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6775 }
6776 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6777}
6778
6779/// \brief Under non-PCH compilation the consumer receives the objc methods
6780/// before receiving the implementation, and codegen depends on this.
6781/// We simulate this by deserializing and passing to consumer the methods of the
6782/// implementation before passing the deserialized implementation decl.
6783static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6784 ASTConsumer *Consumer) {
6785 assert(ImplD && Consumer);
6786
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006787 for (auto *I : ImplD->methods())
6788 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006789
6790 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6791}
6792
6793void ASTReader::PassInterestingDeclsToConsumer() {
6794 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006795
6796 if (PassingDeclsToConsumer)
6797 return;
6798
6799 // Guard variable to avoid recursively redoing the process of passing
6800 // decls to consumer.
6801 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6802 true);
6803
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 while (!InterestingDecls.empty()) {
6805 Decl *D = InterestingDecls.front();
6806 InterestingDecls.pop_front();
6807
6808 PassInterestingDeclToConsumer(D);
6809 }
6810}
6811
6812void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6813 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6814 PassObjCImplDeclToConsumer(ImplD, Consumer);
6815 else
6816 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6817}
6818
6819void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6820 this->Consumer = Consumer;
6821
6822 if (!Consumer)
6823 return;
6824
Ben Langmuir332aafe2014-01-31 01:06:56 +00006825 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 // Force deserialization of this decl, which will cause it to be queued for
6827 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006828 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006830 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006831
6832 PassInterestingDeclsToConsumer();
6833}
6834
6835void ASTReader::PrintStats() {
6836 std::fprintf(stderr, "*** AST File Statistics:\n");
6837
6838 unsigned NumTypesLoaded
6839 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6840 QualType());
6841 unsigned NumDeclsLoaded
6842 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006843 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 unsigned NumIdentifiersLoaded
6845 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6846 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006847 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006848 unsigned NumMacrosLoaded
6849 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6850 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006851 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 unsigned NumSelectorsLoaded
6853 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6854 SelectorsLoaded.end(),
6855 Selector());
6856
6857 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6858 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6859 NumSLocEntriesRead, TotalNumSLocEntries,
6860 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6861 if (!TypesLoaded.empty())
6862 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6863 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6864 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6865 if (!DeclsLoaded.empty())
6866 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6867 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6868 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6869 if (!IdentifiersLoaded.empty())
6870 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6871 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6872 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6873 if (!MacrosLoaded.empty())
6874 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6875 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6876 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6877 if (!SelectorsLoaded.empty())
6878 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6879 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6880 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6881 if (TotalNumStatements)
6882 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6883 NumStatementsRead, TotalNumStatements,
6884 ((float)NumStatementsRead/TotalNumStatements * 100));
6885 if (TotalNumMacros)
6886 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6887 NumMacrosRead, TotalNumMacros,
6888 ((float)NumMacrosRead/TotalNumMacros * 100));
6889 if (TotalLexicalDeclContexts)
6890 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6891 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6892 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6893 * 100));
6894 if (TotalVisibleDeclContexts)
6895 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6896 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6897 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6898 * 100));
6899 if (TotalNumMethodPoolEntries) {
6900 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6901 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6902 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6903 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006905 if (NumMethodPoolLookups) {
6906 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6907 NumMethodPoolHits, NumMethodPoolLookups,
6908 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6909 }
6910 if (NumMethodPoolTableLookups) {
6911 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6912 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6913 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6914 * 100.0));
6915 }
6916
Douglas Gregor00a50f72013-01-25 00:38:33 +00006917 if (NumIdentifierLookupHits) {
6918 std::fprintf(stderr,
6919 " %u / %u identifier table lookups succeeded (%f%%)\n",
6920 NumIdentifierLookupHits, NumIdentifierLookups,
6921 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6922 }
6923
Douglas Gregore060e572013-01-25 01:03:03 +00006924 if (GlobalIndex) {
6925 std::fprintf(stderr, "\n");
6926 GlobalIndex->printStats();
6927 }
6928
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 std::fprintf(stderr, "\n");
6930 dump();
6931 std::fprintf(stderr, "\n");
6932}
6933
6934template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6935static void
6936dumpModuleIDMap(StringRef Name,
6937 const ContinuousRangeMap<Key, ModuleFile *,
6938 InitialCapacity> &Map) {
6939 if (Map.begin() == Map.end())
6940 return;
6941
6942 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6943 llvm::errs() << Name << ":\n";
6944 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6945 I != IEnd; ++I) {
6946 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6947 << "\n";
6948 }
6949}
6950
6951void ASTReader::dump() {
6952 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6953 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6954 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6955 dumpModuleIDMap("Global type map", GlobalTypeMap);
6956 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6957 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6958 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6959 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6960 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6961 dumpModuleIDMap("Global preprocessed entity map",
6962 GlobalPreprocessedEntityMap);
6963
6964 llvm::errs() << "\n*** PCH/Modules Loaded:";
6965 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6966 MEnd = ModuleMgr.end();
6967 M != MEnd; ++M)
6968 (*M)->dump();
6969}
6970
6971/// Return the amount of memory used by memory buffers, breaking down
6972/// by heap-backed versus mmap'ed memory.
6973void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6974 for (ModuleConstIterator I = ModuleMgr.begin(),
6975 E = ModuleMgr.end(); I != E; ++I) {
6976 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6977 size_t bytes = buf->getBufferSize();
6978 switch (buf->getBufferKind()) {
6979 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6980 sizes.malloc_bytes += bytes;
6981 break;
6982 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6983 sizes.mmap_bytes += bytes;
6984 break;
6985 }
6986 }
6987 }
6988}
6989
6990void ASTReader::InitializeSema(Sema &S) {
6991 SemaObj = &S;
6992 S.addExternalSource(this);
6993
6994 // Makes sure any declarations that were deserialized "too early"
6995 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006996 for (uint64_t ID : PreloadedDeclIDs) {
6997 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6998 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007000 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007001
Richard Smith3d8e97e2013-10-18 06:54:39 +00007002 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 if (!FPPragmaOptions.empty()) {
7004 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7005 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7006 }
7007
Richard Smith3d8e97e2013-10-18 06:54:39 +00007008 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 if (!OpenCLExtensions.empty()) {
7010 unsigned I = 0;
7011#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7012#include "clang/Basic/OpenCLExtensions.def"
7013
7014 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7015 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007016
7017 UpdateSema();
7018}
7019
7020void ASTReader::UpdateSema() {
7021 assert(SemaObj && "no Sema to update");
7022
7023 // Load the offsets of the declarations that Sema references.
7024 // They will be lazily deserialized when needed.
7025 if (!SemaDeclRefs.empty()) {
7026 assert(SemaDeclRefs.size() % 2 == 0);
7027 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7028 if (!SemaObj->StdNamespace)
7029 SemaObj->StdNamespace = SemaDeclRefs[I];
7030 if (!SemaObj->StdBadAlloc)
7031 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7032 }
7033 SemaDeclRefs.clear();
7034 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007035
7036 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7037 // encountered the pragma in the source.
7038 if(OptimizeOffPragmaLocation.isValid())
7039 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007040}
7041
7042IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7043 // Note that we are loading an identifier.
7044 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007045 StringRef Name(NameStart, NameEnd - NameStart);
7046
7047 // If there is a global index, look there first to determine which modules
7048 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007049 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007050 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007051 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007052 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7053 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007054 }
7055 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007056 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007057 NumIdentifierLookups,
7058 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007059 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 IdentifierInfo *II = Visitor.getIdentifierInfo();
7061 markIdentifierUpToDate(II);
7062 return II;
7063}
7064
7065namespace clang {
7066 /// \brief An identifier-lookup iterator that enumerates all of the
7067 /// identifiers stored within a set of AST files.
7068 class ASTIdentifierIterator : public IdentifierIterator {
7069 /// \brief The AST reader whose identifiers are being enumerated.
7070 const ASTReader &Reader;
7071
7072 /// \brief The current index into the chain of AST files stored in
7073 /// the AST reader.
7074 unsigned Index;
7075
7076 /// \brief The current position within the identifier lookup table
7077 /// of the current AST file.
7078 ASTIdentifierLookupTable::key_iterator Current;
7079
7080 /// \brief The end position within the identifier lookup table of
7081 /// the current AST file.
7082 ASTIdentifierLookupTable::key_iterator End;
7083
7084 public:
7085 explicit ASTIdentifierIterator(const ASTReader &Reader);
7086
Craig Topper3e89dfe2014-03-13 02:13:41 +00007087 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 };
7089}
7090
7091ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7092 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7093 ASTIdentifierLookupTable *IdTable
7094 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7095 Current = IdTable->key_begin();
7096 End = IdTable->key_end();
7097}
7098
7099StringRef ASTIdentifierIterator::Next() {
7100 while (Current == End) {
7101 // If we have exhausted all of our AST files, we're done.
7102 if (Index == 0)
7103 return StringRef();
7104
7105 --Index;
7106 ASTIdentifierLookupTable *IdTable
7107 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7108 IdentifierLookupTable;
7109 Current = IdTable->key_begin();
7110 End = IdTable->key_end();
7111 }
7112
7113 // We have any identifiers remaining in the current AST file; return
7114 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007115 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007116 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007117 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007118}
7119
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007120IdentifierIterator *ASTReader::getIdentifiers() {
7121 if (!loadGlobalIndex())
7122 return GlobalIndex->createIdentifierIterator();
7123
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 return new ASTIdentifierIterator(*this);
7125}
7126
7127namespace clang { namespace serialization {
7128 class ReadMethodPoolVisitor {
7129 ASTReader &Reader;
7130 Selector Sel;
7131 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007132 unsigned InstanceBits;
7133 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007134 bool InstanceHasMoreThanOneDecl;
7135 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007136 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7137 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007138
7139 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007140 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007142 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007143 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7144 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007145
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 static bool visit(ModuleFile &M, void *UserData) {
7147 ReadMethodPoolVisitor *This
7148 = static_cast<ReadMethodPoolVisitor *>(UserData);
7149
7150 if (!M.SelectorLookupTable)
7151 return false;
7152
7153 // If we've already searched this module file, skip it now.
7154 if (M.Generation <= This->PriorGeneration)
7155 return true;
7156
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007157 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 ASTSelectorLookupTable *PoolTable
7159 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7160 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7161 if (Pos == PoolTable->end())
7162 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007163
7164 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 ++This->Reader.NumSelectorsRead;
7166 // FIXME: Not quite happy with the statistics here. We probably should
7167 // disable this tracking when called via LoadSelector.
7168 // Also, should entries without methods count as misses?
7169 ++This->Reader.NumMethodPoolEntriesRead;
7170 ASTSelectorLookupTrait::data_type Data = *Pos;
7171 if (This->Reader.DeserializationListener)
7172 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7173 This->Sel);
7174
7175 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7176 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007177 This->InstanceBits = Data.InstanceBits;
7178 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007179 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7180 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 return true;
7182 }
7183
7184 /// \brief Retrieve the instance methods found by this visitor.
7185 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7186 return InstanceMethods;
7187 }
7188
7189 /// \brief Retrieve the instance methods found by this visitor.
7190 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7191 return FactoryMethods;
7192 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007193
7194 unsigned getInstanceBits() const { return InstanceBits; }
7195 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007196 bool instanceHasMoreThanOneDecl() const {
7197 return InstanceHasMoreThanOneDecl;
7198 }
7199 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 };
7201} } // end namespace clang::serialization
7202
7203/// \brief Add the given set of methods to the method list.
7204static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7205 ObjCMethodList &List) {
7206 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7207 S.addMethodToGlobalList(&List, Methods[I]);
7208 }
7209}
7210
7211void ASTReader::ReadMethodPool(Selector Sel) {
7212 // Get the selector generation and update it to the current generation.
7213 unsigned &Generation = SelectorGeneration[Sel];
7214 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007215 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007216
7217 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007218 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7220 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7221
7222 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007223 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007225
7226 ++NumMethodPoolHits;
7227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 if (!getSema())
7229 return;
7230
7231 Sema &S = *getSema();
7232 Sema::GlobalMethodPool::iterator Pos
7233 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007234
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007235 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007236 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007237 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007238 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007239
7240 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7241 // when building a module we keep every method individually and may need to
7242 // update hasMoreThanOneDecl as we add the methods.
7243 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7244 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007245}
7246
7247void ASTReader::ReadKnownNamespaces(
7248 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7249 Namespaces.clear();
7250
7251 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7252 if (NamespaceDecl *Namespace
7253 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7254 Namespaces.push_back(Namespace);
7255 }
7256}
7257
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007258void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007259 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007260 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7261 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007262 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007263 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007264 Undefined.insert(std::make_pair(D, Loc));
7265 }
7266}
Nick Lewycky8334af82013-01-26 00:35:08 +00007267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268void ASTReader::ReadTentativeDefinitions(
7269 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7270 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7271 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7272 if (Var)
7273 TentativeDefs.push_back(Var);
7274 }
7275 TentativeDefinitions.clear();
7276}
7277
7278void ASTReader::ReadUnusedFileScopedDecls(
7279 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7280 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7281 DeclaratorDecl *D
7282 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7283 if (D)
7284 Decls.push_back(D);
7285 }
7286 UnusedFileScopedDecls.clear();
7287}
7288
7289void ASTReader::ReadDelegatingConstructors(
7290 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7291 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7292 CXXConstructorDecl *D
7293 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7294 if (D)
7295 Decls.push_back(D);
7296 }
7297 DelegatingCtorDecls.clear();
7298}
7299
7300void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7301 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7302 TypedefNameDecl *D
7303 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7304 if (D)
7305 Decls.push_back(D);
7306 }
7307 ExtVectorDecls.clear();
7308}
7309
Nico Weber72889432014-09-06 01:25:55 +00007310void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7311 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7312 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7313 ++I) {
7314 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7315 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7316 if (D)
7317 Decls.insert(D);
7318 }
7319 UnusedLocalTypedefNameCandidates.clear();
7320}
7321
Guy Benyei11169dd2012-12-18 14:30:41 +00007322void
Richard Smith78165b52013-01-10 23:43:47 +00007323ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7324 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7325 NamedDecl *D
7326 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 if (D)
7328 Decls.push_back(D);
7329 }
Richard Smith78165b52013-01-10 23:43:47 +00007330 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007331}
7332
7333void ASTReader::ReadReferencedSelectors(
7334 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7335 if (ReferencedSelectorsData.empty())
7336 return;
7337
7338 // If there are @selector references added them to its pool. This is for
7339 // implementation of -Wselector.
7340 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7341 unsigned I = 0;
7342 while (I < DataSize) {
7343 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7344 SourceLocation SelLoc
7345 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7346 Sels.push_back(std::make_pair(Sel, SelLoc));
7347 }
7348 ReferencedSelectorsData.clear();
7349}
7350
7351void ASTReader::ReadWeakUndeclaredIdentifiers(
7352 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7353 if (WeakUndeclaredIdentifiers.empty())
7354 return;
7355
7356 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7357 IdentifierInfo *WeakId
7358 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7359 IdentifierInfo *AliasId
7360 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7361 SourceLocation Loc
7362 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7363 bool Used = WeakUndeclaredIdentifiers[I++];
7364 WeakInfo WI(AliasId, Loc);
7365 WI.setUsed(Used);
7366 WeakIDs.push_back(std::make_pair(WeakId, WI));
7367 }
7368 WeakUndeclaredIdentifiers.clear();
7369}
7370
7371void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7372 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7373 ExternalVTableUse VT;
7374 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7375 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7376 VT.DefinitionRequired = VTableUses[Idx++];
7377 VTables.push_back(VT);
7378 }
7379
7380 VTableUses.clear();
7381}
7382
7383void ASTReader::ReadPendingInstantiations(
7384 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7385 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7386 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7387 SourceLocation Loc
7388 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7389
7390 Pending.push_back(std::make_pair(D, Loc));
7391 }
7392 PendingInstantiations.clear();
7393}
7394
Richard Smithe40f2ba2013-08-07 21:41:30 +00007395void ASTReader::ReadLateParsedTemplates(
7396 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7397 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7398 /* In loop */) {
7399 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7400
7401 LateParsedTemplate *LT = new LateParsedTemplate;
7402 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7403
7404 ModuleFile *F = getOwningModuleFile(LT->D);
7405 assert(F && "No module");
7406
7407 unsigned TokN = LateParsedTemplates[Idx++];
7408 LT->Toks.reserve(TokN);
7409 for (unsigned T = 0; T < TokN; ++T)
7410 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7411
7412 LPTMap[FD] = LT;
7413 }
7414
7415 LateParsedTemplates.clear();
7416}
7417
Guy Benyei11169dd2012-12-18 14:30:41 +00007418void ASTReader::LoadSelector(Selector Sel) {
7419 // It would be complicated to avoid reading the methods anyway. So don't.
7420 ReadMethodPool(Sel);
7421}
7422
7423void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7424 assert(ID && "Non-zero identifier ID required");
7425 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7426 IdentifiersLoaded[ID - 1] = II;
7427 if (DeserializationListener)
7428 DeserializationListener->IdentifierRead(ID, II);
7429}
7430
7431/// \brief Set the globally-visible declarations associated with the given
7432/// identifier.
7433///
7434/// If the AST reader is currently in a state where the given declaration IDs
7435/// cannot safely be resolved, they are queued until it is safe to resolve
7436/// them.
7437///
7438/// \param II an IdentifierInfo that refers to one or more globally-visible
7439/// declarations.
7440///
7441/// \param DeclIDs the set of declaration IDs with the name @p II that are
7442/// visible at global scope.
7443///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007444/// \param Decls if non-null, this vector will be populated with the set of
7445/// deserialized declarations. These declarations will not be pushed into
7446/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007447void
7448ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7449 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007450 SmallVectorImpl<Decl *> *Decls) {
7451 if (NumCurrentElementsDeserializing && !Decls) {
7452 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 return;
7454 }
7455
7456 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007457 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 // Queue this declaration so that it will be added to the
7459 // translation unit scope and identifier's declaration chain
7460 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007461 PreloadedDeclIDs.push_back(DeclIDs[I]);
7462 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007464
7465 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7466
7467 // If we're simply supposed to record the declarations, do so now.
7468 if (Decls) {
7469 Decls->push_back(D);
7470 continue;
7471 }
7472
7473 // Introduce this declaration into the translation-unit scope
7474 // and add it to the declaration chain for this identifier, so
7475 // that (unqualified) name lookup will find it.
7476 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
7478}
7479
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007480IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007482 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
7484 if (IdentifiersLoaded.empty()) {
7485 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007486 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
7488
7489 ID -= 1;
7490 if (!IdentifiersLoaded[ID]) {
7491 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7492 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7493 ModuleFile *M = I->second;
7494 unsigned Index = ID - M->BaseIdentifierID;
7495 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7496
7497 // All of the strings in the AST file are preceded by a 16-bit length.
7498 // Extract that 16-bit length to avoid having to execute strlen().
7499 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7500 // unsigned integers. This is important to avoid integer overflow when
7501 // we cast them to 'unsigned'.
7502 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7503 unsigned StrLen = (((unsigned) StrLenPtr[0])
7504 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007505 IdentifiersLoaded[ID]
7506 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 if (DeserializationListener)
7508 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7509 }
7510
7511 return IdentifiersLoaded[ID];
7512}
7513
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007514IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7515 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007516}
7517
7518IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7519 if (LocalID < NUM_PREDEF_IDENT_IDS)
7520 return LocalID;
7521
7522 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7523 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7524 assert(I != M.IdentifierRemap.end()
7525 && "Invalid index into identifier index remap");
7526
7527 return LocalID + I->second;
7528}
7529
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007530MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007532 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007533
7534 if (MacrosLoaded.empty()) {
7535 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007536 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 }
7538
7539 ID -= NUM_PREDEF_MACRO_IDS;
7540 if (!MacrosLoaded[ID]) {
7541 GlobalMacroMapType::iterator I
7542 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7543 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7544 ModuleFile *M = I->second;
7545 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007546 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7547
7548 if (DeserializationListener)
7549 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7550 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 }
7552
7553 return MacrosLoaded[ID];
7554}
7555
7556MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7557 if (LocalID < NUM_PREDEF_MACRO_IDS)
7558 return LocalID;
7559
7560 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7561 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7562 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7563
7564 return LocalID + I->second;
7565}
7566
7567serialization::SubmoduleID
7568ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7569 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7570 return LocalID;
7571
7572 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7573 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7574 assert(I != M.SubmoduleRemap.end()
7575 && "Invalid index into submodule index remap");
7576
7577 return LocalID + I->second;
7578}
7579
7580Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7581 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7582 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007583 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 }
7585
7586 if (GlobalID > SubmodulesLoaded.size()) {
7587 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007588 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007589 }
7590
7591 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7592}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007593
7594Module *ASTReader::getModule(unsigned ID) {
7595 return getSubmodule(ID);
7596}
7597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7599 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7600}
7601
7602Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7603 if (ID == 0)
7604 return Selector();
7605
7606 if (ID > SelectorsLoaded.size()) {
7607 Error("selector ID out of range in AST file");
7608 return Selector();
7609 }
7610
Craig Toppera13603a2014-05-22 05:54:18 +00007611 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 // Load this selector from the selector table.
7613 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7614 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7615 ModuleFile &M = *I->second;
7616 ASTSelectorLookupTrait Trait(*this, M);
7617 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7618 SelectorsLoaded[ID - 1] =
7619 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7620 if (DeserializationListener)
7621 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7622 }
7623
7624 return SelectorsLoaded[ID - 1];
7625}
7626
7627Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7628 return DecodeSelector(ID);
7629}
7630
7631uint32_t ASTReader::GetNumExternalSelectors() {
7632 // ID 0 (the null selector) is considered an external selector.
7633 return getTotalNumSelectors() + 1;
7634}
7635
7636serialization::SelectorID
7637ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7638 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7639 return LocalID;
7640
7641 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7642 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7643 assert(I != M.SelectorRemap.end()
7644 && "Invalid index into selector index remap");
7645
7646 return LocalID + I->second;
7647}
7648
7649DeclarationName
7650ASTReader::ReadDeclarationName(ModuleFile &F,
7651 const RecordData &Record, unsigned &Idx) {
7652 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7653 switch (Kind) {
7654 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007655 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007656
7657 case DeclarationName::ObjCZeroArgSelector:
7658 case DeclarationName::ObjCOneArgSelector:
7659 case DeclarationName::ObjCMultiArgSelector:
7660 return DeclarationName(ReadSelector(F, Record, Idx));
7661
7662 case DeclarationName::CXXConstructorName:
7663 return Context.DeclarationNames.getCXXConstructorName(
7664 Context.getCanonicalType(readType(F, Record, Idx)));
7665
7666 case DeclarationName::CXXDestructorName:
7667 return Context.DeclarationNames.getCXXDestructorName(
7668 Context.getCanonicalType(readType(F, Record, Idx)));
7669
7670 case DeclarationName::CXXConversionFunctionName:
7671 return Context.DeclarationNames.getCXXConversionFunctionName(
7672 Context.getCanonicalType(readType(F, Record, Idx)));
7673
7674 case DeclarationName::CXXOperatorName:
7675 return Context.DeclarationNames.getCXXOperatorName(
7676 (OverloadedOperatorKind)Record[Idx++]);
7677
7678 case DeclarationName::CXXLiteralOperatorName:
7679 return Context.DeclarationNames.getCXXLiteralOperatorName(
7680 GetIdentifierInfo(F, Record, Idx));
7681
7682 case DeclarationName::CXXUsingDirective:
7683 return DeclarationName::getUsingDirectiveName();
7684 }
7685
7686 llvm_unreachable("Invalid NameKind!");
7687}
7688
7689void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7690 DeclarationNameLoc &DNLoc,
7691 DeclarationName Name,
7692 const RecordData &Record, unsigned &Idx) {
7693 switch (Name.getNameKind()) {
7694 case DeclarationName::CXXConstructorName:
7695 case DeclarationName::CXXDestructorName:
7696 case DeclarationName::CXXConversionFunctionName:
7697 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7698 break;
7699
7700 case DeclarationName::CXXOperatorName:
7701 DNLoc.CXXOperatorName.BeginOpNameLoc
7702 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7703 DNLoc.CXXOperatorName.EndOpNameLoc
7704 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7705 break;
7706
7707 case DeclarationName::CXXLiteralOperatorName:
7708 DNLoc.CXXLiteralOperatorName.OpNameLoc
7709 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7710 break;
7711
7712 case DeclarationName::Identifier:
7713 case DeclarationName::ObjCZeroArgSelector:
7714 case DeclarationName::ObjCOneArgSelector:
7715 case DeclarationName::ObjCMultiArgSelector:
7716 case DeclarationName::CXXUsingDirective:
7717 break;
7718 }
7719}
7720
7721void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7722 DeclarationNameInfo &NameInfo,
7723 const RecordData &Record, unsigned &Idx) {
7724 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7725 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7726 DeclarationNameLoc DNLoc;
7727 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7728 NameInfo.setInfo(DNLoc);
7729}
7730
7731void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7732 const RecordData &Record, unsigned &Idx) {
7733 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7734 unsigned NumTPLists = Record[Idx++];
7735 Info.NumTemplParamLists = NumTPLists;
7736 if (NumTPLists) {
7737 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7738 for (unsigned i=0; i != NumTPLists; ++i)
7739 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7740 }
7741}
7742
7743TemplateName
7744ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7745 unsigned &Idx) {
7746 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7747 switch (Kind) {
7748 case TemplateName::Template:
7749 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7750
7751 case TemplateName::OverloadedTemplate: {
7752 unsigned size = Record[Idx++];
7753 UnresolvedSet<8> Decls;
7754 while (size--)
7755 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7756
7757 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7758 }
7759
7760 case TemplateName::QualifiedTemplate: {
7761 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7762 bool hasTemplKeyword = Record[Idx++];
7763 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7764 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7765 }
7766
7767 case TemplateName::DependentTemplate: {
7768 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7769 if (Record[Idx++]) // isIdentifier
7770 return Context.getDependentTemplateName(NNS,
7771 GetIdentifierInfo(F, Record,
7772 Idx));
7773 return Context.getDependentTemplateName(NNS,
7774 (OverloadedOperatorKind)Record[Idx++]);
7775 }
7776
7777 case TemplateName::SubstTemplateTemplateParm: {
7778 TemplateTemplateParmDecl *param
7779 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7780 if (!param) return TemplateName();
7781 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7782 return Context.getSubstTemplateTemplateParm(param, replacement);
7783 }
7784
7785 case TemplateName::SubstTemplateTemplateParmPack: {
7786 TemplateTemplateParmDecl *Param
7787 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7788 if (!Param)
7789 return TemplateName();
7790
7791 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7792 if (ArgPack.getKind() != TemplateArgument::Pack)
7793 return TemplateName();
7794
7795 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7796 }
7797 }
7798
7799 llvm_unreachable("Unhandled template name kind!");
7800}
7801
7802TemplateArgument
7803ASTReader::ReadTemplateArgument(ModuleFile &F,
7804 const RecordData &Record, unsigned &Idx) {
7805 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7806 switch (Kind) {
7807 case TemplateArgument::Null:
7808 return TemplateArgument();
7809 case TemplateArgument::Type:
7810 return TemplateArgument(readType(F, Record, Idx));
7811 case TemplateArgument::Declaration: {
7812 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007813 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 }
7815 case TemplateArgument::NullPtr:
7816 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7817 case TemplateArgument::Integral: {
7818 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7819 QualType T = readType(F, Record, Idx);
7820 return TemplateArgument(Context, Value, T);
7821 }
7822 case TemplateArgument::Template:
7823 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7824 case TemplateArgument::TemplateExpansion: {
7825 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007826 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 if (unsigned NumExpansions = Record[Idx++])
7828 NumTemplateExpansions = NumExpansions - 1;
7829 return TemplateArgument(Name, NumTemplateExpansions);
7830 }
7831 case TemplateArgument::Expression:
7832 return TemplateArgument(ReadExpr(F));
7833 case TemplateArgument::Pack: {
7834 unsigned NumArgs = Record[Idx++];
7835 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7836 for (unsigned I = 0; I != NumArgs; ++I)
7837 Args[I] = ReadTemplateArgument(F, Record, Idx);
7838 return TemplateArgument(Args, NumArgs);
7839 }
7840 }
7841
7842 llvm_unreachable("Unhandled template argument kind!");
7843}
7844
7845TemplateParameterList *
7846ASTReader::ReadTemplateParameterList(ModuleFile &F,
7847 const RecordData &Record, unsigned &Idx) {
7848 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7849 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7850 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7851
7852 unsigned NumParams = Record[Idx++];
7853 SmallVector<NamedDecl *, 16> Params;
7854 Params.reserve(NumParams);
7855 while (NumParams--)
7856 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7857
7858 TemplateParameterList* TemplateParams =
7859 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7860 Params.data(), Params.size(), RAngleLoc);
7861 return TemplateParams;
7862}
7863
7864void
7865ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007866ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 ModuleFile &F, const RecordData &Record,
7868 unsigned &Idx) {
7869 unsigned NumTemplateArgs = Record[Idx++];
7870 TemplArgs.reserve(NumTemplateArgs);
7871 while (NumTemplateArgs--)
7872 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7873}
7874
7875/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007876void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 const RecordData &Record, unsigned &Idx) {
7878 unsigned NumDecls = Record[Idx++];
7879 Set.reserve(Context, NumDecls);
7880 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007881 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007883 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 }
7885}
7886
7887CXXBaseSpecifier
7888ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7889 const RecordData &Record, unsigned &Idx) {
7890 bool isVirtual = static_cast<bool>(Record[Idx++]);
7891 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7892 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7893 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7894 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7897 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7898 EllipsisLoc);
7899 Result.setInheritConstructors(inheritConstructors);
7900 return Result;
7901}
7902
7903std::pair<CXXCtorInitializer **, unsigned>
7904ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7905 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007906 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007907 unsigned NumInitializers = Record[Idx++];
7908 if (NumInitializers) {
7909 CtorInitializers
7910 = new (Context) CXXCtorInitializer*[NumInitializers];
7911 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007912 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007913 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007914 FieldDecl *Member = nullptr;
7915 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007916
7917 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7918 switch (Type) {
7919 case CTOR_INITIALIZER_BASE:
7920 TInfo = GetTypeSourceInfo(F, Record, Idx);
7921 IsBaseVirtual = Record[Idx++];
7922 break;
7923
7924 case CTOR_INITIALIZER_DELEGATING:
7925 TInfo = GetTypeSourceInfo(F, Record, Idx);
7926 break;
7927
7928 case CTOR_INITIALIZER_MEMBER:
7929 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7930 break;
7931
7932 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7933 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7934 break;
7935 }
7936
7937 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7938 Expr *Init = ReadExpr(F);
7939 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7940 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7941 bool IsWritten = Record[Idx++];
7942 unsigned SourceOrderOrNumArrayIndices;
7943 SmallVector<VarDecl *, 8> Indices;
7944 if (IsWritten) {
7945 SourceOrderOrNumArrayIndices = Record[Idx++];
7946 } else {
7947 SourceOrderOrNumArrayIndices = Record[Idx++];
7948 Indices.reserve(SourceOrderOrNumArrayIndices);
7949 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7950 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7951 }
7952
7953 CXXCtorInitializer *BOMInit;
7954 if (Type == CTOR_INITIALIZER_BASE) {
7955 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7956 LParenLoc, Init, RParenLoc,
7957 MemberOrEllipsisLoc);
7958 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7959 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7960 Init, RParenLoc);
7961 } else if (IsWritten) {
7962 if (Member)
7963 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7964 LParenLoc, Init, RParenLoc);
7965 else
7966 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7967 MemberOrEllipsisLoc, LParenLoc,
7968 Init, RParenLoc);
7969 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007970 if (IndirectMember) {
7971 assert(Indices.empty() && "Indirect field improperly initialized");
7972 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7973 MemberOrEllipsisLoc, LParenLoc,
7974 Init, RParenLoc);
7975 } else {
7976 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7977 LParenLoc, Init, RParenLoc,
7978 Indices.data(), Indices.size());
7979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 }
7981
7982 if (IsWritten)
7983 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7984 CtorInitializers[i] = BOMInit;
7985 }
7986 }
7987
7988 return std::make_pair(CtorInitializers, NumInitializers);
7989}
7990
7991NestedNameSpecifier *
7992ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7993 const RecordData &Record, unsigned &Idx) {
7994 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007995 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 for (unsigned I = 0; I != N; ++I) {
7997 NestedNameSpecifier::SpecifierKind Kind
7998 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7999 switch (Kind) {
8000 case NestedNameSpecifier::Identifier: {
8001 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8002 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8003 break;
8004 }
8005
8006 case NestedNameSpecifier::Namespace: {
8007 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8008 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8009 break;
8010 }
8011
8012 case NestedNameSpecifier::NamespaceAlias: {
8013 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8014 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8015 break;
8016 }
8017
8018 case NestedNameSpecifier::TypeSpec:
8019 case NestedNameSpecifier::TypeSpecWithTemplate: {
8020 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8021 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008022 return nullptr;
8023
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 bool Template = Record[Idx++];
8025 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8026 break;
8027 }
8028
8029 case NestedNameSpecifier::Global: {
8030 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8031 // No associated value, and there can't be a prefix.
8032 break;
8033 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008034
8035 case NestedNameSpecifier::Super: {
8036 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8037 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8038 break;
8039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 }
8041 Prev = NNS;
8042 }
8043 return NNS;
8044}
8045
8046NestedNameSpecifierLoc
8047ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8048 unsigned &Idx) {
8049 unsigned N = Record[Idx++];
8050 NestedNameSpecifierLocBuilder Builder;
8051 for (unsigned I = 0; I != N; ++I) {
8052 NestedNameSpecifier::SpecifierKind Kind
8053 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8054 switch (Kind) {
8055 case NestedNameSpecifier::Identifier: {
8056 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8057 SourceRange Range = ReadSourceRange(F, Record, Idx);
8058 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8059 break;
8060 }
8061
8062 case NestedNameSpecifier::Namespace: {
8063 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8064 SourceRange Range = ReadSourceRange(F, Record, Idx);
8065 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8066 break;
8067 }
8068
8069 case NestedNameSpecifier::NamespaceAlias: {
8070 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8071 SourceRange Range = ReadSourceRange(F, Record, Idx);
8072 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8073 break;
8074 }
8075
8076 case NestedNameSpecifier::TypeSpec:
8077 case NestedNameSpecifier::TypeSpecWithTemplate: {
8078 bool Template = Record[Idx++];
8079 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8080 if (!T)
8081 return NestedNameSpecifierLoc();
8082 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8083
8084 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8085 Builder.Extend(Context,
8086 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8087 T->getTypeLoc(), ColonColonLoc);
8088 break;
8089 }
8090
8091 case NestedNameSpecifier::Global: {
8092 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8093 Builder.MakeGlobal(Context, ColonColonLoc);
8094 break;
8095 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008096
8097 case NestedNameSpecifier::Super: {
8098 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8099 SourceRange Range = ReadSourceRange(F, Record, Idx);
8100 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8101 break;
8102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 }
8104 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008105
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 return Builder.getWithLocInContext(Context);
8107}
8108
8109SourceRange
8110ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8111 unsigned &Idx) {
8112 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8113 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8114 return SourceRange(beg, end);
8115}
8116
8117/// \brief Read an integral value
8118llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8119 unsigned BitWidth = Record[Idx++];
8120 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8121 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8122 Idx += NumWords;
8123 return Result;
8124}
8125
8126/// \brief Read a signed integral value
8127llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8128 bool isUnsigned = Record[Idx++];
8129 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8130}
8131
8132/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008133llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8134 const llvm::fltSemantics &Sem,
8135 unsigned &Idx) {
8136 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008137}
8138
8139// \brief Read a string
8140std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8141 unsigned Len = Record[Idx++];
8142 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8143 Idx += Len;
8144 return Result;
8145}
8146
Richard Smith7ed1bc92014-12-05 22:42:13 +00008147std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8148 unsigned &Idx) {
8149 std::string Filename = ReadString(Record, Idx);
8150 ResolveImportedPath(F, Filename);
8151 return Filename;
8152}
8153
Guy Benyei11169dd2012-12-18 14:30:41 +00008154VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8155 unsigned &Idx) {
8156 unsigned Major = Record[Idx++];
8157 unsigned Minor = Record[Idx++];
8158 unsigned Subminor = Record[Idx++];
8159 if (Minor == 0)
8160 return VersionTuple(Major);
8161 if (Subminor == 0)
8162 return VersionTuple(Major, Minor - 1);
8163 return VersionTuple(Major, Minor - 1, Subminor - 1);
8164}
8165
8166CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8167 const RecordData &Record,
8168 unsigned &Idx) {
8169 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8170 return CXXTemporary::Create(Context, Decl);
8171}
8172
8173DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008174 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008175}
8176
8177DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8178 return Diags.Report(Loc, DiagID);
8179}
8180
8181/// \brief Retrieve the identifier table associated with the
8182/// preprocessor.
8183IdentifierTable &ASTReader::getIdentifierTable() {
8184 return PP.getIdentifierTable();
8185}
8186
8187/// \brief Record that the given ID maps to the given switch-case
8188/// statement.
8189void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008190 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 "Already have a SwitchCase with this ID");
8192 (*CurrSwitchCaseStmts)[ID] = SC;
8193}
8194
8195/// \brief Retrieve the switch-case statement with the given ID.
8196SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008197 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 return (*CurrSwitchCaseStmts)[ID];
8199}
8200
8201void ASTReader::ClearSwitchCaseIDs() {
8202 CurrSwitchCaseStmts->clear();
8203}
8204
8205void ASTReader::ReadComments() {
8206 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008207 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 serialization::ModuleFile *> >::iterator
8209 I = CommentsCursors.begin(),
8210 E = CommentsCursors.end();
8211 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008212 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008213 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 serialization::ModuleFile &F = *I->second;
8215 SavedStreamPosition SavedPosition(Cursor);
8216
8217 RecordData Record;
8218 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008219 llvm::BitstreamEntry Entry =
8220 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008221
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008222 switch (Entry.Kind) {
8223 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8224 case llvm::BitstreamEntry::Error:
8225 Error("malformed block record in AST file");
8226 return;
8227 case llvm::BitstreamEntry::EndBlock:
8228 goto NextCursor;
8229 case llvm::BitstreamEntry::Record:
8230 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 }
8233
8234 // Read a record.
8235 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008236 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 case COMMENTS_RAW_COMMENT: {
8238 unsigned Idx = 0;
8239 SourceRange SR = ReadSourceRange(F, Record, Idx);
8240 RawComment::CommentKind Kind =
8241 (RawComment::CommentKind) Record[Idx++];
8242 bool IsTrailingComment = Record[Idx++];
8243 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008244 Comments.push_back(new (Context) RawComment(
8245 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8246 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 break;
8248 }
8249 }
8250 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008251 NextCursor:
8252 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008254}
8255
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008256void ASTReader::getInputFiles(ModuleFile &F,
8257 SmallVectorImpl<serialization::InputFile> &Files) {
8258 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8259 unsigned ID = I+1;
8260 Files.push_back(getInputFile(F, ID));
8261 }
8262}
8263
Richard Smithcd45dbc2014-04-19 03:48:30 +00008264std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8265 // If we know the owning module, use it.
8266 if (Module *M = D->getOwningModule())
8267 return M->getFullModuleName();
8268
8269 // Otherwise, use the name of the top-level module the decl is within.
8270 if (ModuleFile *M = getOwningModuleFile(D))
8271 return M->ModuleName;
8272
8273 // Not from a module.
8274 return "";
8275}
8276
Guy Benyei11169dd2012-12-18 14:30:41 +00008277void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008278 while (!PendingIdentifierInfos.empty() ||
8279 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008280 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008281 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 // If any identifiers with corresponding top-level declarations have
8283 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008284 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8285 TopLevelDeclsMap;
8286 TopLevelDeclsMap TopLevelDecls;
8287
Guy Benyei11169dd2012-12-18 14:30:41 +00008288 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008289 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008290 SmallVector<uint32_t, 4> DeclIDs =
8291 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008292 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008293
8294 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008295 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008296
Richard Smith851072e2014-05-19 20:59:20 +00008297 // For each decl chain that we wanted to complete while deserializing, mark
8298 // it as "still needs to be completed".
8299 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8300 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8301 }
8302 PendingIncompleteDeclChains.clear();
8303
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 // Load pending declaration chains.
Richard Smith78bea732015-02-27 20:14:19 +00008305 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +00008306 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smith78bea732015-02-27 20:14:19 +00008307 PendingDeclChainsKnown.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008308 PendingDeclChains.clear();
8309
Douglas Gregor6168bd22013-02-18 15:53:43 +00008310 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008311 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8312 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008313 IdentifierInfo *II = TLD->first;
8314 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008315 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008316 }
8317 }
8318
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 // Load any pending macro definitions.
8320 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008321 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8322 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8323 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8324 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008325 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008326 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008327 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008328 if (Info.M->Kind != MK_ImplicitModule &&
8329 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008330 resolvePendingMacro(II, Info);
8331 }
8332 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008333 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008334 ++IDIdx) {
8335 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008336 if (Info.M->Kind == MK_ImplicitModule ||
8337 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008338 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008339 }
8340 }
8341 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008342
8343 // Wire up the DeclContexts for Decls that we delayed setting until
8344 // recursive loading is completed.
8345 while (!PendingDeclContextInfos.empty()) {
8346 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8347 PendingDeclContextInfos.pop_front();
8348 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8349 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8350 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8351 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008352
Richard Smithd1c46742014-04-30 02:24:17 +00008353 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008354 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008355 auto Update = PendingUpdateRecords.pop_back_val();
8356 ReadingKindTracker ReadingKind(Read_Decl, *this);
8357 loadDeclUpdateRecords(Update.first, Update.second);
8358 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008359 }
Richard Smith8a639892015-01-24 01:07:20 +00008360
8361 // At this point, all update records for loaded decls are in place, so any
8362 // fake class definitions should have become real.
8363 assert(PendingFakeDefinitionData.empty() &&
8364 "faked up a class definition but never saw the real one");
8365
Guy Benyei11169dd2012-12-18 14:30:41 +00008366 // If we deserialized any C++ or Objective-C class definitions, any
8367 // Objective-C protocol definitions, or any redeclarable templates, make sure
8368 // that all redeclarations point to the definitions. Note that this can only
8369 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008370 for (Decl *D : PendingDefinitions) {
8371 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008372 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008373 // Make sure that the TagType points at the definition.
8374 const_cast<TagType*>(TagT)->decl = TD;
8375 }
8376
Craig Topperc6914d02014-08-25 04:15:02 +00008377 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008378 for (auto R : RD->redecls()) {
8379 assert((R == D) == R->isThisDeclarationADefinition() &&
8380 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008381 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 }
8384
8385 continue;
8386 }
8387
Craig Topperc6914d02014-08-25 04:15:02 +00008388 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008389 // Make sure that the ObjCInterfaceType points at the definition.
8390 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8391 ->Decl = ID;
8392
Aaron Ballman86c93902014-03-06 23:45:36 +00008393 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 R->Data = ID->Data;
8395
8396 continue;
8397 }
8398
Craig Topperc6914d02014-08-25 04:15:02 +00008399 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008400 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 R->Data = PD->Data;
8402
8403 continue;
8404 }
8405
Craig Topperc6914d02014-08-25 04:15:02 +00008406 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008407 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 R->Common = RTD->Common;
8409 }
8410 PendingDefinitions.clear();
8411
8412 // Load the bodies of any functions or methods we've encountered. We do
8413 // this now (delayed) so that we can be sure that the declaration chains
8414 // have been fully wired up.
8415 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8416 PBEnd = PendingBodies.end();
8417 PB != PBEnd; ++PB) {
8418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8419 // FIXME: Check for =delete/=default?
8420 // FIXME: Complain about ODR violations here?
8421 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8422 FD->setLazyBody(PB->second);
8423 continue;
8424 }
8425
8426 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8427 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8428 MD->setLazyBody(PB->second);
8429 }
8430 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008431}
8432
8433void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008434 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8435 return;
8436
Richard Smitha0ce9c42014-07-29 23:23:27 +00008437 // Trigger the import of the full definition of each class that had any
8438 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008439 // These updates may in turn find and diagnose some ODR failures, so take
8440 // ownership of the set first.
8441 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8442 PendingOdrMergeFailures.clear();
8443 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008444 Merge.first->buildLookup();
8445 Merge.first->decls_begin();
8446 Merge.first->bases_begin();
8447 Merge.first->vbases_begin();
8448 for (auto *RD : Merge.second) {
8449 RD->decls_begin();
8450 RD->bases_begin();
8451 RD->vbases_begin();
8452 }
8453 }
8454
8455 // For each declaration from a merged context, check that the canonical
8456 // definition of that context also contains a declaration of the same
8457 // entity.
8458 //
8459 // Caution: this loop does things that might invalidate iterators into
8460 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8461 while (!PendingOdrMergeChecks.empty()) {
8462 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8463
8464 // FIXME: Skip over implicit declarations for now. This matters for things
8465 // like implicitly-declared special member functions. This isn't entirely
8466 // correct; we can end up with multiple unmerged declarations of the same
8467 // implicit entity.
8468 if (D->isImplicit())
8469 continue;
8470
8471 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008472
8473 bool Found = false;
8474 const Decl *DCanon = D->getCanonicalDecl();
8475
Richard Smith01bdb7a2014-08-28 05:44:07 +00008476 for (auto RI : D->redecls()) {
8477 if (RI->getLexicalDeclContext() == CanonDef) {
8478 Found = true;
8479 break;
8480 }
8481 }
8482 if (Found)
8483 continue;
8484
Richard Smitha0ce9c42014-07-29 23:23:27 +00008485 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008486 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008487 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8488 !Found && I != E; ++I) {
8489 for (auto RI : (*I)->redecls()) {
8490 if (RI->getLexicalDeclContext() == CanonDef) {
8491 // This declaration is present in the canonical definition. If it's
8492 // in the same redecl chain, it's the one we're looking for.
8493 if (RI->getCanonicalDecl() == DCanon)
8494 Found = true;
8495 else
8496 Candidates.push_back(cast<NamedDecl>(RI));
8497 break;
8498 }
8499 }
8500 }
8501
8502 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008503 // The AST doesn't like TagDecls becoming invalid after they've been
8504 // completed. We only really need to mark FieldDecls as invalid here.
8505 if (!isa<TagDecl>(D))
8506 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008507
8508 // Ensure we don't accidentally recursively enter deserialization while
8509 // we're producing our diagnostic.
8510 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008511
8512 std::string CanonDefModule =
8513 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8514 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8515 << D << getOwningModuleNameForDiagnostic(D)
8516 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8517
8518 if (Candidates.empty())
8519 Diag(cast<Decl>(CanonDef)->getLocation(),
8520 diag::note_module_odr_violation_no_possible_decls) << D;
8521 else {
8522 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8523 Diag(Candidates[I]->getLocation(),
8524 diag::note_module_odr_violation_possible_decl)
8525 << Candidates[I];
8526 }
8527
8528 DiagnosedOdrMergeFailures.insert(CanonDef);
8529 }
8530 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008531
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008532 if (OdrMergeFailures.empty())
8533 return;
8534
8535 // Ensure we don't accidentally recursively enter deserialization while
8536 // we're producing our diagnostics.
8537 Deserializing RecursionGuard(this);
8538
Richard Smithcd45dbc2014-04-19 03:48:30 +00008539 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008540 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008541 // If we've already pointed out a specific problem with this class, don't
8542 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008543 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008544 continue;
8545
8546 bool Diagnosed = false;
8547 for (auto *RD : Merge.second) {
8548 // Multiple different declarations got merged together; tell the user
8549 // where they came from.
8550 if (Merge.first != RD) {
8551 // FIXME: Walk the definition, figure out what's different,
8552 // and diagnose that.
8553 if (!Diagnosed) {
8554 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8555 Diag(Merge.first->getLocation(),
8556 diag::err_module_odr_violation_different_definitions)
8557 << Merge.first << Module.empty() << Module;
8558 Diagnosed = true;
8559 }
8560
8561 Diag(RD->getLocation(),
8562 diag::note_module_odr_violation_different_definitions)
8563 << getOwningModuleNameForDiagnostic(RD);
8564 }
8565 }
8566
8567 if (!Diagnosed) {
8568 // All definitions are updates to the same declaration. This happens if a
8569 // module instantiates the declaration of a class template specialization
8570 // and two or more other modules instantiate its definition.
8571 //
8572 // FIXME: Indicate which modules had instantiations of this definition.
8573 // FIXME: How can this even happen?
8574 Diag(Merge.first->getLocation(),
8575 diag::err_module_odr_violation_different_instantiations)
8576 << Merge.first;
8577 }
8578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008579}
8580
8581void ASTReader::FinishedDeserializing() {
8582 assert(NumCurrentElementsDeserializing &&
8583 "FinishedDeserializing not paired with StartedDeserializing");
8584 if (NumCurrentElementsDeserializing == 1) {
8585 // We decrease NumCurrentElementsDeserializing only after pending actions
8586 // are finished, to avoid recursively re-calling finishPendingActions().
8587 finishPendingActions();
8588 }
8589 --NumCurrentElementsDeserializing;
8590
Richard Smitha0ce9c42014-07-29 23:23:27 +00008591 if (NumCurrentElementsDeserializing == 0) {
8592 diagnoseOdrViolations();
8593
Richard Smith04d05b52014-03-23 00:27:18 +00008594 // We are not in recursive loading, so it's safe to pass the "interesting"
8595 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008596 if (Consumer)
8597 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008598 }
8599}
8600
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008601void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008602 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008603
8604 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8605 SemaObj->TUScope->AddDecl(D);
8606 } else if (SemaObj->TUScope) {
8607 // Adding the decl to IdResolver may have failed because it was already in
8608 // (even though it was not added in scope). If it is already in, make sure
8609 // it gets in the scope as well.
8610 if (std::find(SemaObj->IdResolver.begin(Name),
8611 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8612 SemaObj->TUScope->AddDecl(D);
8613 }
8614}
8615
Nico Weber824285e2014-05-08 04:26:47 +00008616ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8617 bool DisableValidation, bool AllowASTWithCompilerErrors,
8618 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008619 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008620 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008621 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008622 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8623 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8624 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8625 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008626 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8627 AllowConfigurationMismatch(AllowConfigurationMismatch),
8628 ValidateSystemInputs(ValidateSystemInputs),
8629 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008630 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008631 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8632 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8633 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8634 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8635 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8636 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8637 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8638 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8639 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8640 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8641 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 SourceMgr.setExternalSLocEntrySource(this);
8643}
8644
8645ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008646 if (OwnsDeserializationListener)
8647 delete DeserializationListener;
8648
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 for (DeclContextVisibleUpdatesPending::iterator
8650 I = PendingVisibleUpdates.begin(),
8651 E = PendingVisibleUpdates.end();
8652 I != E; ++I) {
8653 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8654 F = I->second.end();
8655 J != F; ++J)
8656 delete J->first;
8657 }
8658}