blob: 4de9919c88a1b0edb2d8f259ada0a6d1b40ce01d [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 "llvm/Support/system_error.h"
56#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
59
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}
Ben Langmuircb69b572014-03-07 06:40:32 +000083bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
84 bool Complain) {
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
87}
88bool
89ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
90 bool Complain) {
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
93}
94bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000096 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
98}
99bool
100ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
101 bool Complain) {
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
104}
105
106bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
110}
111bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
117}
118void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
119 unsigned Value) {
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
122}
123bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
126}
127bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
130}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000131void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
134}
Ben Langmuircb69b572014-03-07 06:40:32 +0000135bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000136 bool isSystem,
137 bool isOverridden) {
138 return First->visitInputFile(Filename, isSystem, isOverridden) ||
139 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000140}
141
Guy Benyei11169dd2012-12-18 14:30:41 +0000142//===----------------------------------------------------------------------===//
143// PCH validator implementation
144//===----------------------------------------------------------------------===//
145
146ASTReaderListener::~ASTReaderListener() {}
147
148/// \brief Compare the given set of language options against an existing set of
149/// language options.
150///
151/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
152///
153/// \returns true if the languagae options mis-match, false otherwise.
154static bool checkLanguageOptions(const LangOptions &LangOpts,
155 const LangOptions &ExistingLangOpts,
156 DiagnosticsEngine *Diags) {
157#define LANGOPT(Name, Bits, Default, Description) \
158 if (ExistingLangOpts.Name != LangOpts.Name) { \
159 if (Diags) \
160 Diags->Report(diag::err_pch_langopt_mismatch) \
161 << Description << LangOpts.Name << ExistingLangOpts.Name; \
162 return true; \
163 }
164
165#define VALUE_LANGOPT(Name, Bits, Default, Description) \
166 if (ExistingLangOpts.Name != LangOpts.Name) { \
167 if (Diags) \
168 Diags->Report(diag::err_pch_langopt_value_mismatch) \
169 << Description; \
170 return true; \
171 }
172
173#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
174 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
175 if (Diags) \
176 Diags->Report(diag::err_pch_langopt_value_mismatch) \
177 << Description; \
178 return true; \
179 }
180
181#define BENIGN_LANGOPT(Name, Bits, Default, Description)
182#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
183#include "clang/Basic/LangOptions.def"
184
185 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
186 if (Diags)
187 Diags->Report(diag::err_pch_langopt_value_mismatch)
188 << "target Objective-C runtime";
189 return true;
190 }
191
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000192 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
193 LangOpts.CommentOpts.BlockCommandNames) {
194 if (Diags)
195 Diags->Report(diag::err_pch_langopt_value_mismatch)
196 << "block command names";
197 return true;
198 }
199
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 return false;
201}
202
203/// \brief Compare the given set of target options against an existing set of
204/// target options.
205///
206/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
207///
208/// \returns true if the target options mis-match, false otherwise.
209static bool checkTargetOptions(const TargetOptions &TargetOpts,
210 const TargetOptions &ExistingTargetOpts,
211 DiagnosticsEngine *Diags) {
212#define CHECK_TARGET_OPT(Field, Name) \
213 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
214 if (Diags) \
215 Diags->Report(diag::err_pch_targetopt_mismatch) \
216 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
217 return true; \
218 }
219
220 CHECK_TARGET_OPT(Triple, "target");
221 CHECK_TARGET_OPT(CPU, "target CPU");
222 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000223#undef CHECK_TARGET_OPT
224
225 // Compare feature sets.
226 SmallVector<StringRef, 4> ExistingFeatures(
227 ExistingTargetOpts.FeaturesAsWritten.begin(),
228 ExistingTargetOpts.FeaturesAsWritten.end());
229 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
230 TargetOpts.FeaturesAsWritten.end());
231 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
232 std::sort(ReadFeatures.begin(), ReadFeatures.end());
233
234 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
235 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
236 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
237 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
238 ++ExistingIdx;
239 ++ReadIdx;
240 continue;
241 }
242
243 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
244 if (Diags)
245 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
246 << false << ReadFeatures[ReadIdx];
247 return true;
248 }
249
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << true << ExistingFeatures[ExistingIdx];
253 return true;
254 }
255
256 if (ExistingIdx < ExistingN) {
257 if (Diags)
258 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
259 << true << ExistingFeatures[ExistingIdx];
260 return true;
261 }
262
263 if (ReadIdx < ReadN) {
264 if (Diags)
265 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
266 << false << ReadFeatures[ReadIdx];
267 return true;
268 }
269
270 return false;
271}
272
273bool
274PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
275 bool Complain) {
276 const LangOptions &ExistingLangOpts = PP.getLangOpts();
277 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000278 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000279}
280
281bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
282 bool Complain) {
283 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
284 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000285 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000286}
287
288namespace {
289 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
290 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000291 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
292 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
Ben Langmuirb92de022014-04-29 16:25:26 +0000295static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
296 DiagnosticsEngine &Diags,
297 bool Complain) {
298 typedef DiagnosticsEngine::Level Level;
299
300 // Check current mappings for new -Werror mappings, and the stored mappings
301 // for cases that were explicitly mapped to *not* be errors that are now
302 // errors because of options like -Werror.
303 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
304
305 for (DiagnosticsEngine *MappingSource : MappingSources) {
306 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
307 diag::kind DiagID = DiagIDMappingPair.first;
308 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
309 if (CurLevel < DiagnosticsEngine::Error)
310 continue; // not significant
311 Level StoredLevel =
312 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
313 if (StoredLevel < DiagnosticsEngine::Error) {
314 if (Complain)
315 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
316 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
317 return true;
318 }
319 }
320 }
321
322 return false;
323}
324
325static DiagnosticsEngine::ExtensionHandling
326isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
327 DiagnosticsEngine::ExtensionHandling Ext =
328 Diags.getExtensionHandlingBehavior();
329 if (Ext == DiagnosticsEngine::Ext_Warn && Diags.getWarningsAsErrors())
330 Ext = DiagnosticsEngine::Ext_Error;
331 return Ext;
332}
333
334static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
335 DiagnosticsEngine &Diags,
336 bool IsSystem, bool Complain) {
337 // Top-level options
338 if (IsSystem) {
339 if (Diags.getSuppressSystemWarnings())
340 return false;
341 // If -Wsystem-headers was not enabled before, be conservative
342 if (StoredDiags.getSuppressSystemWarnings()) {
343 if (Complain)
344 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
345 return true;
346 }
347 }
348
349 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
350 if (Complain)
351 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
352 return true;
353 }
354
355 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
356 !StoredDiags.getEnableAllWarnings()) {
357 if (Complain)
358 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
359 return true;
360 }
361
362 if (isExtHandlingFromDiagsError(Diags) &&
363 !isExtHandlingFromDiagsError(StoredDiags)) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
366 return true;
367 }
368
369 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
370}
371
372bool PCHValidator::ReadDiagnosticOptions(
373 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
374 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
375 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
376 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
377 new DiagnosticsEngine(DiagIDs, DiagOpts.getPtr()));
378 // This should never fail, because we would have processed these options
379 // before writing them to an ASTFile.
380 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
381
382 ModuleManager &ModuleMgr = Reader.getModuleManager();
383 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
384
385 // If the original import came from a file explicitly generated by the user,
386 // don't check the diagnostic mappings.
387 // FIXME: currently this is approximated by checking whether this is not a
388 // module import.
389 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
390 // the transitive closure of its imports, since unrelated modules cannot be
391 // imported until after this module finishes validation.
392 ModuleFile *TopImport = *ModuleMgr.rbegin();
393 while (!TopImport->ImportedBy.empty())
394 TopImport = TopImport->ImportedBy[0];
395 if (TopImport->Kind != MK_Module)
396 return false;
397
398 StringRef ModuleName = TopImport->ModuleName;
399 assert(!ModuleName.empty() && "diagnostic options read before module name");
400
401 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
402 assert(M && "missing module");
403
404 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
405 // contains the union of their flags.
406 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
407}
408
Guy Benyei11169dd2012-12-18 14:30:41 +0000409/// \brief Collect the macro definitions provided by the given preprocessor
410/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000411static void
412collectMacroDefinitions(const PreprocessorOptions &PPOpts,
413 MacroDefinitionsMap &Macros,
414 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000415 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
416 StringRef Macro = PPOpts.Macros[I].first;
417 bool IsUndef = PPOpts.Macros[I].second;
418
419 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
420 StringRef MacroName = MacroPair.first;
421 StringRef MacroBody = MacroPair.second;
422
423 // For an #undef'd macro, we only care about the name.
424 if (IsUndef) {
425 if (MacroNames && !Macros.count(MacroName))
426 MacroNames->push_back(MacroName);
427
428 Macros[MacroName] = std::make_pair("", true);
429 continue;
430 }
431
432 // For a #define'd macro, figure out the actual definition.
433 if (MacroName.size() == Macro.size())
434 MacroBody = "1";
435 else {
436 // Note: GCC drops anything following an end-of-line character.
437 StringRef::size_type End = MacroBody.find_first_of("\n\r");
438 MacroBody = MacroBody.substr(0, End);
439 }
440
441 if (MacroNames && !Macros.count(MacroName))
442 MacroNames->push_back(MacroName);
443 Macros[MacroName] = std::make_pair(MacroBody, false);
444 }
445}
446
447/// \brief Check the preprocessor options deserialized from the control block
448/// against the preprocessor options in an existing preprocessor.
449///
450/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
451static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
452 const PreprocessorOptions &ExistingPPOpts,
453 DiagnosticsEngine *Diags,
454 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000455 std::string &SuggestedPredefines,
456 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 // Check macro definitions.
458 MacroDefinitionsMap ASTFileMacros;
459 collectMacroDefinitions(PPOpts, ASTFileMacros);
460 MacroDefinitionsMap ExistingMacros;
461 SmallVector<StringRef, 4> ExistingMacroNames;
462 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
463
464 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
465 // Dig out the macro definition in the existing preprocessor options.
466 StringRef MacroName = ExistingMacroNames[I];
467 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
468
469 // Check whether we know anything about this macro name or not.
470 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
471 = ASTFileMacros.find(MacroName);
472 if (Known == ASTFileMacros.end()) {
473 // FIXME: Check whether this identifier was referenced anywhere in the
474 // AST file. If so, we should reject the AST file. Unfortunately, this
475 // information isn't in the control block. What shall we do about it?
476
477 if (Existing.second) {
478 SuggestedPredefines += "#undef ";
479 SuggestedPredefines += MacroName.str();
480 SuggestedPredefines += '\n';
481 } else {
482 SuggestedPredefines += "#define ";
483 SuggestedPredefines += MacroName.str();
484 SuggestedPredefines += ' ';
485 SuggestedPredefines += Existing.first.str();
486 SuggestedPredefines += '\n';
487 }
488 continue;
489 }
490
491 // If the macro was defined in one but undef'd in the other, we have a
492 // conflict.
493 if (Existing.second != Known->second.second) {
494 if (Diags) {
495 Diags->Report(diag::err_pch_macro_def_undef)
496 << MacroName << Known->second.second;
497 }
498 return true;
499 }
500
501 // If the macro was #undef'd in both, or if the macro bodies are identical,
502 // it's fine.
503 if (Existing.second || Existing.first == Known->second.first)
504 continue;
505
506 // The macro bodies differ; complain.
507 if (Diags) {
508 Diags->Report(diag::err_pch_macro_def_conflict)
509 << MacroName << Known->second.first << Existing.first;
510 }
511 return true;
512 }
513
514 // Check whether we're using predefines.
515 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
516 if (Diags) {
517 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
518 }
519 return true;
520 }
521
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000522 // Detailed record is important since it is used for the module cache hash.
523 if (LangOpts.Modules &&
524 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
527 }
528 return true;
529 }
530
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 // Compute the #include and #include_macros lines we need.
532 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
533 StringRef File = ExistingPPOpts.Includes[I];
534 if (File == ExistingPPOpts.ImplicitPCHInclude)
535 continue;
536
537 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
538 != PPOpts.Includes.end())
539 continue;
540
541 SuggestedPredefines += "#include \"";
542 SuggestedPredefines +=
543 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
544 SuggestedPredefines += "\"\n";
545 }
546
547 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
548 StringRef File = ExistingPPOpts.MacroIncludes[I];
549 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
550 File)
551 != PPOpts.MacroIncludes.end())
552 continue;
553
554 SuggestedPredefines += "#__include_macros \"";
555 SuggestedPredefines +=
556 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
557 SuggestedPredefines += "\"\n##\n";
558 }
559
560 return false;
561}
562
563bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
564 bool Complain,
565 std::string &SuggestedPredefines) {
566 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
567
568 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000569 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000571 SuggestedPredefines,
572 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000573}
574
Guy Benyei11169dd2012-12-18 14:30:41 +0000575void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
576 PP.setCounterValue(Value);
577}
578
579//===----------------------------------------------------------------------===//
580// AST reader implementation
581//===----------------------------------------------------------------------===//
582
Nico Weber824285e2014-05-08 04:26:47 +0000583void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
584 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000586 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000587}
588
589
590
591unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
592 return serialization::ComputeHash(Sel);
593}
594
595
596std::pair<unsigned, unsigned>
597ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000598 using namespace llvm::support;
599 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
600 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 return std::make_pair(KeyLen, DataLen);
602}
603
604ASTSelectorLookupTrait::internal_key_type
605ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000606 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000608 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
609 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
610 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 if (N == 0)
612 return SelTable.getNullarySelector(FirstII);
613 else if (N == 1)
614 return SelTable.getUnarySelector(FirstII);
615
616 SmallVector<IdentifierInfo *, 16> Args;
617 Args.push_back(FirstII);
618 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000619 Args.push_back(Reader.getLocalIdentifier(
620 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000621
622 return SelTable.getSelector(N, Args.data());
623}
624
625ASTSelectorLookupTrait::data_type
626ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
627 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000628 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000629
630 data_type Result;
631
Justin Bogner57ba0b22014-03-28 22:03:24 +0000632 Result.ID = Reader.getGlobalSelectorID(
633 F, endian::readNext<uint32_t, little, unaligned>(d));
634 unsigned NumInstanceMethodsAndBits =
635 endian::readNext<uint16_t, little, unaligned>(d);
636 unsigned NumFactoryMethodsAndBits =
637 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000638 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
639 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
640 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
641 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000642
643 // Load instance methods
644 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000645 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
646 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 Result.Instance.push_back(Method);
648 }
649
650 // Load factory methods
651 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000652 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
653 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000654 Result.Factory.push_back(Method);
655 }
656
657 return Result;
658}
659
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000660unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
661 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000662}
663
664std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000665ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000666 using namespace llvm::support;
667 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
668 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000669 return std::make_pair(KeyLen, DataLen);
670}
671
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000672ASTIdentifierLookupTraitBase::internal_key_type
673ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000675 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000676}
677
Douglas Gregordcf25082013-02-11 18:16:18 +0000678/// \brief Whether the given identifier is "interesting".
679static bool isInterestingIdentifier(IdentifierInfo &II) {
680 return II.isPoisoned() ||
681 II.isExtensionToken() ||
682 II.getObjCOrBuiltinID() ||
683 II.hasRevertedTokenIDToIdentifier() ||
684 II.hadMacroDefinition() ||
685 II.getFETokenInfo<void>();
686}
687
Guy Benyei11169dd2012-12-18 14:30:41 +0000688IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
689 const unsigned char* d,
690 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
692 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 bool IsInteresting = RawID & 0x01;
694
695 // Wipe out the "is interesting" bit.
696 RawID = RawID >> 1;
697
698 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
699 if (!IsInteresting) {
700 // For uninteresting identifiers, just build the IdentifierInfo
701 // and associate it with the persistent ID.
702 IdentifierInfo *II = KnownII;
703 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000704 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000705 KnownII = II;
706 }
707 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000708 if (!II->isFromAST()) {
709 bool WasInteresting = isInterestingIdentifier(*II);
710 II->setIsFromAST();
711 if (WasInteresting)
712 II->setChangedSinceDeserialization();
713 }
714 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000715 return II;
716 }
717
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
719 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000720 bool CPlusPlusOperatorKeyword = Bits & 0x01;
721 Bits >>= 1;
722 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
723 Bits >>= 1;
724 bool Poisoned = Bits & 0x01;
725 Bits >>= 1;
726 bool ExtensionToken = Bits & 0x01;
727 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000728 bool hasSubmoduleMacros = Bits & 0x01;
729 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 bool hadMacroDefinition = Bits & 0x01;
731 Bits >>= 1;
732
733 assert(Bits == 0 && "Extra bits in the identifier?");
734 DataLen -= 8;
735
736 // Build the IdentifierInfo itself and link the identifier ID with
737 // the new IdentifierInfo.
738 IdentifierInfo *II = KnownII;
739 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000740 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 KnownII = II;
742 }
743 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000744 if (!II->isFromAST()) {
745 bool WasInteresting = isInterestingIdentifier(*II);
746 II->setIsFromAST();
747 if (WasInteresting)
748 II->setChangedSinceDeserialization();
749 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000750
751 // Set or check the various bits in the IdentifierInfo structure.
752 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000753 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 II->RevertTokenIDToIdentifier();
755 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
756 assert(II->isExtensionToken() == ExtensionToken &&
757 "Incorrect extension token flag");
758 (void)ExtensionToken;
759 if (Poisoned)
760 II->setIsPoisoned(true);
761 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
762 "Incorrect C++ operator keyword flag");
763 (void)CPlusPlusOperatorKeyword;
764
765 // If this identifier is a macro, deserialize the macro
766 // definition.
767 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000768 uint32_t MacroDirectivesOffset =
769 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000770 DataLen -= 4;
771 SmallVector<uint32_t, 8> LocalMacroIDs;
772 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000773 while (uint32_t LocalMacroID =
774 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000775 DataLen -= 4;
776 LocalMacroIDs.push_back(LocalMacroID);
777 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000778 DataLen -= 4;
779 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780
781 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000782 // Macro definitions are stored from newest to oldest, so reverse them
783 // before registering them.
784 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000785 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000786 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
787 unsigned Size = 1;
788
789 static const uint32_t HasOverridesFlag = 0x80000000U;
790 if (I + 1 != E && (I[1] & HasOverridesFlag))
791 Size += 1 + (I[1] & ~HasOverridesFlag);
792
793 MacroSizes.push_back(Size);
794 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000795 }
Richard Smith49f906a2014-03-01 00:08:04 +0000796
797 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
798 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
799 SE = MacroSizes.rend();
800 SI != SE; ++SI) {
801 I -= *SI;
802
803 uint32_t LocalMacroID = *I;
804 llvm::ArrayRef<uint32_t> Overrides;
805 if (*SI != 1)
806 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
807 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
808 }
809 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000810 } else {
811 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
812 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 }
814
815 Reader.SetIdentifierInfo(ID, II);
816
817 // Read all of the declarations visible at global scope with this
818 // name.
819 if (DataLen > 0) {
820 SmallVector<uint32_t, 4> DeclIDs;
821 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000822 DeclIDs.push_back(Reader.getGlobalDeclID(
823 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 Reader.SetGloballyVisibleDecls(II, DeclIDs);
825 }
826
827 return II;
828}
829
830unsigned
831ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
832 llvm::FoldingSetNodeID ID;
833 ID.AddInteger(Key.Kind);
834
835 switch (Key.Kind) {
836 case DeclarationName::Identifier:
837 case DeclarationName::CXXLiteralOperatorName:
838 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
839 break;
840 case DeclarationName::ObjCZeroArgSelector:
841 case DeclarationName::ObjCOneArgSelector:
842 case DeclarationName::ObjCMultiArgSelector:
843 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
844 break;
845 case DeclarationName::CXXOperatorName:
846 ID.AddInteger((OverloadedOperatorKind)Key.Data);
847 break;
848 case DeclarationName::CXXConstructorName:
849 case DeclarationName::CXXDestructorName:
850 case DeclarationName::CXXConversionFunctionName:
851 case DeclarationName::CXXUsingDirective:
852 break;
853 }
854
855 return ID.ComputeHash();
856}
857
858ASTDeclContextNameLookupTrait::internal_key_type
859ASTDeclContextNameLookupTrait::GetInternalKey(
860 const external_key_type& Name) const {
861 DeclNameKey Key;
862 Key.Kind = Name.getNameKind();
863 switch (Name.getNameKind()) {
864 case DeclarationName::Identifier:
865 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
866 break;
867 case DeclarationName::ObjCZeroArgSelector:
868 case DeclarationName::ObjCOneArgSelector:
869 case DeclarationName::ObjCMultiArgSelector:
870 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
871 break;
872 case DeclarationName::CXXOperatorName:
873 Key.Data = Name.getCXXOverloadedOperator();
874 break;
875 case DeclarationName::CXXLiteralOperatorName:
876 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
877 break;
878 case DeclarationName::CXXConstructorName:
879 case DeclarationName::CXXDestructorName:
880 case DeclarationName::CXXConversionFunctionName:
881 case DeclarationName::CXXUsingDirective:
882 Key.Data = 0;
883 break;
884 }
885
886 return Key;
887}
888
889std::pair<unsigned, unsigned>
890ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000891 using namespace llvm::support;
892 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
893 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000894 return std::make_pair(KeyLen, DataLen);
895}
896
897ASTDeclContextNameLookupTrait::internal_key_type
898ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000899 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000900
901 DeclNameKey Key;
902 Key.Kind = (DeclarationName::NameKind)*d++;
903 switch (Key.Kind) {
904 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000905 Key.Data = (uint64_t)Reader.getLocalIdentifier(
906 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 break;
908 case DeclarationName::ObjCZeroArgSelector:
909 case DeclarationName::ObjCOneArgSelector:
910 case DeclarationName::ObjCMultiArgSelector:
911 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 (uint64_t)Reader.getLocalSelector(
913 F, endian::readNext<uint32_t, little, unaligned>(
914 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000915 break;
916 case DeclarationName::CXXOperatorName:
917 Key.Data = *d++; // OverloadedOperatorKind
918 break;
919 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000920 Key.Data = (uint64_t)Reader.getLocalIdentifier(
921 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000922 break;
923 case DeclarationName::CXXConstructorName:
924 case DeclarationName::CXXDestructorName:
925 case DeclarationName::CXXConversionFunctionName:
926 case DeclarationName::CXXUsingDirective:
927 Key.Data = 0;
928 break;
929 }
930
931 return Key;
932}
933
934ASTDeclContextNameLookupTrait::data_type
935ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
936 const unsigned char* d,
937 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000938 using namespace llvm::support;
939 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000940 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
941 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 return std::make_pair(Start, Start + NumDecls);
943}
944
945bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000946 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 const std::pair<uint64_t, uint64_t> &Offsets,
948 DeclContextInfo &Info) {
949 SavedStreamPosition SavedPosition(Cursor);
950 // First the lexical decls.
951 if (Offsets.first != 0) {
952 Cursor.JumpToBit(Offsets.first);
953
954 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000955 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000957 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 if (RecCode != DECL_CONTEXT_LEXICAL) {
959 Error("Expected lexical block");
960 return true;
961 }
962
Chris Lattner0e6c9402013-01-20 02:38:54 +0000963 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
964 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 }
966
967 // Now the lookup table.
968 if (Offsets.second != 0) {
969 Cursor.JumpToBit(Offsets.second);
970
971 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000972 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 if (RecCode != DECL_CONTEXT_VISIBLE) {
976 Error("Expected visible lookup table block");
977 return true;
978 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000979 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
980 (const unsigned char *)Blob.data() + Record[0],
981 (const unsigned char *)Blob.data() + sizeof(uint32_t),
982 (const unsigned char *)Blob.data(),
983 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 }
985
986 return false;
987}
988
989void ASTReader::Error(StringRef Msg) {
990 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000991 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
992 Diag(diag::note_module_cache_path)
993 << PP.getHeaderSearchInfo().getModuleCachePath();
994 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000995}
996
997void ASTReader::Error(unsigned DiagID,
998 StringRef Arg1, StringRef Arg2) {
999 if (Diags.isDiagnosticInFlight())
1000 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1001 else
1002 Diag(DiagID) << Arg1 << Arg2;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// Source Manager Deserialization
1007//===----------------------------------------------------------------------===//
1008
1009/// \brief Read the line table in the source manager block.
1010/// \returns true if there was an error.
1011bool ASTReader::ParseLineTable(ModuleFile &F,
1012 SmallVectorImpl<uint64_t> &Record) {
1013 unsigned Idx = 0;
1014 LineTableInfo &LineTable = SourceMgr.getLineTable();
1015
1016 // Parse the file names
1017 std::map<int, int> FileIDs;
1018 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1019 // Extract the file name
1020 unsigned FilenameLen = Record[Idx++];
1021 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1022 Idx += FilenameLen;
1023 MaybeAddSystemRootToFilename(F, Filename);
1024 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1025 }
1026
1027 // Parse the line entries
1028 std::vector<LineEntry> Entries;
1029 while (Idx < Record.size()) {
1030 int FID = Record[Idx++];
1031 assert(FID >= 0 && "Serialized line entries for non-local file.");
1032 // Remap FileID from 1-based old view.
1033 FID += F.SLocEntryBaseID - 1;
1034
1035 // Extract the line entries
1036 unsigned NumEntries = Record[Idx++];
1037 assert(NumEntries && "Numentries is 00000");
1038 Entries.clear();
1039 Entries.reserve(NumEntries);
1040 for (unsigned I = 0; I != NumEntries; ++I) {
1041 unsigned FileOffset = Record[Idx++];
1042 unsigned LineNo = Record[Idx++];
1043 int FilenameID = FileIDs[Record[Idx++]];
1044 SrcMgr::CharacteristicKind FileKind
1045 = (SrcMgr::CharacteristicKind)Record[Idx++];
1046 unsigned IncludeOffset = Record[Idx++];
1047 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1048 FileKind, IncludeOffset));
1049 }
1050 LineTable.AddEntry(FileID::get(FID), Entries);
1051 }
1052
1053 return false;
1054}
1055
1056/// \brief Read a source manager block
1057bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1058 using namespace SrcMgr;
1059
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001060 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001061
1062 // Set the source-location entry cursor to the current position in
1063 // the stream. This cursor will be used to read the contents of the
1064 // source manager block initially, and then lazily read
1065 // source-location entries as needed.
1066 SLocEntryCursor = F.Stream;
1067
1068 // The stream itself is going to skip over the source manager block.
1069 if (F.Stream.SkipBlock()) {
1070 Error("malformed block record in AST file");
1071 return true;
1072 }
1073
1074 // Enter the source manager block.
1075 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1076 Error("malformed source manager block record in AST file");
1077 return true;
1078 }
1079
1080 RecordData Record;
1081 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001082 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1083
1084 switch (E.Kind) {
1085 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1086 case llvm::BitstreamEntry::Error:
1087 Error("malformed block record in AST file");
1088 return true;
1089 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001090 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001091 case llvm::BitstreamEntry::Record:
1092 // The interesting case.
1093 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001095
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001098 StringRef Blob;
1099 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 default: // Default behavior: ignore.
1101 break;
1102
1103 case SM_SLOC_FILE_ENTRY:
1104 case SM_SLOC_BUFFER_ENTRY:
1105 case SM_SLOC_EXPANSION_ENTRY:
1106 // Once we hit one of the source location entries, we're done.
1107 return false;
1108 }
1109 }
1110}
1111
1112/// \brief If a header file is not found at the path that we expect it to be
1113/// and the PCH file was moved from its original location, try to resolve the
1114/// file by assuming that header+PCH were moved together and the header is in
1115/// the same place relative to the PCH.
1116static std::string
1117resolveFileRelativeToOriginalDir(const std::string &Filename,
1118 const std::string &OriginalDir,
1119 const std::string &CurrDir) {
1120 assert(OriginalDir != CurrDir &&
1121 "No point trying to resolve the file if the PCH dir didn't change");
1122 using namespace llvm::sys;
1123 SmallString<128> filePath(Filename);
1124 fs::make_absolute(filePath);
1125 assert(path::is_absolute(OriginalDir));
1126 SmallString<128> currPCHPath(CurrDir);
1127
1128 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1129 fileDirE = path::end(path::parent_path(filePath));
1130 path::const_iterator origDirI = path::begin(OriginalDir),
1131 origDirE = path::end(OriginalDir);
1132 // Skip the common path components from filePath and OriginalDir.
1133 while (fileDirI != fileDirE && origDirI != origDirE &&
1134 *fileDirI == *origDirI) {
1135 ++fileDirI;
1136 ++origDirI;
1137 }
1138 for (; origDirI != origDirE; ++origDirI)
1139 path::append(currPCHPath, "..");
1140 path::append(currPCHPath, fileDirI, fileDirE);
1141 path::append(currPCHPath, path::filename(Filename));
1142 return currPCHPath.str();
1143}
1144
1145bool ASTReader::ReadSLocEntry(int ID) {
1146 if (ID == 0)
1147 return false;
1148
1149 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1150 Error("source location entry ID out-of-range for AST file");
1151 return true;
1152 }
1153
1154 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1155 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001156 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001157 unsigned BaseOffset = F->SLocEntryBaseOffset;
1158
1159 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001160 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1161 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 Error("incorrectly-formatted source location entry in AST file");
1163 return true;
1164 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001165
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001167 StringRef Blob;
1168 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 default:
1170 Error("incorrectly-formatted source location entry in AST file");
1171 return true;
1172
1173 case SM_SLOC_FILE_ENTRY: {
1174 // We will detect whether a file changed and return 'Failure' for it, but
1175 // we will also try to fail gracefully by setting up the SLocEntry.
1176 unsigned InputID = Record[4];
1177 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001178 const FileEntry *File = IF.getFile();
1179 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001180
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001181 // Note that we only check if a File was returned. If it was out-of-date
1182 // we have complained but we will continue creating a FileID to recover
1183 // gracefully.
1184 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 return true;
1186
1187 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1188 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1189 // This is the module's main file.
1190 IncludeLoc = getImportLocation(F);
1191 }
1192 SrcMgr::CharacteristicKind
1193 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1194 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1195 ID, BaseOffset + Record[0]);
1196 SrcMgr::FileInfo &FileInfo =
1197 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1198 FileInfo.NumCreatedFIDs = Record[5];
1199 if (Record[3])
1200 FileInfo.setHasLineDirectives();
1201
1202 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1203 unsigned NumFileDecls = Record[7];
1204 if (NumFileDecls) {
1205 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1206 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1207 NumFileDecls));
1208 }
1209
1210 const SrcMgr::ContentCache *ContentCache
1211 = SourceMgr.getOrCreateContentCache(File,
1212 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1213 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1214 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1215 unsigned Code = SLocEntryCursor.ReadCode();
1216 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001217 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001218
1219 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1220 Error("AST record has invalid code");
1221 return true;
1222 }
1223
1224 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001225 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 SourceMgr.overrideFileContents(File, Buffer);
1227 }
1228
1229 break;
1230 }
1231
1232 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001233 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 unsigned Offset = Record[0];
1235 SrcMgr::CharacteristicKind
1236 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1237 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1238 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1239 IncludeLoc = getImportLocation(F);
1240 }
1241 unsigned Code = SLocEntryCursor.ReadCode();
1242 Record.clear();
1243 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001244 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001245
1246 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1247 Error("AST record has invalid code");
1248 return true;
1249 }
1250
1251 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001252 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001253 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1254 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 break;
1256 }
1257
1258 case SM_SLOC_EXPANSION_ENTRY: {
1259 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1260 SourceMgr.createExpansionLoc(SpellingLoc,
1261 ReadSourceLocation(*F, Record[2]),
1262 ReadSourceLocation(*F, Record[3]),
1263 Record[4],
1264 ID,
1265 BaseOffset + Record[0]);
1266 break;
1267 }
1268 }
1269
1270 return false;
1271}
1272
1273std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1274 if (ID == 0)
1275 return std::make_pair(SourceLocation(), "");
1276
1277 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1278 Error("source location entry ID out-of-range for AST file");
1279 return std::make_pair(SourceLocation(), "");
1280 }
1281
1282 // Find which module file this entry lands in.
1283 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1284 if (M->Kind != MK_Module)
1285 return std::make_pair(SourceLocation(), "");
1286
1287 // FIXME: Can we map this down to a particular submodule? That would be
1288 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001289 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001290}
1291
1292/// \brief Find the location where the module F is imported.
1293SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1294 if (F->ImportLoc.isValid())
1295 return F->ImportLoc;
1296
1297 // Otherwise we have a PCH. It's considered to be "imported" at the first
1298 // location of its includer.
1299 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001300 // Main file is the importer.
1301 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1302 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 return F->ImportedBy[0]->FirstLoc;
1305}
1306
1307/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1308/// specified cursor. Read the abbreviations that are at the top of the block
1309/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001310bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 if (Cursor.EnterSubBlock(BlockID)) {
1312 Error("malformed block record in AST file");
1313 return Failure;
1314 }
1315
1316 while (true) {
1317 uint64_t Offset = Cursor.GetCurrentBitNo();
1318 unsigned Code = Cursor.ReadCode();
1319
1320 // We expect all abbrevs to be at the start of the block.
1321 if (Code != llvm::bitc::DEFINE_ABBREV) {
1322 Cursor.JumpToBit(Offset);
1323 return false;
1324 }
1325 Cursor.ReadAbbrevRecord();
1326 }
1327}
1328
Richard Smithe40f2ba2013-08-07 21:41:30 +00001329Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001330 unsigned &Idx) {
1331 Token Tok;
1332 Tok.startToken();
1333 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1334 Tok.setLength(Record[Idx++]);
1335 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1336 Tok.setIdentifierInfo(II);
1337 Tok.setKind((tok::TokenKind)Record[Idx++]);
1338 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1339 return Tok;
1340}
1341
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001342MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001343 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001344
1345 // Keep track of where we are in the stream, then jump back there
1346 // after reading this macro.
1347 SavedStreamPosition SavedPosition(Stream);
1348
1349 Stream.JumpToBit(Offset);
1350 RecordData Record;
1351 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001352 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001353
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001355 // Advance to the next record, but if we get to the end of the block, don't
1356 // pop it (removing all the abbreviations from the cursor) since we want to
1357 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001358 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001359 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1360
1361 switch (Entry.Kind) {
1362 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1363 case llvm::BitstreamEntry::Error:
1364 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001365 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001366 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001367 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001368 case llvm::BitstreamEntry::Record:
1369 // The interesting case.
1370 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 }
1372
1373 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 Record.clear();
1375 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001376 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001378 case PP_MACRO_DIRECTIVE_HISTORY:
1379 return Macro;
1380
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 case PP_MACRO_OBJECT_LIKE:
1382 case PP_MACRO_FUNCTION_LIKE: {
1383 // If we already have a macro, that means that we've hit the end
1384 // of the definition of the macro we were looking for. We're
1385 // done.
1386 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001388
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001389 unsigned NextIndex = 1; // Skip identifier ID.
1390 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001393 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001395 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001396
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1398 // Decode function-like macro info.
1399 bool isC99VarArgs = Record[NextIndex++];
1400 bool isGNUVarArgs = Record[NextIndex++];
1401 bool hasCommaPasting = Record[NextIndex++];
1402 MacroArgs.clear();
1403 unsigned NumArgs = Record[NextIndex++];
1404 for (unsigned i = 0; i != NumArgs; ++i)
1405 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1406
1407 // Install function-like macro info.
1408 MI->setIsFunctionLike();
1409 if (isC99VarArgs) MI->setIsC99Varargs();
1410 if (isGNUVarArgs) MI->setIsGNUVarargs();
1411 if (hasCommaPasting) MI->setHasCommaPasting();
1412 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1413 PP.getPreprocessorAllocator());
1414 }
1415
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 // Remember that we saw this macro last so that we add the tokens that
1417 // form its body to it.
1418 Macro = MI;
1419
1420 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1421 Record[NextIndex]) {
1422 // We have a macro definition. Register the association
1423 PreprocessedEntityID
1424 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1425 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001426 PreprocessingRecord::PPEntityID
1427 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1428 MacroDefinition *PPDef =
1429 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1430 if (PPDef)
1431 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 }
1433
1434 ++NumMacrosRead;
1435 break;
1436 }
1437
1438 case PP_TOKEN: {
1439 // If we see a TOKEN before a PP_MACRO_*, then the file is
1440 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001441 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001442
John McCallf413f5e2013-05-03 00:10:13 +00001443 unsigned Idx = 0;
1444 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 Macro->AddTokenToBody(Tok);
1446 break;
1447 }
1448 }
1449 }
1450}
1451
1452PreprocessedEntityID
1453ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1454 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1455 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1456 assert(I != M.PreprocessedEntityRemap.end()
1457 && "Invalid index into preprocessed entity index remap");
1458
1459 return LocalID + I->second;
1460}
1461
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001462unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1463 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001464}
1465
1466HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001467HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1468 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1469 FE->getName() };
1470 return ikey;
1471}
Guy Benyei11169dd2012-12-18 14:30:41 +00001472
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001473bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1474 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 return false;
1476
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001477 if (strcmp(a.Filename, b.Filename) == 0)
1478 return true;
1479
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001481 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1483 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001484 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001485}
1486
1487std::pair<unsigned, unsigned>
1488HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001489 using namespace llvm::support;
1490 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001493}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001494
1495HeaderFileInfoTrait::internal_key_type
1496HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001497 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001499 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1500 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001501 ikey.Filename = (const char *)d;
1502 return ikey;
1503}
1504
Guy Benyei11169dd2012-12-18 14:30:41 +00001505HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001506HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 unsigned DataLen) {
1508 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001509 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 HeaderFileInfo HFI;
1511 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001512 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1513 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 HFI.isImport = (Flags >> 5) & 0x01;
1515 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1516 HFI.DirInfo = (Flags >> 2) & 0x03;
1517 HFI.Resolved = (Flags >> 1) & 0x01;
1518 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001519 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1520 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1521 M, endian::readNext<uint32_t, little, unaligned>(d));
1522 if (unsigned FrameworkOffset =
1523 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 // The framework offset is 1 greater than the actual offset,
1525 // since 0 is used as an indicator for "no framework name".
1526 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1527 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1528 }
1529
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001530 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001531 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001532 if (LocalSMID) {
1533 // This header is part of a module. Associate it with the module to enable
1534 // implicit module import.
1535 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1536 Module *Mod = Reader.getSubmodule(GlobalSMID);
1537 HFI.isModuleHeader = true;
1538 FileManager &FileMgr = Reader.getFileManager();
1539 ModuleMap &ModMap =
1540 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001541 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001542 }
1543 }
1544
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1546 (void)End;
1547
1548 // This HeaderFileInfo was externally loaded.
1549 HFI.External = true;
1550 return HFI;
1551}
1552
Richard Smith49f906a2014-03-01 00:08:04 +00001553void
1554ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1555 GlobalMacroID GMacID,
1556 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001558 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001559 if (!Overrides.empty()) {
1560 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1561 OverrideData[0] = Overrides.size();
1562 for (unsigned I = 0; I != Overrides.size(); ++I)
1563 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1564 }
1565 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001566}
1567
1568void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1569 ModuleFile *M,
1570 uint64_t MacroDirectivesOffset) {
1571 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1572 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001573}
1574
1575void ASTReader::ReadDefinedMacros() {
1576 // Note that we are loading defined macros.
1577 Deserializing Macros(this);
1578
1579 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1580 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001581 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001582
1583 // If there was no preprocessor block, skip this file.
1584 if (!MacroCursor.getBitStreamReader())
1585 continue;
1586
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001587 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001588 Cursor.JumpToBit((*I)->MacroStartOffset);
1589
1590 RecordData Record;
1591 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001592 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1593
1594 switch (E.Kind) {
1595 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1596 case llvm::BitstreamEntry::Error:
1597 Error("malformed block record in AST file");
1598 return;
1599 case llvm::BitstreamEntry::EndBlock:
1600 goto NextCursor;
1601
1602 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001603 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001604 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001605 default: // Default behavior: ignore.
1606 break;
1607
1608 case PP_MACRO_OBJECT_LIKE:
1609 case PP_MACRO_FUNCTION_LIKE:
1610 getLocalIdentifier(**I, Record[0]);
1611 break;
1612
1613 case PP_TOKEN:
1614 // Ignore tokens.
1615 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 break;
1618 }
1619 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001620 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 }
1622}
1623
1624namespace {
1625 /// \brief Visitor class used to look up identifirs in an AST file.
1626 class IdentifierLookupVisitor {
1627 StringRef Name;
1628 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001629 unsigned &NumIdentifierLookups;
1630 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001632
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001634 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1635 unsigned &NumIdentifierLookups,
1636 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001637 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001638 NumIdentifierLookups(NumIdentifierLookups),
1639 NumIdentifierLookupHits(NumIdentifierLookupHits),
1640 Found()
1641 {
1642 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001643
1644 static bool visit(ModuleFile &M, void *UserData) {
1645 IdentifierLookupVisitor *This
1646 = static_cast<IdentifierLookupVisitor *>(UserData);
1647
1648 // If we've already searched this module file, skip it now.
1649 if (M.Generation <= This->PriorGeneration)
1650 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001651
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 ASTIdentifierLookupTable *IdTable
1653 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1654 if (!IdTable)
1655 return false;
1656
1657 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1658 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001659 ++This->NumIdentifierLookups;
1660 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 if (Pos == IdTable->end())
1662 return false;
1663
1664 // Dereferencing the iterator has the effect of building the
1665 // IdentifierInfo node and populating it with the various
1666 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001667 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 This->Found = *Pos;
1669 return true;
1670 }
1671
1672 // \brief Retrieve the identifier info found within the module
1673 // files.
1674 IdentifierInfo *getIdentifierInfo() const { return Found; }
1675 };
1676}
1677
1678void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1679 // Note that we are loading an identifier.
1680 Deserializing AnIdentifier(this);
1681
1682 unsigned PriorGeneration = 0;
1683 if (getContext().getLangOpts().Modules)
1684 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001685
1686 // If there is a global index, look there first to determine which modules
1687 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001688 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001689 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001690 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001691 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1692 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001693 }
1694 }
1695
Douglas Gregor7211ac12013-01-25 23:32:03 +00001696 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001697 NumIdentifierLookups,
1698 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001699 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 markIdentifierUpToDate(&II);
1701}
1702
1703void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1704 if (!II)
1705 return;
1706
1707 II->setOutOfDate(false);
1708
1709 // Update the generation for this identifier.
1710 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001711 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001712}
1713
Richard Smith49f906a2014-03-01 00:08:04 +00001714struct ASTReader::ModuleMacroInfo {
1715 SubmoduleID SubModID;
1716 MacroInfo *MI;
1717 SubmoduleID *Overrides;
1718 // FIXME: Remove this.
1719 ModuleFile *F;
1720
1721 bool isDefine() const { return MI; }
1722
1723 SubmoduleID getSubmoduleID() const { return SubModID; }
1724
1725 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1726 if (!Overrides)
1727 return llvm::ArrayRef<SubmoduleID>();
1728 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1729 }
1730
1731 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1732 if (!MI)
Craig Toppera13603a2014-05-22 05:54:18 +00001733 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001734 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1735 }
1736};
1737
1738ASTReader::ModuleMacroInfo *
1739ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1740 ModuleMacroInfo Info;
1741
1742 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1743 if (ID & 1) {
1744 // Macro undefinition.
1745 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001746 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001747 } else {
1748 // Macro definition.
1749 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1750 assert(GMacID);
1751
1752 // If this macro has already been loaded, don't do so again.
1753 // FIXME: This is highly dubious. Multiple macro definitions can have the
1754 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1755 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001756 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001757
1758 Info.MI = getMacro(GMacID);
1759 Info.SubModID = Info.MI->getOwningModuleID();
1760 }
1761 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1762 Info.F = PMInfo.M;
1763
1764 return new (Context) ModuleMacroInfo(Info);
1765}
1766
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001767void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1768 const PendingMacroInfo &PMInfo) {
1769 assert(II);
1770
1771 if (PMInfo.M->Kind != MK_Module) {
1772 installPCHMacroDirectives(II, *PMInfo.M,
1773 PMInfo.PCHMacroData.MacroDirectivesOffset);
1774 return;
1775 }
Richard Smith49f906a2014-03-01 00:08:04 +00001776
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001777 // Module Macro.
1778
Richard Smith49f906a2014-03-01 00:08:04 +00001779 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1780 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001781 return;
1782
Richard Smith49f906a2014-03-01 00:08:04 +00001783 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1784 if (Owner && Owner->NameVisibility == Module::Hidden) {
1785 // Macros in the owning module are hidden. Just remember this macro to
1786 // install if we make this module visible.
1787 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1788 } else {
1789 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001790 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001791}
1792
1793void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1794 ModuleFile &M, uint64_t Offset) {
1795 assert(M.Kind != MK_Module);
1796
1797 BitstreamCursor &Cursor = M.MacroCursor;
1798 SavedStreamPosition SavedPosition(Cursor);
1799 Cursor.JumpToBit(Offset);
1800
1801 llvm::BitstreamEntry Entry =
1802 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1803 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1804 Error("malformed block record in AST file");
1805 return;
1806 }
1807
1808 RecordData Record;
1809 PreprocessorRecordTypes RecType =
1810 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1811 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1812 Error("malformed block record in AST file");
1813 return;
1814 }
1815
1816 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001817 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001818 unsigned Idx = 0, N = Record.size();
1819 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001820 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001821 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001822 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1823 switch (K) {
1824 case MacroDirective::MD_Define: {
1825 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1826 MacroInfo *MI = getMacro(GMacID);
1827 bool isImported = Record[Idx++];
1828 bool isAmbiguous = Record[Idx++];
1829 DefMacroDirective *DefMD =
1830 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1831 DefMD->setAmbiguous(isAmbiguous);
1832 MD = DefMD;
1833 break;
1834 }
1835 case MacroDirective::MD_Undefine:
1836 MD = PP.AllocateUndefMacroDirective(Loc);
1837 break;
1838 case MacroDirective::MD_Visibility: {
1839 bool isPublic = Record[Idx++];
1840 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1841 break;
1842 }
1843 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844
1845 if (!Latest)
1846 Latest = MD;
1847 if (Earliest)
1848 Earliest->setPrevious(MD);
1849 Earliest = MD;
1850 }
1851
1852 PP.setLoadedMacroDirective(II, Latest);
1853}
1854
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001855/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001856/// modules.
1857static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001858 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001859 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001860 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001861 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1862 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001863 SourceManager &SrcMgr = Reader.getSourceManager();
1864 bool PrevInSystem
1865 = PrevOwner? PrevOwner->IsSystem
1866 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1867 bool NewInSystem
1868 = NewOwner? NewOwner->IsSystem
1869 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1870 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001871 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001872 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001873}
1874
Richard Smith49f906a2014-03-01 00:08:04 +00001875void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1876 AmbiguousMacros &Ambig,
1877 llvm::ArrayRef<SubmoduleID> Overrides) {
1878 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1879 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001880
Richard Smith49f906a2014-03-01 00:08:04 +00001881 // If this macro is not yet visible, remove it from the hidden names list.
1882 Module *Owner = getSubmodule(OwnerID);
1883 HiddenNames &Hidden = HiddenNamesMap[Owner];
1884 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1885 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001886 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001887 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001888 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001889 }
1890
1891 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001892 Ambig.erase(
1893 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1894 return MD->getInfo()->getOwningModuleID() == OwnerID;
1895 }),
1896 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001897 }
1898}
1899
1900ASTReader::AmbiguousMacros *
1901ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1902 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001903 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001904 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001905 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001906
Craig Toppera13603a2014-05-22 05:54:18 +00001907 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1908 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001909 if (PrevDef && PrevDef->isAmbiguous()) {
1910 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1911 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1912 Ambig.push_back(PrevDef);
1913
1914 removeOverriddenMacros(II, Ambig, Overrides);
1915
1916 if (!Ambig.empty())
1917 return &Ambig;
1918
1919 AmbiguousMacroDefs.erase(II);
1920 } else {
1921 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001922 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001923 if (PrevDef)
1924 Ambig.push_back(PrevDef);
1925
1926 removeOverriddenMacros(II, Ambig, Overrides);
1927
1928 if (!Ambig.empty()) {
1929 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001930 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001931 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001932 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933 }
Richard Smith49f906a2014-03-01 00:08:04 +00001934
1935 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001936 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001937}
1938
1939void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1940 Module *Owner) {
1941 assert(II && Owner);
1942
1943 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1944 if (ImportLoc.isInvalid()) {
1945 // FIXME: If we made macros from this module visible but didn't provide a
1946 // source location for the import, we don't have a location for the macro.
1947 // Use the location at which the containing module file was first imported
1948 // for now.
1949 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001950 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001951 }
1952
Benjamin Kramer834652a2014-05-03 18:44:26 +00001953 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001954 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1955
Richard Smith49f906a2014-03-01 00:08:04 +00001956 // Create a synthetic macro definition corresponding to the import (or null
1957 // if this was an undefinition of the macro).
1958 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1959
1960 // If there's no ambiguity, just install the macro.
1961 if (!Prev) {
1962 if (MD)
1963 PP.appendMacroDirective(II, MD);
1964 else
1965 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1966 return;
1967 }
1968 assert(!Prev->empty());
1969
1970 if (!MD) {
1971 // We imported a #undef that didn't remove all prior definitions. The most
1972 // recent prior definition remains, and we install it in the place of the
1973 // imported directive.
1974 MacroInfo *NewMI = Prev->back()->getInfo();
1975 Prev->pop_back();
1976 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1977 }
1978
1979 // We're introducing a macro definition that creates or adds to an ambiguity.
1980 // We can resolve that ambiguity if this macro is token-for-token identical to
1981 // all of the existing definitions.
1982 MacroInfo *NewMI = MD->getInfo();
1983 assert(NewMI && "macro definition with no MacroInfo?");
1984 while (!Prev->empty()) {
1985 MacroInfo *PrevMI = Prev->back()->getInfo();
1986 assert(PrevMI && "macro definition with no MacroInfo?");
1987
1988 // Before marking the macros as ambiguous, check if this is a case where
1989 // both macros are in system headers. If so, we trust that the system
1990 // did not get it wrong. This also handles cases where Clang's own
1991 // headers have a different spelling of certain system macros:
1992 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1993 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1994 //
1995 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1996 // overrides the system limits.h's macros, so there's no conflict here.
1997 if (NewMI != PrevMI &&
1998 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1999 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2000 break;
2001
2002 // The previous definition is the same as this one (or both are defined in
2003 // system modules so we can assume they're equivalent); we don't need to
2004 // track it any more.
2005 Prev->pop_back();
2006 }
2007
2008 if (!Prev->empty())
2009 MD->setAmbiguous(true);
2010
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002011 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002012}
2013
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002014ASTReader::InputFileInfo
2015ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 // Go find this input file.
2017 BitstreamCursor &Cursor = F.InputFilesCursor;
2018 SavedStreamPosition SavedPosition(Cursor);
2019 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2020
2021 unsigned Code = Cursor.ReadCode();
2022 RecordData Record;
2023 StringRef Blob;
2024
2025 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2026 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2027 "invalid record type for input file");
2028 (void)Result;
2029
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002030 std::string Filename;
2031 off_t StoredSize;
2032 time_t StoredTime;
2033 bool Overridden;
2034
Ben Langmuir198c1682014-03-07 07:27:49 +00002035 assert(Record[0] == ID && "Bogus stored ID or offset");
2036 StoredSize = static_cast<off_t>(Record[1]);
2037 StoredTime = static_cast<time_t>(Record[2]);
2038 Overridden = static_cast<bool>(Record[3]);
2039 Filename = Blob;
2040 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002041
Hans Wennborg73945142014-03-14 17:45:06 +00002042 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2043 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002044}
2045
2046std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002047 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002048}
2049
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002050InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 // If this ID is bogus, just return an empty input file.
2052 if (ID == 0 || ID > F.InputFilesLoaded.size())
2053 return InputFile();
2054
2055 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002056 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 return F.InputFilesLoaded[ID-1];
2058
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002059 if (F.InputFilesLoaded[ID-1].isNotFound())
2060 return InputFile();
2061
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002063 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002064 SavedStreamPosition SavedPosition(Cursor);
2065 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2066
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002067 InputFileInfo FI = readInputFileInfo(F, ID);
2068 off_t StoredSize = FI.StoredSize;
2069 time_t StoredTime = FI.StoredTime;
2070 bool Overridden = FI.Overridden;
2071 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002072
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 const FileEntry *File
2074 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2075 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2076
2077 // If we didn't find the file, resolve it relative to the
2078 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002079 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002080 F.OriginalDir != CurrentDir) {
2081 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2082 F.OriginalDir,
2083 CurrentDir);
2084 if (!Resolved.empty())
2085 File = FileMgr.getFile(Resolved);
2086 }
2087
2088 // For an overridden file, create a virtual file with the stored
2089 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002090 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002091 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2092 }
2093
Craig Toppera13603a2014-05-22 05:54:18 +00002094 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002095 if (Complain) {
2096 std::string ErrorStr = "could not find file '";
2097 ErrorStr += Filename;
2098 ErrorStr += "' referenced by AST file";
2099 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002100 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002101 // Record that we didn't find the file.
2102 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2103 return InputFile();
2104 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002105
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 // Check if there was a request to override the contents of the file
2107 // that was part of the precompiled header. Overridding such a file
2108 // can lead to problems when lexing using the source locations from the
2109 // PCH.
2110 SourceManager &SM = getSourceManager();
2111 if (!Overridden && SM.isFileOverridden(File)) {
2112 if (Complain)
2113 Error(diag::err_fe_pch_file_overridden, Filename);
2114 // After emitting the diagnostic, recover by disabling the override so
2115 // that the original file will be used.
2116 SM.disableFileContentsOverride(File);
2117 // The FileEntry is a virtual file entry with the size of the contents
2118 // that would override the original contents. Set it to the original's
2119 // size/time.
2120 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2121 StoredSize, StoredTime);
2122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002123
Ben Langmuir198c1682014-03-07 07:27:49 +00002124 bool IsOutOfDate = false;
2125
2126 // For an overridden file, there is nothing to validate.
2127 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002128#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002129 // In our regression testing, the Windows file system seems to
2130 // have inconsistent modification times that sometimes
2131 // erroneously trigger this error-handling path.
2132 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002133#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 )) {
2135 if (Complain) {
2136 // Build a list of the PCH imports that got us here (in reverse).
2137 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2138 while (ImportStack.back()->ImportedBy.size() > 0)
2139 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002140
Ben Langmuir198c1682014-03-07 07:27:49 +00002141 // The top-level PCH is stale.
2142 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2143 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002144
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 // Print the import stack.
2146 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2147 Diag(diag::note_pch_required_by)
2148 << Filename << ImportStack[0]->FileName;
2149 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002150 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002152 }
2153
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 if (!Diags.isDiagnosticInFlight())
2155 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 }
2157
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 }
2160
Ben Langmuir198c1682014-03-07 07:27:49 +00002161 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2162
2163 // Note that we've loaded this input file.
2164 F.InputFilesLoaded[ID-1] = IF;
2165 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002166}
2167
2168const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2169 ModuleFile &M = ModuleMgr.getPrimaryModule();
2170 std::string Filename = filenameStrRef;
2171 MaybeAddSystemRootToFilename(M, Filename);
2172 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002173 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 M.OriginalDir != CurrentDir) {
2175 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2176 M.OriginalDir,
2177 CurrentDir);
2178 if (!resolved.empty())
2179 File = FileMgr.getFile(resolved);
2180 }
2181
2182 return File;
2183}
2184
2185/// \brief If we are loading a relocatable PCH file, and the filename is
2186/// not an absolute path, add the system root to the beginning of the file
2187/// name.
2188void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2189 std::string &Filename) {
2190 // If this is not a relocatable PCH file, there's nothing to do.
2191 if (!M.RelocatablePCH)
2192 return;
2193
2194 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2195 return;
2196
2197 if (isysroot.empty()) {
2198 // If no system root was given, default to '/'
2199 Filename.insert(Filename.begin(), '/');
2200 return;
2201 }
2202
2203 unsigned Length = isysroot.size();
2204 if (isysroot[Length - 1] != '/')
2205 Filename.insert(Filename.begin(), '/');
2206
2207 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2208}
2209
2210ASTReader::ASTReadResult
2211ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002212 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002213 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002215 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002216
2217 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2218 Error("malformed block record in AST file");
2219 return Failure;
2220 }
2221
2222 // Read all of the records and blocks in the control block.
2223 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002224 while (1) {
2225 llvm::BitstreamEntry Entry = Stream.advance();
2226
2227 switch (Entry.Kind) {
2228 case llvm::BitstreamEntry::Error:
2229 Error("malformed block record in AST file");
2230 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002231 case llvm::BitstreamEntry::EndBlock: {
2232 // Validate input files.
2233 const HeaderSearchOptions &HSOpts =
2234 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002235
2236 // All user input files reside at the index range [0, Record[1]), and
2237 // system input files reside at [Record[1], Record[0]).
2238 // Record is the one from INPUT_FILE_OFFSETS.
2239 unsigned NumInputs = Record[0];
2240 unsigned NumUserInputs = Record[1];
2241
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002242 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002243 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002244 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002246
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002247 // If we are reading a module, we will create a verification timestamp,
2248 // so we verify all input files. Otherwise, verify only user input
2249 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002250
2251 unsigned N = NumUserInputs;
2252 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002253 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2254 N = NumInputs;
2255
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002256 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002257 InputFile IF = getInputFile(F, I+1, Complain);
2258 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002260 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002262
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002263 if (Listener)
2264 Listener->visitModuleFile(F.FileName);
2265
Ben Langmuircb69b572014-03-07 06:40:32 +00002266 if (Listener && Listener->needsInputFileVisitation()) {
2267 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2268 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002269 for (unsigned I = 0; I < N; ++I) {
2270 bool IsSystem = I >= NumUserInputs;
2271 InputFileInfo FI = readInputFileInfo(F, I+1);
2272 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2273 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002274 }
2275
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002277 }
2278
Chris Lattnere7b154b2013-01-19 21:39:22 +00002279 case llvm::BitstreamEntry::SubBlock:
2280 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 case INPUT_FILES_BLOCK_ID:
2282 F.InputFilesCursor = Stream;
2283 if (Stream.SkipBlock() || // Skip with the main cursor
2284 // Read the abbreviations
2285 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2286 Error("malformed block record in AST file");
2287 return Failure;
2288 }
2289 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002290
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002292 if (Stream.SkipBlock()) {
2293 Error("malformed block record in AST file");
2294 return Failure;
2295 }
2296 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002298
2299 case llvm::BitstreamEntry::Record:
2300 // The interesting case.
2301 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 }
2303
2304 // Read and process a record.
2305 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002306 StringRef Blob;
2307 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 case METADATA: {
2309 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2310 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002311 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2312 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 return VersionMismatch;
2314 }
2315
2316 bool hasErrors = Record[5];
2317 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2318 Diag(diag::err_pch_with_compiler_errors);
2319 return HadErrors;
2320 }
2321
2322 F.RelocatablePCH = Record[4];
2323
2324 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002325 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2327 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002328 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 return VersionMismatch;
2330 }
2331 break;
2332 }
2333
2334 case IMPORTS: {
2335 // Load each of the imported PCH files.
2336 unsigned Idx = 0, N = Record.size();
2337 while (Idx < N) {
2338 // Read information about the AST file.
2339 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2340 // The import location will be the local one for now; we will adjust
2341 // all import locations of module imports after the global source
2342 // location info are setup.
2343 SourceLocation ImportLoc =
2344 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002345 off_t StoredSize = (off_t)Record[Idx++];
2346 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 unsigned Length = Record[Idx++];
2348 SmallString<128> ImportedFile(Record.begin() + Idx,
2349 Record.begin() + Idx + Length);
2350 Idx += Length;
2351
2352 // Load the AST file.
2353 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002354 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 ClientLoadCapabilities)) {
2356 case Failure: return Failure;
2357 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002358 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 case OutOfDate: return OutOfDate;
2360 case VersionMismatch: return VersionMismatch;
2361 case ConfigurationMismatch: return ConfigurationMismatch;
2362 case HadErrors: return HadErrors;
2363 case Success: break;
2364 }
2365 }
2366 break;
2367 }
2368
2369 case LANGUAGE_OPTIONS: {
2370 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2371 if (Listener && &F == *ModuleMgr.begin() &&
2372 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002373 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 return ConfigurationMismatch;
2375 break;
2376 }
2377
2378 case TARGET_OPTIONS: {
2379 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2380 if (Listener && &F == *ModuleMgr.begin() &&
2381 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002382 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 return ConfigurationMismatch;
2384 break;
2385 }
2386
2387 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002388 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 if (Listener && &F == *ModuleMgr.begin() &&
2390 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002391 !DisableValidation)
2392 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 break;
2394 }
2395
2396 case FILE_SYSTEM_OPTIONS: {
2397 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2398 if (Listener && &F == *ModuleMgr.begin() &&
2399 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002400 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 return ConfigurationMismatch;
2402 break;
2403 }
2404
2405 case HEADER_SEARCH_OPTIONS: {
2406 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2407 if (Listener && &F == *ModuleMgr.begin() &&
2408 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002409 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return ConfigurationMismatch;
2411 break;
2412 }
2413
2414 case PREPROCESSOR_OPTIONS: {
2415 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2416 if (Listener && &F == *ModuleMgr.begin() &&
2417 ParsePreprocessorOptions(Record, Complain, *Listener,
2418 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002419 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 return ConfigurationMismatch;
2421 break;
2422 }
2423
2424 case ORIGINAL_FILE:
2425 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002426 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2428 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2429 break;
2430
2431 case ORIGINAL_FILE_ID:
2432 F.OriginalSourceFileID = FileID::get(Record[0]);
2433 break;
2434
2435 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002436 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 break;
2438
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002439 case MODULE_NAME:
2440 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002441 if (Listener)
2442 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002443 break;
2444
2445 case MODULE_MAP_FILE:
2446 F.ModuleMapPath = Blob;
2447
2448 // Try to resolve ModuleName in the current header search context and
2449 // verify that it is found in the same module map file as we saved. If the
2450 // top-level AST file is a main file, skip this check because there is no
2451 // usable header search context.
2452 assert(!F.ModuleName.empty() &&
2453 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2454 if (F.Kind == MK_Module &&
2455 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2456 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2457 if (!M) {
2458 assert(ImportedBy && "top-level import should be verified");
2459 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2460 Diag(diag::err_imported_module_not_found)
2461 << F.ModuleName << ImportedBy->FileName;
2462 return Missing;
2463 }
2464
2465 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2466 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2467 assert(M->ModuleMap && "found module is missing module map file");
2468 assert(M->Name == F.ModuleName && "found module with different name");
2469 assert(ImportedBy && "top-level import should be verified");
2470 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2471 Diag(diag::err_imported_module_modmap_changed)
2472 << F.ModuleName << ImportedBy->FileName
2473 << M->ModuleMap->getName() << F.ModuleMapPath;
2474 return OutOfDate;
2475 }
2476 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002477
2478 if (Listener)
2479 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002480 break;
2481
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002483 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 F.InputFilesLoaded.resize(Record[0]);
2485 break;
2486 }
2487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002488}
2489
Ben Langmuir2c9af442014-04-10 17:57:43 +00002490ASTReader::ASTReadResult
2491ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002492 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493
2494 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2495 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002496 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 }
2498
2499 // Read all of the records and blocks for the AST file.
2500 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002501 while (1) {
2502 llvm::BitstreamEntry Entry = Stream.advance();
2503
2504 switch (Entry.Kind) {
2505 case llvm::BitstreamEntry::Error:
2506 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002507 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002508 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002509 // Outside of C++, we do not store a lookup map for the translation unit.
2510 // Instead, mark it as needing a lookup map to be built if this module
2511 // contains any declarations lexically within it (which it always does!).
2512 // This usually has no cost, since we very rarely need the lookup map for
2513 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002515 if (DC->hasExternalLexicalStorage() &&
2516 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002518
Ben Langmuir2c9af442014-04-10 17:57:43 +00002519 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002521 case llvm::BitstreamEntry::SubBlock:
2522 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 case DECLTYPES_BLOCK_ID:
2524 // We lazily load the decls block, but we want to set up the
2525 // DeclsCursor cursor to point into it. Clone our current bitcode
2526 // cursor to it, enter the block and read the abbrevs in that block.
2527 // With the main cursor, we just skip over it.
2528 F.DeclsCursor = Stream;
2529 if (Stream.SkipBlock() || // Skip with the main cursor.
2530 // Read the abbrevs.
2531 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2532 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002533 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 }
2535 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002536
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 case PREPROCESSOR_BLOCK_ID:
2538 F.MacroCursor = Stream;
2539 if (!PP.getExternalSource())
2540 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002541
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 if (Stream.SkipBlock() ||
2543 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2544 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002545 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 }
2547 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2548 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 case PREPROCESSOR_DETAIL_BLOCK_ID:
2551 F.PreprocessorDetailCursor = Stream;
2552 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002556 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002557 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2560
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 if (!PP.getPreprocessingRecord())
2562 PP.createPreprocessingRecord();
2563 if (!PP.getPreprocessingRecord()->getExternalSource())
2564 PP.getPreprocessingRecord()->SetExternalSource(*this);
2565 break;
2566
2567 case SOURCE_MANAGER_BLOCK_ID:
2568 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002569 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002571
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2574 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002576
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002578 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 if (Stream.SkipBlock() ||
2580 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2581 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002582 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 }
2584 CommentsCursors.push_back(std::make_pair(C, &F));
2585 break;
2586 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002589 if (Stream.SkipBlock()) {
2590 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592 }
2593 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 }
2595 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596
2597 case llvm::BitstreamEntry::Record:
2598 // The interesting case.
2599 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601
2602 // Read and process a record.
2603 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002604 StringRef Blob;
2605 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 default: // Default behavior: ignore.
2607 break;
2608
2609 case TYPE_OFFSET: {
2610 if (F.LocalNumTypes != 0) {
2611 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002612 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002614 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 F.LocalNumTypes = Record[0];
2616 unsigned LocalBaseTypeIndex = Record[1];
2617 F.BaseTypeIndex = getTotalNumTypes();
2618
2619 if (F.LocalNumTypes > 0) {
2620 // Introduce the global -> local mapping for types within this module.
2621 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2622
2623 // Introduce the local -> global mapping for types within this module.
2624 F.TypeRemap.insertOrReplace(
2625 std::make_pair(LocalBaseTypeIndex,
2626 F.BaseTypeIndex - LocalBaseTypeIndex));
2627
2628 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2629 }
2630 break;
2631 }
2632
2633 case DECL_OFFSET: {
2634 if (F.LocalNumDecls != 0) {
2635 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002638 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 F.LocalNumDecls = Record[0];
2640 unsigned LocalBaseDeclID = Record[1];
2641 F.BaseDeclID = getTotalNumDecls();
2642
2643 if (F.LocalNumDecls > 0) {
2644 // Introduce the global -> local mapping for declarations within this
2645 // module.
2646 GlobalDeclMap.insert(
2647 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2648
2649 // Introduce the local -> global mapping for declarations within this
2650 // module.
2651 F.DeclRemap.insertOrReplace(
2652 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2653
2654 // Introduce the global -> local mapping for declarations within this
2655 // module.
2656 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2657
2658 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2659 }
2660 break;
2661 }
2662
2663 case TU_UPDATE_LEXICAL: {
2664 DeclContext *TU = Context.getTranslationUnitDecl();
2665 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002668 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 TU->setHasExternalLexicalStorage(true);
2670 break;
2671 }
2672
2673 case UPDATE_VISIBLE: {
2674 unsigned Idx = 0;
2675 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2676 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002677 ASTDeclContextNameLookupTable::Create(
2678 (const unsigned char *)Blob.data() + Record[Idx++],
2679 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2680 (const unsigned char *)Blob.data(),
2681 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002682 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002683 auto *DC = cast<DeclContext>(D);
2684 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002685 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002686 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002687 delete LookupTable;
2688 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 } else
2690 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2691 break;
2692 }
2693
2694 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002695 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002697 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2698 (const unsigned char *)F.IdentifierTableData + Record[0],
2699 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2700 (const unsigned char *)F.IdentifierTableData,
2701 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002702
2703 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2704 }
2705 break;
2706
2707 case IDENTIFIER_OFFSET: {
2708 if (F.LocalNumIdentifiers != 0) {
2709 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002710 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002712 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 F.LocalNumIdentifiers = Record[0];
2714 unsigned LocalBaseIdentifierID = Record[1];
2715 F.BaseIdentifierID = getTotalNumIdentifiers();
2716
2717 if (F.LocalNumIdentifiers > 0) {
2718 // Introduce the global -> local mapping for identifiers within this
2719 // module.
2720 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2721 &F));
2722
2723 // Introduce the local -> global mapping for identifiers within this
2724 // module.
2725 F.IdentifierRemap.insertOrReplace(
2726 std::make_pair(LocalBaseIdentifierID,
2727 F.BaseIdentifierID - LocalBaseIdentifierID));
2728
2729 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2730 + F.LocalNumIdentifiers);
2731 }
2732 break;
2733 }
2734
Ben Langmuir332aafe2014-01-31 01:06:56 +00002735 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002737 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 break;
2739
2740 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002741 if (SpecialTypes.empty()) {
2742 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2743 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2744 break;
2745 }
2746
2747 if (SpecialTypes.size() != Record.size()) {
2748 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002749 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002750 }
2751
2752 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2753 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2754 if (!SpecialTypes[I])
2755 SpecialTypes[I] = ID;
2756 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2757 // merge step?
2758 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 break;
2760
2761 case STATISTICS:
2762 TotalNumStatements += Record[0];
2763 TotalNumMacros += Record[1];
2764 TotalLexicalDeclContexts += Record[2];
2765 TotalVisibleDeclContexts += Record[3];
2766 break;
2767
2768 case UNUSED_FILESCOPED_DECLS:
2769 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2770 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2771 break;
2772
2773 case DELEGATING_CTORS:
2774 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2775 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2776 break;
2777
2778 case WEAK_UNDECLARED_IDENTIFIERS:
2779 if (Record.size() % 4 != 0) {
2780 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002781 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 }
2783
2784 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2785 // files. This isn't the way to do it :)
2786 WeakUndeclaredIdentifiers.clear();
2787
2788 // Translate the weak, undeclared identifiers into global IDs.
2789 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2790 WeakUndeclaredIdentifiers.push_back(
2791 getGlobalIdentifierID(F, Record[I++]));
2792 WeakUndeclaredIdentifiers.push_back(
2793 getGlobalIdentifierID(F, Record[I++]));
2794 WeakUndeclaredIdentifiers.push_back(
2795 ReadSourceLocation(F, Record, I).getRawEncoding());
2796 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2797 }
2798 break;
2799
Richard Smith78165b52013-01-10 23:43:47 +00002800 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002802 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 break;
2804
2805 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002806 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 F.LocalNumSelectors = Record[0];
2808 unsigned LocalBaseSelectorID = Record[1];
2809 F.BaseSelectorID = getTotalNumSelectors();
2810
2811 if (F.LocalNumSelectors > 0) {
2812 // Introduce the global -> local mapping for selectors within this
2813 // module.
2814 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2815
2816 // Introduce the local -> global mapping for selectors within this
2817 // module.
2818 F.SelectorRemap.insertOrReplace(
2819 std::make_pair(LocalBaseSelectorID,
2820 F.BaseSelectorID - LocalBaseSelectorID));
2821
2822 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2823 }
2824 break;
2825 }
2826
2827 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002828 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 if (Record[0])
2830 F.SelectorLookupTable
2831 = ASTSelectorLookupTable::Create(
2832 F.SelectorLookupTableData + Record[0],
2833 F.SelectorLookupTableData,
2834 ASTSelectorLookupTrait(*this, F));
2835 TotalNumMethodPoolEntries += Record[1];
2836 break;
2837
2838 case REFERENCED_SELECTOR_POOL:
2839 if (!Record.empty()) {
2840 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2841 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2842 Record[Idx++]));
2843 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2844 getRawEncoding());
2845 }
2846 }
2847 break;
2848
2849 case PP_COUNTER_VALUE:
2850 if (!Record.empty() && Listener)
2851 Listener->ReadCounter(F, Record[0]);
2852 break;
2853
2854 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002855 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 F.NumFileSortedDecls = Record[0];
2857 break;
2858
2859 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002860 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 F.LocalNumSLocEntries = Record[0];
2862 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002863 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2865 SLocSpaceSize);
2866 // Make our entry in the range map. BaseID is negative and growing, so
2867 // we invert it. Because we invert it, though, we need the other end of
2868 // the range.
2869 unsigned RangeStart =
2870 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2871 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2872 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2873
2874 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2875 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2876 GlobalSLocOffsetMap.insert(
2877 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2878 - SLocSpaceSize,&F));
2879
2880 // Initialize the remapping table.
2881 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002882 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002884 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2886
2887 TotalNumSLocEntries += F.LocalNumSLocEntries;
2888 break;
2889 }
2890
2891 case MODULE_OFFSET_MAP: {
2892 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002893 const unsigned char *Data = (const unsigned char*)Blob.data();
2894 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002895
2896 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2897 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2898 F.SLocRemap.insert(std::make_pair(0U, 0));
2899 F.SLocRemap.insert(std::make_pair(2U, 1));
2900 }
2901
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 // Continuous range maps we may be updating in our module.
2903 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2904 ContinuousRangeMap<uint32_t, int, 2>::Builder
2905 IdentifierRemap(F.IdentifierRemap);
2906 ContinuousRangeMap<uint32_t, int, 2>::Builder
2907 MacroRemap(F.MacroRemap);
2908 ContinuousRangeMap<uint32_t, int, 2>::Builder
2909 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder
2911 SubmoduleRemap(F.SubmoduleRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder
2913 SelectorRemap(F.SelectorRemap);
2914 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2915 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2916
2917 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002918 using namespace llvm::support;
2919 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 StringRef Name = StringRef((const char*)Data, Len);
2921 Data += Len;
2922 ModuleFile *OM = ModuleMgr.lookup(Name);
2923 if (!OM) {
2924 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002925 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 }
2927
Justin Bogner57ba0b22014-03-28 22:03:24 +00002928 uint32_t SLocOffset =
2929 endian::readNext<uint32_t, little, unaligned>(Data);
2930 uint32_t IdentifierIDOffset =
2931 endian::readNext<uint32_t, little, unaligned>(Data);
2932 uint32_t MacroIDOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t PreprocessedEntityIDOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t SubmoduleIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t SelectorIDOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940 uint32_t DeclIDOffset =
2941 endian::readNext<uint32_t, little, unaligned>(Data);
2942 uint32_t TypeIndexOffset =
2943 endian::readNext<uint32_t, little, unaligned>(Data);
2944
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2946 SLocRemap.insert(std::make_pair(SLocOffset,
2947 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2948 IdentifierRemap.insert(
2949 std::make_pair(IdentifierIDOffset,
2950 OM->BaseIdentifierID - IdentifierIDOffset));
2951 MacroRemap.insert(std::make_pair(MacroIDOffset,
2952 OM->BaseMacroID - MacroIDOffset));
2953 PreprocessedEntityRemap.insert(
2954 std::make_pair(PreprocessedEntityIDOffset,
2955 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2956 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2957 OM->BaseSubmoduleID - SubmoduleIDOffset));
2958 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2959 OM->BaseSelectorID - SelectorIDOffset));
2960 DeclRemap.insert(std::make_pair(DeclIDOffset,
2961 OM->BaseDeclID - DeclIDOffset));
2962
2963 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2964 OM->BaseTypeIndex - TypeIndexOffset));
2965
2966 // Global -> local mappings.
2967 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2968 }
2969 break;
2970 }
2971
2972 case SOURCE_MANAGER_LINE_TABLE:
2973 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002974 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 break;
2976
2977 case SOURCE_LOCATION_PRELOADS: {
2978 // Need to transform from the local view (1-based IDs) to the global view,
2979 // which is based off F.SLocEntryBaseID.
2980 if (!F.PreloadSLocEntries.empty()) {
2981 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002982 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 }
2984
2985 F.PreloadSLocEntries.swap(Record);
2986 break;
2987 }
2988
2989 case EXT_VECTOR_DECLS:
2990 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2991 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2992 break;
2993
2994 case VTABLE_USES:
2995 if (Record.size() % 3 != 0) {
2996 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002997 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 }
2999
3000 // Later tables overwrite earlier ones.
3001 // FIXME: Modules will have some trouble with this. This is clearly not
3002 // the right way to do this.
3003 VTableUses.clear();
3004
3005 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3006 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3007 VTableUses.push_back(
3008 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3009 VTableUses.push_back(Record[Idx++]);
3010 }
3011 break;
3012
3013 case DYNAMIC_CLASSES:
3014 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3015 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3016 break;
3017
3018 case PENDING_IMPLICIT_INSTANTIATIONS:
3019 if (PendingInstantiations.size() % 2 != 0) {
3020 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 }
3023
3024 if (Record.size() % 2 != 0) {
3025 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 }
3028
3029 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3030 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3031 PendingInstantiations.push_back(
3032 ReadSourceLocation(F, Record, I).getRawEncoding());
3033 }
3034 break;
3035
3036 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003037 if (Record.size() != 2) {
3038 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003039 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3042 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3043 break;
3044
3045 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003046 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3047 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3048 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003049
3050 unsigned LocalBasePreprocessedEntityID = Record[0];
3051
3052 unsigned StartingID;
3053 if (!PP.getPreprocessingRecord())
3054 PP.createPreprocessingRecord();
3055 if (!PP.getPreprocessingRecord()->getExternalSource())
3056 PP.getPreprocessingRecord()->SetExternalSource(*this);
3057 StartingID
3058 = PP.getPreprocessingRecord()
3059 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3060 F.BasePreprocessedEntityID = StartingID;
3061
3062 if (F.NumPreprocessedEntities > 0) {
3063 // Introduce the global -> local mapping for preprocessed entities in
3064 // this module.
3065 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3066
3067 // Introduce the local -> global mapping for preprocessed entities in
3068 // this module.
3069 F.PreprocessedEntityRemap.insertOrReplace(
3070 std::make_pair(LocalBasePreprocessedEntityID,
3071 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3072 }
3073
3074 break;
3075 }
3076
3077 case DECL_UPDATE_OFFSETS: {
3078 if (Record.size() % 2 != 0) {
3079 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003080 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003082 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3083 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3084 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3085
3086 // If we've already loaded the decl, perform the updates when we finish
3087 // loading this block.
3088 if (Decl *D = GetExistingDecl(ID))
3089 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 break;
3092 }
3093
3094 case DECL_REPLACEMENTS: {
3095 if (Record.size() % 3 != 0) {
3096 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003097 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
3099 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3100 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3101 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3102 break;
3103 }
3104
3105 case OBJC_CATEGORIES_MAP: {
3106 if (F.LocalNumObjCCategoriesInMap != 0) {
3107 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003108 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 }
3110
3111 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003112 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 break;
3114 }
3115
3116 case OBJC_CATEGORIES:
3117 F.ObjCCategories.swap(Record);
3118 break;
3119
3120 case CXX_BASE_SPECIFIER_OFFSETS: {
3121 if (F.LocalNumCXXBaseSpecifiers != 0) {
3122 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 }
3125
3126 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003127 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3129 break;
3130 }
3131
3132 case DIAG_PRAGMA_MAPPINGS:
3133 if (F.PragmaDiagMappings.empty())
3134 F.PragmaDiagMappings.swap(Record);
3135 else
3136 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3137 Record.begin(), Record.end());
3138 break;
3139
3140 case CUDA_SPECIAL_DECL_REFS:
3141 // Later tables overwrite earlier ones.
3142 // FIXME: Modules will have trouble with this.
3143 CUDASpecialDeclRefs.clear();
3144 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3145 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3146 break;
3147
3148 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003149 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 if (Record[0]) {
3152 F.HeaderFileInfoTable
3153 = HeaderFileInfoLookupTable::Create(
3154 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3155 (const unsigned char *)F.HeaderFileInfoTableData,
3156 HeaderFileInfoTrait(*this, F,
3157 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003159
3160 PP.getHeaderSearchInfo().SetExternalSource(this);
3161 if (!PP.getHeaderSearchInfo().getExternalLookup())
3162 PP.getHeaderSearchInfo().SetExternalLookup(this);
3163 }
3164 break;
3165 }
3166
3167 case FP_PRAGMA_OPTIONS:
3168 // Later tables overwrite earlier ones.
3169 FPPragmaOptions.swap(Record);
3170 break;
3171
3172 case OPENCL_EXTENSIONS:
3173 // Later tables overwrite earlier ones.
3174 OpenCLExtensions.swap(Record);
3175 break;
3176
3177 case TENTATIVE_DEFINITIONS:
3178 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3179 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3180 break;
3181
3182 case KNOWN_NAMESPACES:
3183 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3184 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3185 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003186
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003187 case UNDEFINED_BUT_USED:
3188 if (UndefinedButUsed.size() % 2 != 0) {
3189 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003190 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003191 }
3192
3193 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003194 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003195 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003196 }
3197 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003198 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3199 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003200 ReadSourceLocation(F, Record, I).getRawEncoding());
3201 }
3202 break;
3203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 case IMPORTED_MODULES: {
3205 if (F.Kind != MK_Module) {
3206 // If we aren't loading a module (which has its own exports), make
3207 // all of the imported modules visible.
3208 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003209 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3210 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3211 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3212 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003213 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 }
3215 }
3216 break;
3217 }
3218
3219 case LOCAL_REDECLARATIONS: {
3220 F.RedeclarationChains.swap(Record);
3221 break;
3222 }
3223
3224 case LOCAL_REDECLARATIONS_MAP: {
3225 if (F.LocalNumRedeclarationsInMap != 0) {
3226 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003227 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 }
3229
3230 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003231 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 break;
3233 }
3234
3235 case MERGED_DECLARATIONS: {
3236 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3237 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3238 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3239 for (unsigned N = Record[Idx++]; N > 0; --N)
3240 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3241 }
3242 break;
3243 }
3244
3245 case MACRO_OFFSET: {
3246 if (F.LocalNumMacros != 0) {
3247 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003248 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003250 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 F.LocalNumMacros = Record[0];
3252 unsigned LocalBaseMacroID = Record[1];
3253 F.BaseMacroID = getTotalNumMacros();
3254
3255 if (F.LocalNumMacros > 0) {
3256 // Introduce the global -> local mapping for macros within this module.
3257 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3258
3259 // Introduce the local -> global mapping for macros within this module.
3260 F.MacroRemap.insertOrReplace(
3261 std::make_pair(LocalBaseMacroID,
3262 F.BaseMacroID - LocalBaseMacroID));
3263
3264 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3265 }
3266 break;
3267 }
3268
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003269 case MACRO_TABLE: {
3270 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 break;
3272 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003273
3274 case LATE_PARSED_TEMPLATE: {
3275 LateParsedTemplates.append(Record.begin(), Record.end());
3276 break;
3277 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 }
3279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003280}
3281
Douglas Gregorc1489562013-02-12 23:36:21 +00003282/// \brief Move the given method to the back of the global list of methods.
3283static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3284 // Find the entry for this selector in the method pool.
3285 Sema::GlobalMethodPool::iterator Known
3286 = S.MethodPool.find(Method->getSelector());
3287 if (Known == S.MethodPool.end())
3288 return;
3289
3290 // Retrieve the appropriate method list.
3291 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3292 : Known->second.second;
3293 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003294 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003295 if (!Found) {
3296 if (List->Method == Method) {
3297 Found = true;
3298 } else {
3299 // Keep searching.
3300 continue;
3301 }
3302 }
3303
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003304 if (List->getNext())
3305 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003306 else
3307 List->Method = Method;
3308 }
3309}
3310
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003311void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003312 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3313 Decl *D = Names.HiddenDecls[I];
3314 bool wasHidden = D->Hidden;
3315 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003316
Richard Smith49f906a2014-03-01 00:08:04 +00003317 if (wasHidden && SemaObj) {
3318 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3319 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003320 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 }
3322 }
Richard Smith49f906a2014-03-01 00:08:04 +00003323
3324 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3325 E = Names.HiddenMacros.end();
3326 I != E; ++I)
3327 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003328}
3329
Richard Smith49f906a2014-03-01 00:08:04 +00003330void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003331 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003332 SourceLocation ImportLoc,
3333 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003335 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003336 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003338 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003339
3340 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003341 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 // there is nothing more to do.
3343 continue;
3344 }
Richard Smith49f906a2014-03-01 00:08:04 +00003345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 if (!Mod->isAvailable()) {
3347 // Modules that aren't available cannot be made visible.
3348 continue;
3349 }
3350
3351 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003352 if (NameVisibility >= Module::MacrosVisible &&
3353 Mod->NameVisibility < Module::MacrosVisible)
3354 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003356
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 // If we've already deserialized any names from this module,
3358 // mark them as visible.
3359 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3360 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003361 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 HiddenNamesMap.erase(Hidden);
3363 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003366 SmallVector<Module *, 16> Exports;
3367 Mod->getExportedModules(Exports);
3368 for (SmallVectorImpl<Module *>::iterator
3369 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3370 Module *Exported = *I;
3371 if (Visited.insert(Exported))
3372 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003374
3375 // Detect any conflicts.
3376 if (Complain) {
3377 assert(ImportLoc.isValid() && "Missing import location");
3378 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3379 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3380 Diag(ImportLoc, diag::warn_module_conflict)
3381 << Mod->getFullModuleName()
3382 << Mod->Conflicts[I].Other->getFullModuleName()
3383 << Mod->Conflicts[I].Message;
3384 // FIXME: Need note where the other module was imported.
3385 }
3386 }
3387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 }
3389}
3390
Douglas Gregore060e572013-01-25 01:03:03 +00003391bool ASTReader::loadGlobalIndex() {
3392 if (GlobalIndex)
3393 return false;
3394
3395 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3396 !Context.getLangOpts().Modules)
3397 return true;
3398
3399 // Try to load the global index.
3400 TriedLoadingGlobalIndex = true;
3401 StringRef ModuleCachePath
3402 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3403 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003404 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003405 if (!Result.first)
3406 return true;
3407
3408 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003409 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003410 return false;
3411}
3412
3413bool ASTReader::isGlobalIndexUnavailable() const {
3414 return Context.getLangOpts().Modules && UseGlobalIndex &&
3415 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3416}
3417
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003418static void updateModuleTimestamp(ModuleFile &MF) {
3419 // Overwrite the timestamp file contents so that file's mtime changes.
3420 std::string TimestampFilename = MF.getTimestampFilename();
3421 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003422 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003423 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003424 if (!ErrorInfo.empty())
3425 return;
3426 OS << "Timestamp file\n";
3427}
3428
Guy Benyei11169dd2012-12-18 14:30:41 +00003429ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3430 ModuleKind Type,
3431 SourceLocation ImportLoc,
3432 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003433 llvm::SaveAndRestore<SourceLocation>
3434 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3435
Richard Smithd1c46742014-04-30 02:24:17 +00003436 // Defer any pending actions until we get to the end of reading the AST file.
3437 Deserializing AnASTFile(this);
3438
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003440 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003441
3442 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003443 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003445 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003446 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 ClientLoadCapabilities)) {
3448 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003449 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003450 case OutOfDate:
3451 case VersionMismatch:
3452 case ConfigurationMismatch:
3453 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003454 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3455 Context.getLangOpts().Modules
3456 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003457 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003458
3459 // If we find that any modules are unusable, the global index is going
3460 // to be out-of-date. Just remove it.
3461 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003462 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 return ReadResult;
3464
3465 case Success:
3466 break;
3467 }
3468
3469 // Here comes stuff that we only do once the entire chain is loaded.
3470
3471 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003472 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3473 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 M != MEnd; ++M) {
3475 ModuleFile &F = *M->Mod;
3476
3477 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003478 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3479 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003480
3481 // Once read, set the ModuleFile bit base offset and update the size in
3482 // bits of all files we've seen.
3483 F.GlobalBitOffset = TotalModulesSizeInBits;
3484 TotalModulesSizeInBits += F.SizeInBits;
3485 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3486
3487 // Preload SLocEntries.
3488 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3489 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3490 // Load it through the SourceManager and don't call ReadSLocEntry()
3491 // directly because the entry may have already been loaded in which case
3492 // calling ReadSLocEntry() directly would trigger an assertion in
3493 // SourceManager.
3494 SourceMgr.getLoadedSLocEntryByID(Index);
3495 }
3496 }
3497
Douglas Gregor603cd862013-03-22 18:50:14 +00003498 // Setup the import locations and notify the module manager that we've
3499 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003500 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3501 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 M != MEnd; ++M) {
3503 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003504
3505 ModuleMgr.moduleFileAccepted(&F);
3506
3507 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003508 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 if (!M->ImportedBy)
3510 F.ImportLoc = M->ImportLoc;
3511 else
3512 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3513 M->ImportLoc.getRawEncoding());
3514 }
3515
3516 // Mark all of the identifiers in the identifier table as being out of date,
3517 // so that various accessors know to check the loaded modules when the
3518 // identifier is used.
3519 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3520 IdEnd = PP.getIdentifierTable().end();
3521 Id != IdEnd; ++Id)
3522 Id->second->setOutOfDate(true);
3523
3524 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003525 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3526 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3528 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003529
3530 switch (Unresolved.Kind) {
3531 case UnresolvedModuleRef::Conflict:
3532 if (ResolvedMod) {
3533 Module::Conflict Conflict;
3534 Conflict.Other = ResolvedMod;
3535 Conflict.Message = Unresolved.String.str();
3536 Unresolved.Mod->Conflicts.push_back(Conflict);
3537 }
3538 continue;
3539
3540 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 if (ResolvedMod)
3542 Unresolved.Mod->Imports.push_back(ResolvedMod);
3543 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003544
Douglas Gregorfb912652013-03-20 21:10:35 +00003545 case UnresolvedModuleRef::Export:
3546 if (ResolvedMod || Unresolved.IsWildcard)
3547 Unresolved.Mod->Exports.push_back(
3548 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3549 continue;
3550 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003552 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003553
3554 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3555 // Might be unnecessary as use declarations are only used to build the
3556 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003557
3558 InitializeContext();
3559
Richard Smith3d8e97e2013-10-18 06:54:39 +00003560 if (SemaObj)
3561 UpdateSema();
3562
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 if (DeserializationListener)
3564 DeserializationListener->ReaderInitialized(this);
3565
3566 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3567 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3568 PrimaryModule.OriginalSourceFileID
3569 = FileID::get(PrimaryModule.SLocEntryBaseID
3570 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3571
3572 // If this AST file is a precompiled preamble, then set the
3573 // preamble file ID of the source manager to the file source file
3574 // from which the preamble was built.
3575 if (Type == MK_Preamble) {
3576 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3577 } else if (Type == MK_MainFile) {
3578 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3579 }
3580 }
3581
3582 // For any Objective-C class definitions we have already loaded, make sure
3583 // that we load any additional categories.
3584 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3585 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3586 ObjCClassesLoaded[I],
3587 PreviousGeneration);
3588 }
Douglas Gregore060e572013-01-25 01:03:03 +00003589
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003590 if (PP.getHeaderSearchInfo()
3591 .getHeaderSearchOpts()
3592 .ModulesValidateOncePerBuildSession) {
3593 // Now we are certain that the module and all modules it depends on are
3594 // up to date. Create or update timestamp files for modules that are
3595 // located in the module cache (not for PCH files that could be anywhere
3596 // in the filesystem).
3597 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3598 ImportedModule &M = Loaded[I];
3599 if (M.Mod->Kind == MK_Module) {
3600 updateModuleTimestamp(*M.Mod);
3601 }
3602 }
3603 }
3604
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 return Success;
3606}
3607
3608ASTReader::ASTReadResult
3609ASTReader::ReadASTCore(StringRef FileName,
3610 ModuleKind Type,
3611 SourceLocation ImportLoc,
3612 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003613 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003614 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 unsigned ClientLoadCapabilities) {
3616 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003618 ModuleManager::AddModuleResult AddResult
3619 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003620 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003621 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003622
Douglas Gregor7029ce12013-03-19 00:28:20 +00003623 switch (AddResult) {
3624 case ModuleManager::AlreadyLoaded:
3625 return Success;
3626
3627 case ModuleManager::NewlyLoaded:
3628 // Load module file below.
3629 break;
3630
3631 case ModuleManager::Missing:
3632 // The module file was missing; if the client handle handle, that, return
3633 // it.
3634 if (ClientLoadCapabilities & ARR_Missing)
3635 return Missing;
3636
3637 // Otherwise, return an error.
3638 {
3639 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3640 + ErrorStr;
3641 Error(Msg);
3642 }
3643 return Failure;
3644
3645 case ModuleManager::OutOfDate:
3646 // We couldn't load the module file because it is out-of-date. If the
3647 // client can handle out-of-date, return it.
3648 if (ClientLoadCapabilities & ARR_OutOfDate)
3649 return OutOfDate;
3650
3651 // Otherwise, return an error.
3652 {
3653 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3654 + ErrorStr;
3655 Error(Msg);
3656 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 return Failure;
3658 }
3659
Douglas Gregor7029ce12013-03-19 00:28:20 +00003660 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003661
3662 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3663 // module?
3664 if (FileName != "-") {
3665 CurrentDir = llvm::sys::path::parent_path(FileName);
3666 if (CurrentDir.empty()) CurrentDir = ".";
3667 }
3668
3669 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003670 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 Stream.init(F.StreamFile);
3672 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3673
3674 // Sniff for the signature.
3675 if (Stream.Read(8) != 'C' ||
3676 Stream.Read(8) != 'P' ||
3677 Stream.Read(8) != 'C' ||
3678 Stream.Read(8) != 'H') {
3679 Diag(diag::err_not_a_pch_file) << FileName;
3680 return Failure;
3681 }
3682
3683 // This is used for compatibility with older PCH formats.
3684 bool HaveReadControlBlock = false;
3685
Chris Lattnerefa77172013-01-20 00:00:22 +00003686 while (1) {
3687 llvm::BitstreamEntry Entry = Stream.advance();
3688
3689 switch (Entry.Kind) {
3690 case llvm::BitstreamEntry::Error:
3691 case llvm::BitstreamEntry::EndBlock:
3692 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 Error("invalid record at top-level of AST file");
3694 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003695
3696 case llvm::BitstreamEntry::SubBlock:
3697 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 }
3699
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003701 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003702 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3703 if (Stream.ReadBlockInfoBlock()) {
3704 Error("malformed BlockInfoBlock in AST file");
3705 return Failure;
3706 }
3707 break;
3708 case CONTROL_BLOCK_ID:
3709 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003710 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 case Success:
3712 break;
3713
3714 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003715 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 case OutOfDate: return OutOfDate;
3717 case VersionMismatch: return VersionMismatch;
3718 case ConfigurationMismatch: return ConfigurationMismatch;
3719 case HadErrors: return HadErrors;
3720 }
3721 break;
3722 case AST_BLOCK_ID:
3723 if (!HaveReadControlBlock) {
3724 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003725 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 return VersionMismatch;
3727 }
3728
3729 // Record that we've loaded this module.
3730 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3731 return Success;
3732
3733 default:
3734 if (Stream.SkipBlock()) {
3735 Error("malformed block record in AST file");
3736 return Failure;
3737 }
3738 break;
3739 }
3740 }
3741
3742 return Success;
3743}
3744
3745void ASTReader::InitializeContext() {
3746 // If there's a listener, notify them that we "read" the translation unit.
3747 if (DeserializationListener)
3748 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3749 Context.getTranslationUnitDecl());
3750
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 // FIXME: Find a better way to deal with collisions between these
3752 // built-in types. Right now, we just ignore the problem.
3753
3754 // Load the special types.
3755 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3756 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3757 if (!Context.CFConstantStringTypeDecl)
3758 Context.setCFConstantStringType(GetType(String));
3759 }
3760
3761 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3762 QualType FileType = GetType(File);
3763 if (FileType.isNull()) {
3764 Error("FILE type is NULL");
3765 return;
3766 }
3767
3768 if (!Context.FILEDecl) {
3769 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3770 Context.setFILEDecl(Typedef->getDecl());
3771 else {
3772 const TagType *Tag = FileType->getAs<TagType>();
3773 if (!Tag) {
3774 Error("Invalid FILE type in AST file");
3775 return;
3776 }
3777 Context.setFILEDecl(Tag->getDecl());
3778 }
3779 }
3780 }
3781
3782 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3783 QualType Jmp_bufType = GetType(Jmp_buf);
3784 if (Jmp_bufType.isNull()) {
3785 Error("jmp_buf type is NULL");
3786 return;
3787 }
3788
3789 if (!Context.jmp_bufDecl) {
3790 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3791 Context.setjmp_bufDecl(Typedef->getDecl());
3792 else {
3793 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3794 if (!Tag) {
3795 Error("Invalid jmp_buf type in AST file");
3796 return;
3797 }
3798 Context.setjmp_bufDecl(Tag->getDecl());
3799 }
3800 }
3801 }
3802
3803 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3804 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3805 if (Sigjmp_bufType.isNull()) {
3806 Error("sigjmp_buf type is NULL");
3807 return;
3808 }
3809
3810 if (!Context.sigjmp_bufDecl) {
3811 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3812 Context.setsigjmp_bufDecl(Typedef->getDecl());
3813 else {
3814 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3815 assert(Tag && "Invalid sigjmp_buf type in AST file");
3816 Context.setsigjmp_bufDecl(Tag->getDecl());
3817 }
3818 }
3819 }
3820
3821 if (unsigned ObjCIdRedef
3822 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3823 if (Context.ObjCIdRedefinitionType.isNull())
3824 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3825 }
3826
3827 if (unsigned ObjCClassRedef
3828 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3829 if (Context.ObjCClassRedefinitionType.isNull())
3830 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3831 }
3832
3833 if (unsigned ObjCSelRedef
3834 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3835 if (Context.ObjCSelRedefinitionType.isNull())
3836 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3837 }
3838
3839 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3840 QualType Ucontext_tType = GetType(Ucontext_t);
3841 if (Ucontext_tType.isNull()) {
3842 Error("ucontext_t type is NULL");
3843 return;
3844 }
3845
3846 if (!Context.ucontext_tDecl) {
3847 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3848 Context.setucontext_tDecl(Typedef->getDecl());
3849 else {
3850 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3851 assert(Tag && "Invalid ucontext_t type in AST file");
3852 Context.setucontext_tDecl(Tag->getDecl());
3853 }
3854 }
3855 }
3856 }
3857
3858 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3859
3860 // If there were any CUDA special declarations, deserialize them.
3861 if (!CUDASpecialDeclRefs.empty()) {
3862 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3863 Context.setcudaConfigureCallDecl(
3864 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3865 }
Richard Smith56be7542014-03-21 00:33:59 +00003866
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003868 // FIXME: This does not make macro-only imports visible again. It also doesn't
3869 // make #includes mapped to module imports visible.
3870 for (auto &Import : ImportedModules) {
3871 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003872 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003873 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003874 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 }
3876 ImportedModules.clear();
3877}
3878
3879void ASTReader::finalizeForWriting() {
3880 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3881 HiddenEnd = HiddenNamesMap.end();
3882 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003883 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 }
3885 HiddenNamesMap.clear();
3886}
3887
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003888/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3889/// cursor into the start of the given block ID, returning false on success and
3890/// true on failure.
3891static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003892 while (1) {
3893 llvm::BitstreamEntry Entry = Cursor.advance();
3894 switch (Entry.Kind) {
3895 case llvm::BitstreamEntry::Error:
3896 case llvm::BitstreamEntry::EndBlock:
3897 return true;
3898
3899 case llvm::BitstreamEntry::Record:
3900 // Ignore top-level records.
3901 Cursor.skipRecord(Entry.ID);
3902 break;
3903
3904 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003905 if (Entry.ID == BlockID) {
3906 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003907 return true;
3908 // Found it!
3909 return false;
3910 }
3911
3912 if (Cursor.SkipBlock())
3913 return true;
3914 }
3915 }
3916}
3917
Guy Benyei11169dd2012-12-18 14:30:41 +00003918/// \brief Retrieve the name of the original source file name
3919/// directly from the AST file, without actually loading the AST
3920/// file.
3921std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3922 FileManager &FileMgr,
3923 DiagnosticsEngine &Diags) {
3924 // Open the AST file.
3925 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003926 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3928 if (!Buffer) {
3929 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3930 return std::string();
3931 }
3932
3933 // Initialize the stream
3934 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003935 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3937 (const unsigned char *)Buffer->getBufferEnd());
3938 Stream.init(StreamFile);
3939
3940 // Sniff for the signature.
3941 if (Stream.Read(8) != 'C' ||
3942 Stream.Read(8) != 'P' ||
3943 Stream.Read(8) != 'C' ||
3944 Stream.Read(8) != 'H') {
3945 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3946 return std::string();
3947 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003948
Chris Lattnere7b154b2013-01-19 21:39:22 +00003949 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003950 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003951 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3952 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003954
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003955 // Scan for ORIGINAL_FILE inside the control block.
3956 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003957 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003958 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003959 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3960 return std::string();
3961
3962 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3963 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3964 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003966
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003968 StringRef Blob;
3969 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3970 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003972}
3973
3974namespace {
3975 class SimplePCHValidator : public ASTReaderListener {
3976 const LangOptions &ExistingLangOpts;
3977 const TargetOptions &ExistingTargetOpts;
3978 const PreprocessorOptions &ExistingPPOpts;
3979 FileManager &FileMgr;
3980
3981 public:
3982 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3983 const TargetOptions &ExistingTargetOpts,
3984 const PreprocessorOptions &ExistingPPOpts,
3985 FileManager &FileMgr)
3986 : ExistingLangOpts(ExistingLangOpts),
3987 ExistingTargetOpts(ExistingTargetOpts),
3988 ExistingPPOpts(ExistingPPOpts),
3989 FileMgr(FileMgr)
3990 {
3991 }
3992
Craig Topper3e89dfe2014-03-13 02:13:41 +00003993 bool ReadLanguageOptions(const LangOptions &LangOpts,
3994 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003995 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003997 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3998 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003999 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004001 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4002 bool Complain,
4003 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004004 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004005 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 }
4007 };
4008}
4009
4010bool ASTReader::readASTFileControlBlock(StringRef Filename,
4011 FileManager &FileMgr,
4012 ASTReaderListener &Listener) {
4013 // Open the AST file.
4014 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004015 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4017 if (!Buffer) {
4018 return true;
4019 }
4020
4021 // Initialize the stream
4022 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004023 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4025 (const unsigned char *)Buffer->getBufferEnd());
4026 Stream.init(StreamFile);
4027
4028 // Sniff for the signature.
4029 if (Stream.Read(8) != 'C' ||
4030 Stream.Read(8) != 'P' ||
4031 Stream.Read(8) != 'C' ||
4032 Stream.Read(8) != 'H') {
4033 return true;
4034 }
4035
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004037 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004038 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004039
4040 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004041 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004042 BitstreamCursor InputFilesCursor;
4043 if (NeedsInputFiles) {
4044 InputFilesCursor = Stream;
4045 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4046 return true;
4047
4048 // Read the abbreviations
4049 while (true) {
4050 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4051 unsigned Code = InputFilesCursor.ReadCode();
4052
4053 // We expect all abbrevs to be at the start of the block.
4054 if (Code != llvm::bitc::DEFINE_ABBREV) {
4055 InputFilesCursor.JumpToBit(Offset);
4056 break;
4057 }
4058 InputFilesCursor.ReadAbbrevRecord();
4059 }
4060 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004061
4062 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004064 while (1) {
4065 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4066 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4067 return false;
4068
4069 if (Entry.Kind != llvm::BitstreamEntry::Record)
4070 return true;
4071
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004073 StringRef Blob;
4074 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004075 switch ((ControlRecordTypes)RecCode) {
4076 case METADATA: {
4077 if (Record[0] != VERSION_MAJOR)
4078 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004080 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004082
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004083 break;
4084 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004085 case MODULE_NAME:
4086 Listener.ReadModuleName(Blob);
4087 break;
4088 case MODULE_MAP_FILE:
4089 Listener.ReadModuleMapFile(Blob);
4090 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 case LANGUAGE_OPTIONS:
4092 if (ParseLanguageOptions(Record, false, Listener))
4093 return true;
4094 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004095
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 case TARGET_OPTIONS:
4097 if (ParseTargetOptions(Record, false, Listener))
4098 return true;
4099 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004101 case DIAGNOSTIC_OPTIONS:
4102 if (ParseDiagnosticOptions(Record, false, Listener))
4103 return true;
4104 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004105
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004106 case FILE_SYSTEM_OPTIONS:
4107 if (ParseFileSystemOptions(Record, false, Listener))
4108 return true;
4109 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004110
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004111 case HEADER_SEARCH_OPTIONS:
4112 if (ParseHeaderSearchOptions(Record, false, Listener))
4113 return true;
4114 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004116 case PREPROCESSOR_OPTIONS: {
4117 std::string IgnoredSuggestedPredefines;
4118 if (ParsePreprocessorOptions(Record, false, Listener,
4119 IgnoredSuggestedPredefines))
4120 return true;
4121 break;
4122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004123
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004124 case INPUT_FILE_OFFSETS: {
4125 if (!NeedsInputFiles)
4126 break;
4127
4128 unsigned NumInputFiles = Record[0];
4129 unsigned NumUserFiles = Record[1];
4130 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4131 for (unsigned I = 0; I != NumInputFiles; ++I) {
4132 // Go find this input file.
4133 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004134
4135 if (isSystemFile && !NeedsSystemInputFiles)
4136 break; // the rest are system input files
4137
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004138 BitstreamCursor &Cursor = InputFilesCursor;
4139 SavedStreamPosition SavedPosition(Cursor);
4140 Cursor.JumpToBit(InputFileOffs[I]);
4141
4142 unsigned Code = Cursor.ReadCode();
4143 RecordData Record;
4144 StringRef Blob;
4145 bool shouldContinue = false;
4146 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4147 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004148 bool Overridden = static_cast<bool>(Record[3]);
4149 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004150 break;
4151 }
4152 if (!shouldContinue)
4153 break;
4154 }
4155 break;
4156 }
4157
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004158 default:
4159 // No other validation to perform.
4160 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 }
4162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004163}
4164
4165
4166bool ASTReader::isAcceptableASTFile(StringRef Filename,
4167 FileManager &FileMgr,
4168 const LangOptions &LangOpts,
4169 const TargetOptions &TargetOpts,
4170 const PreprocessorOptions &PPOpts) {
4171 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4172 return !readASTFileControlBlock(Filename, FileMgr, validator);
4173}
4174
Ben Langmuir2c9af442014-04-10 17:57:43 +00004175ASTReader::ASTReadResult
4176ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 // Enter the submodule block.
4178 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4179 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004180 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004181 }
4182
4183 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4184 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004185 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 RecordData Record;
4187 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004188 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4189
4190 switch (Entry.Kind) {
4191 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4192 case llvm::BitstreamEntry::Error:
4193 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004194 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004195 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004196 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004197 case llvm::BitstreamEntry::Record:
4198 // The interesting case.
4199 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004203 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004205 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 default: // Default behavior: ignore.
4207 break;
4208
4209 case SUBMODULE_DEFINITION: {
4210 if (First) {
4211 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004212 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
4214
Douglas Gregor8d932422013-03-20 03:59:18 +00004215 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004217 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 }
4219
Chris Lattner0e6c9402013-01-20 02:38:54 +00004220 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004221 unsigned Idx = 0;
4222 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4223 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4224 bool IsFramework = Record[Idx++];
4225 bool IsExplicit = Record[Idx++];
4226 bool IsSystem = Record[Idx++];
4227 bool IsExternC = Record[Idx++];
4228 bool InferSubmodules = Record[Idx++];
4229 bool InferExplicitSubmodules = Record[Idx++];
4230 bool InferExportWildcard = Record[Idx++];
4231 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004232
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004233 Module *ParentModule = nullptr;
4234 const FileEntry *ModuleMap = nullptr;
4235 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004237 ModuleMap = ParentModule->ModuleMap;
4238 }
4239
4240 if (!F.ModuleMapPath.empty())
4241 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4242
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 // Retrieve this (sub)module from the module map, creating it if
4244 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004245 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 IsFramework,
4247 IsExplicit).first;
4248 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4249 if (GlobalIndex >= SubmodulesLoaded.size() ||
4250 SubmodulesLoaded[GlobalIndex]) {
4251 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004252 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004254
Douglas Gregor7029ce12013-03-19 00:28:20 +00004255 if (!ParentModule) {
4256 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4257 if (CurFile != F.File) {
4258 if (!Diags.isDiagnosticInFlight()) {
4259 Diag(diag::err_module_file_conflict)
4260 << CurrentModule->getTopLevelModuleName()
4261 << CurFile->getName()
4262 << F.File->getName();
4263 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004264 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004265 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004266 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004267
4268 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004269 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004270
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 CurrentModule->IsFromModuleFile = true;
4272 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004273 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 CurrentModule->InferSubmodules = InferSubmodules;
4275 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4276 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004277 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 if (DeserializationListener)
4279 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4280
4281 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004282
Douglas Gregorfb912652013-03-20 21:10:35 +00004283 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004284 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004285 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004286 CurrentModule->UnresolvedConflicts.clear();
4287 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 break;
4289 }
4290
4291 case SUBMODULE_UMBRELLA_HEADER: {
4292 if (First) {
4293 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004294 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 }
4296
4297 if (!CurrentModule)
4298 break;
4299
Chris Lattner0e6c9402013-01-20 02:38:54 +00004300 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 if (!CurrentModule->getUmbrellaHeader())
4302 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4303 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004304 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4305 Error("mismatched umbrella headers in submodule");
4306 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308 }
4309 break;
4310 }
4311
4312 case SUBMODULE_HEADER: {
4313 if (First) {
4314 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004315 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 }
4317
4318 if (!CurrentModule)
4319 break;
4320
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004321 // We lazily associate headers with their modules via the HeaderInfoTable.
4322 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4323 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 break;
4325 }
4326
4327 case SUBMODULE_EXCLUDED_HEADER: {
4328 if (First) {
4329 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004330 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 }
4332
4333 if (!CurrentModule)
4334 break;
4335
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004336 // We lazily associate headers with their modules via the HeaderInfoTable.
4337 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4338 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 break;
4340 }
4341
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004342 case SUBMODULE_PRIVATE_HEADER: {
4343 if (First) {
4344 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004345 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004346 }
4347
4348 if (!CurrentModule)
4349 break;
4350
4351 // We lazily associate headers with their modules via the HeaderInfoTable.
4352 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4353 // of complete filenames or remove it entirely.
4354 break;
4355 }
4356
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 case SUBMODULE_TOPHEADER: {
4358 if (First) {
4359 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004360 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 }
4362
4363 if (!CurrentModule)
4364 break;
4365
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004366 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 break;
4368 }
4369
4370 case SUBMODULE_UMBRELLA_DIR: {
4371 if (First) {
4372 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004373 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 }
4375
4376 if (!CurrentModule)
4377 break;
4378
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004380 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 if (!CurrentModule->getUmbrellaDir())
4382 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4383 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004384 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4385 Error("mismatched umbrella directories in submodule");
4386 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 }
4388 }
4389 break;
4390 }
4391
4392 case SUBMODULE_METADATA: {
4393 if (!First) {
4394 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 }
4397 First = false;
4398
4399 F.BaseSubmoduleID = getTotalNumSubmodules();
4400 F.LocalNumSubmodules = Record[0];
4401 unsigned LocalBaseSubmoduleID = Record[1];
4402 if (F.LocalNumSubmodules > 0) {
4403 // Introduce the global -> local mapping for submodules within this
4404 // module.
4405 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4406
4407 // Introduce the local -> global mapping for submodules within this
4408 // module.
4409 F.SubmoduleRemap.insertOrReplace(
4410 std::make_pair(LocalBaseSubmoduleID,
4411 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4412
4413 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4414 }
4415 break;
4416 }
4417
4418 case SUBMODULE_IMPORTS: {
4419 if (First) {
4420 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
4423
4424 if (!CurrentModule)
4425 break;
4426
4427 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004428 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 Unresolved.File = &F;
4430 Unresolved.Mod = CurrentModule;
4431 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004432 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004434 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 }
4436 break;
4437 }
4438
4439 case SUBMODULE_EXPORTS: {
4440 if (First) {
4441 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 }
4444
4445 if (!CurrentModule)
4446 break;
4447
4448 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004449 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 Unresolved.File = &F;
4451 Unresolved.Mod = CurrentModule;
4452 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004453 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004455 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 }
4457
4458 // Once we've loaded the set of exports, there's no reason to keep
4459 // the parsed, unresolved exports around.
4460 CurrentModule->UnresolvedExports.clear();
4461 break;
4462 }
4463 case SUBMODULE_REQUIRES: {
4464 if (First) {
4465 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468
4469 if (!CurrentModule)
4470 break;
4471
Richard Smitha3feee22013-10-28 22:18:19 +00004472 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 Context.getTargetInfo());
4474 break;
4475 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004476
4477 case SUBMODULE_LINK_LIBRARY:
4478 if (First) {
4479 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004480 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004481 }
4482
4483 if (!CurrentModule)
4484 break;
4485
4486 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004487 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004488 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004489
4490 case SUBMODULE_CONFIG_MACRO:
4491 if (First) {
4492 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004493 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004494 }
4495
4496 if (!CurrentModule)
4497 break;
4498
4499 CurrentModule->ConfigMacros.push_back(Blob.str());
4500 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004501
4502 case SUBMODULE_CONFLICT: {
4503 if (First) {
4504 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004505 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004506 }
4507
4508 if (!CurrentModule)
4509 break;
4510
4511 UnresolvedModuleRef Unresolved;
4512 Unresolved.File = &F;
4513 Unresolved.Mod = CurrentModule;
4514 Unresolved.ID = Record[0];
4515 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4516 Unresolved.IsWildcard = false;
4517 Unresolved.String = Blob;
4518 UnresolvedModuleRefs.push_back(Unresolved);
4519 break;
4520 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522 }
4523}
4524
4525/// \brief Parse the record that corresponds to a LangOptions data
4526/// structure.
4527///
4528/// This routine parses the language options from the AST file and then gives
4529/// them to the AST listener if one is set.
4530///
4531/// \returns true if the listener deems the file unacceptable, false otherwise.
4532bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4533 bool Complain,
4534 ASTReaderListener &Listener) {
4535 LangOptions LangOpts;
4536 unsigned Idx = 0;
4537#define LANGOPT(Name, Bits, Default, Description) \
4538 LangOpts.Name = Record[Idx++];
4539#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4540 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4541#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004542#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4543#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004544
4545 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4546 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4547 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4548
4549 unsigned Length = Record[Idx++];
4550 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4551 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004552
4553 Idx += Length;
4554
4555 // Comment options.
4556 for (unsigned N = Record[Idx++]; N; --N) {
4557 LangOpts.CommentOpts.BlockCommandNames.push_back(
4558 ReadString(Record, Idx));
4559 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004560 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004561
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 return Listener.ReadLanguageOptions(LangOpts, Complain);
4563}
4564
4565bool ASTReader::ParseTargetOptions(const RecordData &Record,
4566 bool Complain,
4567 ASTReaderListener &Listener) {
4568 unsigned Idx = 0;
4569 TargetOptions TargetOpts;
4570 TargetOpts.Triple = ReadString(Record, Idx);
4571 TargetOpts.CPU = ReadString(Record, Idx);
4572 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 for (unsigned N = Record[Idx++]; N; --N) {
4574 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4575 }
4576 for (unsigned N = Record[Idx++]; N; --N) {
4577 TargetOpts.Features.push_back(ReadString(Record, Idx));
4578 }
4579
4580 return Listener.ReadTargetOptions(TargetOpts, Complain);
4581}
4582
4583bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4584 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004585 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004587#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004588#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004589 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004590#include "clang/Basic/DiagnosticOptions.def"
4591
4592 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004593 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 }
4595
4596 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4597}
4598
4599bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4600 ASTReaderListener &Listener) {
4601 FileSystemOptions FSOpts;
4602 unsigned Idx = 0;
4603 FSOpts.WorkingDir = ReadString(Record, Idx);
4604 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4605}
4606
4607bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4608 bool Complain,
4609 ASTReaderListener &Listener) {
4610 HeaderSearchOptions HSOpts;
4611 unsigned Idx = 0;
4612 HSOpts.Sysroot = ReadString(Record, Idx);
4613
4614 // Include entries.
4615 for (unsigned N = Record[Idx++]; N; --N) {
4616 std::string Path = ReadString(Record, Idx);
4617 frontend::IncludeDirGroup Group
4618 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 bool IsFramework = Record[Idx++];
4620 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004622 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 }
4624
4625 // System header prefixes.
4626 for (unsigned N = Record[Idx++]; N; --N) {
4627 std::string Prefix = ReadString(Record, Idx);
4628 bool IsSystemHeader = Record[Idx++];
4629 HSOpts.SystemHeaderPrefixes.push_back(
4630 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4631 }
4632
4633 HSOpts.ResourceDir = ReadString(Record, Idx);
4634 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004635 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 HSOpts.DisableModuleHash = Record[Idx++];
4637 HSOpts.UseBuiltinIncludes = Record[Idx++];
4638 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4639 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4640 HSOpts.UseLibcxx = Record[Idx++];
4641
4642 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4643}
4644
4645bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4646 bool Complain,
4647 ASTReaderListener &Listener,
4648 std::string &SuggestedPredefines) {
4649 PreprocessorOptions PPOpts;
4650 unsigned Idx = 0;
4651
4652 // Macro definitions/undefs
4653 for (unsigned N = Record[Idx++]; N; --N) {
4654 std::string Macro = ReadString(Record, Idx);
4655 bool IsUndef = Record[Idx++];
4656 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4657 }
4658
4659 // Includes
4660 for (unsigned N = Record[Idx++]; N; --N) {
4661 PPOpts.Includes.push_back(ReadString(Record, Idx));
4662 }
4663
4664 // Macro Includes
4665 for (unsigned N = Record[Idx++]; N; --N) {
4666 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4667 }
4668
4669 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004670 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4672 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4673 PPOpts.ObjCXXARCStandardLibrary =
4674 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4675 SuggestedPredefines.clear();
4676 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4677 SuggestedPredefines);
4678}
4679
4680std::pair<ModuleFile *, unsigned>
4681ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4682 GlobalPreprocessedEntityMapType::iterator
4683 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4684 assert(I != GlobalPreprocessedEntityMap.end() &&
4685 "Corrupted global preprocessed entity map");
4686 ModuleFile *M = I->second;
4687 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4688 return std::make_pair(M, LocalIndex);
4689}
4690
4691std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4692ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4693 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4694 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4695 Mod.NumPreprocessedEntities);
4696
4697 return std::make_pair(PreprocessingRecord::iterator(),
4698 PreprocessingRecord::iterator());
4699}
4700
4701std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4702ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4703 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4704 ModuleDeclIterator(this, &Mod,
4705 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4706}
4707
4708PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4709 PreprocessedEntityID PPID = Index+1;
4710 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4711 ModuleFile &M = *PPInfo.first;
4712 unsigned LocalIndex = PPInfo.second;
4713 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4714
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 if (!PP.getPreprocessingRecord()) {
4716 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004717 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 }
4719
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004720 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4721 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4722
4723 llvm::BitstreamEntry Entry =
4724 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4725 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004726 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004727
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 // Read the record.
4729 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4730 ReadSourceLocation(M, PPOffs.End));
4731 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004732 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 RecordData Record;
4734 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004735 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4736 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 switch (RecType) {
4738 case PPD_MACRO_EXPANSION: {
4739 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004740 IdentifierInfo *Name = nullptr;
4741 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 if (isBuiltin)
4743 Name = getLocalIdentifier(M, Record[1]);
4744 else {
4745 PreprocessedEntityID
4746 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4747 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4748 }
4749
4750 MacroExpansion *ME;
4751 if (isBuiltin)
4752 ME = new (PPRec) MacroExpansion(Name, Range);
4753 else
4754 ME = new (PPRec) MacroExpansion(Def, Range);
4755
4756 return ME;
4757 }
4758
4759 case PPD_MACRO_DEFINITION: {
4760 // Decode the identifier info and then check again; if the macro is
4761 // still defined and associated with the identifier,
4762 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4763 MacroDefinition *MD
4764 = new (PPRec) MacroDefinition(II, Range);
4765
4766 if (DeserializationListener)
4767 DeserializationListener->MacroDefinitionRead(PPID, MD);
4768
4769 return MD;
4770 }
4771
4772 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004773 const char *FullFileNameStart = Blob.data() + Record[0];
4774 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004775 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 if (!FullFileName.empty())
4777 File = PP.getFileManager().getFile(FullFileName);
4778
4779 // FIXME: Stable encoding
4780 InclusionDirective::InclusionKind Kind
4781 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4782 InclusionDirective *ID
4783 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004784 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 Record[1], Record[3],
4786 File,
4787 Range);
4788 return ID;
4789 }
4790 }
4791
4792 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4793}
4794
4795/// \brief \arg SLocMapI points at a chunk of a module that contains no
4796/// preprocessed entities or the entities it contains are not the ones we are
4797/// looking for. Find the next module that contains entities and return the ID
4798/// of the first entry.
4799PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4800 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4801 ++SLocMapI;
4802 for (GlobalSLocOffsetMapType::const_iterator
4803 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4804 ModuleFile &M = *SLocMapI->second;
4805 if (M.NumPreprocessedEntities)
4806 return M.BasePreprocessedEntityID;
4807 }
4808
4809 return getTotalNumPreprocessedEntities();
4810}
4811
4812namespace {
4813
4814template <unsigned PPEntityOffset::*PPLoc>
4815struct PPEntityComp {
4816 const ASTReader &Reader;
4817 ModuleFile &M;
4818
4819 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4820
4821 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4822 SourceLocation LHS = getLoc(L);
4823 SourceLocation RHS = getLoc(R);
4824 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4825 }
4826
4827 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4828 SourceLocation LHS = getLoc(L);
4829 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4830 }
4831
4832 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4833 SourceLocation RHS = getLoc(R);
4834 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4835 }
4836
4837 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4838 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4839 }
4840};
4841
4842}
4843
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004844PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4845 bool EndsAfter) const {
4846 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 return getTotalNumPreprocessedEntities();
4848
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004849 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4850 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4852 "Corrupted global sloc offset map");
4853
4854 if (SLocMapI->second->NumPreprocessedEntities == 0)
4855 return findNextPreprocessedEntity(SLocMapI);
4856
4857 ModuleFile &M = *SLocMapI->second;
4858 typedef const PPEntityOffset *pp_iterator;
4859 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4860 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4861
4862 size_t Count = M.NumPreprocessedEntities;
4863 size_t Half;
4864 pp_iterator First = pp_begin;
4865 pp_iterator PPI;
4866
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004867 if (EndsAfter) {
4868 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4869 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4870 } else {
4871 // Do a binary search manually instead of using std::lower_bound because
4872 // The end locations of entities may be unordered (when a macro expansion
4873 // is inside another macro argument), but for this case it is not important
4874 // whether we get the first macro expansion or its containing macro.
4875 while (Count > 0) {
4876 Half = Count / 2;
4877 PPI = First;
4878 std::advance(PPI, Half);
4879 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4880 Loc)) {
4881 First = PPI;
4882 ++First;
4883 Count = Count - Half - 1;
4884 } else
4885 Count = Half;
4886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 }
4888
4889 if (PPI == pp_end)
4890 return findNextPreprocessedEntity(SLocMapI);
4891
4892 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4893}
4894
Guy Benyei11169dd2012-12-18 14:30:41 +00004895/// \brief Returns a pair of [Begin, End) indices of preallocated
4896/// preprocessed entities that \arg Range encompasses.
4897std::pair<unsigned, unsigned>
4898 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4899 if (Range.isInvalid())
4900 return std::make_pair(0,0);
4901 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4902
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004903 PreprocessedEntityID BeginID =
4904 findPreprocessedEntity(Range.getBegin(), false);
4905 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 return std::make_pair(BeginID, EndID);
4907}
4908
4909/// \brief Optionally returns true or false if the preallocated preprocessed
4910/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004911Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 FileID FID) {
4913 if (FID.isInvalid())
4914 return false;
4915
4916 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4917 ModuleFile &M = *PPInfo.first;
4918 unsigned LocalIndex = PPInfo.second;
4919 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4920
4921 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4922 if (Loc.isInvalid())
4923 return false;
4924
4925 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4926 return true;
4927 else
4928 return false;
4929}
4930
4931namespace {
4932 /// \brief Visitor used to search for information about a header file.
4933 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 const FileEntry *FE;
4935
David Blaikie05785d12013-02-20 22:23:23 +00004936 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004937
4938 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004939 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4940 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004941
4942 static bool visit(ModuleFile &M, void *UserData) {
4943 HeaderFileInfoVisitor *This
4944 = static_cast<HeaderFileInfoVisitor *>(UserData);
4945
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 HeaderFileInfoLookupTable *Table
4947 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4948 if (!Table)
4949 return false;
4950
4951 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004952 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 if (Pos == Table->end())
4954 return false;
4955
4956 This->HFI = *Pos;
4957 return true;
4958 }
4959
David Blaikie05785d12013-02-20 22:23:23 +00004960 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 };
4962}
4963
4964HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004965 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004967 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004969
4970 return HeaderFileInfo();
4971}
4972
4973void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4974 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004975 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4977 ModuleFile &F = *(*I);
4978 unsigned Idx = 0;
4979 DiagStates.clear();
4980 assert(!Diag.DiagStates.empty());
4981 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4982 while (Idx < F.PragmaDiagMappings.size()) {
4983 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4984 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4985 if (DiagStateID != 0) {
4986 Diag.DiagStatePoints.push_back(
4987 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4988 FullSourceLoc(Loc, SourceMgr)));
4989 continue;
4990 }
4991
4992 assert(DiagStateID == 0);
4993 // A new DiagState was created here.
4994 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4995 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4996 DiagStates.push_back(NewState);
4997 Diag.DiagStatePoints.push_back(
4998 DiagnosticsEngine::DiagStatePoint(NewState,
4999 FullSourceLoc(Loc, SourceMgr)));
5000 while (1) {
5001 assert(Idx < F.PragmaDiagMappings.size() &&
5002 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5003 if (Idx >= F.PragmaDiagMappings.size()) {
5004 break; // Something is messed up but at least avoid infinite loop in
5005 // release build.
5006 }
5007 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5008 if (DiagID == (unsigned)-1) {
5009 break; // no more diag/map pairs for this location.
5010 }
5011 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5012 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5013 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5014 }
5015 }
5016 }
5017}
5018
5019/// \brief Get the correct cursor and offset for loading a type.
5020ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5021 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5022 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5023 ModuleFile *M = I->second;
5024 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5025}
5026
5027/// \brief Read and return the type with the given index..
5028///
5029/// The index is the type ID, shifted and minus the number of predefs. This
5030/// routine actually reads the record corresponding to the type at the given
5031/// location. It is a helper routine for GetType, which deals with reading type
5032/// IDs.
5033QualType ASTReader::readTypeRecord(unsigned Index) {
5034 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005035 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005036
5037 // Keep track of where we are in the stream, then jump back there
5038 // after reading this type.
5039 SavedStreamPosition SavedPosition(DeclsCursor);
5040
5041 ReadingKindTracker ReadingKind(Read_Type, *this);
5042
5043 // Note that we are loading a type record.
5044 Deserializing AType(this);
5045
5046 unsigned Idx = 0;
5047 DeclsCursor.JumpToBit(Loc.Offset);
5048 RecordData Record;
5049 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005050 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case TYPE_EXT_QUAL: {
5052 if (Record.size() != 2) {
5053 Error("Incorrect encoding of extended qualifier type");
5054 return QualType();
5055 }
5056 QualType Base = readType(*Loc.F, Record, Idx);
5057 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5058 return Context.getQualifiedType(Base, Quals);
5059 }
5060
5061 case TYPE_COMPLEX: {
5062 if (Record.size() != 1) {
5063 Error("Incorrect encoding of complex type");
5064 return QualType();
5065 }
5066 QualType ElemType = readType(*Loc.F, Record, Idx);
5067 return Context.getComplexType(ElemType);
5068 }
5069
5070 case TYPE_POINTER: {
5071 if (Record.size() != 1) {
5072 Error("Incorrect encoding of pointer type");
5073 return QualType();
5074 }
5075 QualType PointeeType = readType(*Loc.F, Record, Idx);
5076 return Context.getPointerType(PointeeType);
5077 }
5078
Reid Kleckner8a365022013-06-24 17:51:48 +00005079 case TYPE_DECAYED: {
5080 if (Record.size() != 1) {
5081 Error("Incorrect encoding of decayed type");
5082 return QualType();
5083 }
5084 QualType OriginalType = readType(*Loc.F, Record, Idx);
5085 QualType DT = Context.getAdjustedParameterType(OriginalType);
5086 if (!isa<DecayedType>(DT))
5087 Error("Decayed type does not decay");
5088 return DT;
5089 }
5090
Reid Kleckner0503a872013-12-05 01:23:43 +00005091 case TYPE_ADJUSTED: {
5092 if (Record.size() != 2) {
5093 Error("Incorrect encoding of adjusted type");
5094 return QualType();
5095 }
5096 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5097 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5098 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5099 }
5100
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case TYPE_BLOCK_POINTER: {
5102 if (Record.size() != 1) {
5103 Error("Incorrect encoding of block pointer type");
5104 return QualType();
5105 }
5106 QualType PointeeType = readType(*Loc.F, Record, Idx);
5107 return Context.getBlockPointerType(PointeeType);
5108 }
5109
5110 case TYPE_LVALUE_REFERENCE: {
5111 if (Record.size() != 2) {
5112 Error("Incorrect encoding of lvalue reference type");
5113 return QualType();
5114 }
5115 QualType PointeeType = readType(*Loc.F, Record, Idx);
5116 return Context.getLValueReferenceType(PointeeType, Record[1]);
5117 }
5118
5119 case TYPE_RVALUE_REFERENCE: {
5120 if (Record.size() != 1) {
5121 Error("Incorrect encoding of rvalue reference type");
5122 return QualType();
5123 }
5124 QualType PointeeType = readType(*Loc.F, Record, Idx);
5125 return Context.getRValueReferenceType(PointeeType);
5126 }
5127
5128 case TYPE_MEMBER_POINTER: {
5129 if (Record.size() != 2) {
5130 Error("Incorrect encoding of member pointer type");
5131 return QualType();
5132 }
5133 QualType PointeeType = readType(*Loc.F, Record, Idx);
5134 QualType ClassType = readType(*Loc.F, Record, Idx);
5135 if (PointeeType.isNull() || ClassType.isNull())
5136 return QualType();
5137
5138 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5139 }
5140
5141 case TYPE_CONSTANT_ARRAY: {
5142 QualType ElementType = readType(*Loc.F, Record, Idx);
5143 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5144 unsigned IndexTypeQuals = Record[2];
5145 unsigned Idx = 3;
5146 llvm::APInt Size = ReadAPInt(Record, Idx);
5147 return Context.getConstantArrayType(ElementType, Size,
5148 ASM, IndexTypeQuals);
5149 }
5150
5151 case TYPE_INCOMPLETE_ARRAY: {
5152 QualType ElementType = readType(*Loc.F, Record, Idx);
5153 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5154 unsigned IndexTypeQuals = Record[2];
5155 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5156 }
5157
5158 case TYPE_VARIABLE_ARRAY: {
5159 QualType ElementType = readType(*Loc.F, Record, Idx);
5160 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5161 unsigned IndexTypeQuals = Record[2];
5162 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5163 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5164 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5165 ASM, IndexTypeQuals,
5166 SourceRange(LBLoc, RBLoc));
5167 }
5168
5169 case TYPE_VECTOR: {
5170 if (Record.size() != 3) {
5171 Error("incorrect encoding of vector type in AST file");
5172 return QualType();
5173 }
5174
5175 QualType ElementType = readType(*Loc.F, Record, Idx);
5176 unsigned NumElements = Record[1];
5177 unsigned VecKind = Record[2];
5178 return Context.getVectorType(ElementType, NumElements,
5179 (VectorType::VectorKind)VecKind);
5180 }
5181
5182 case TYPE_EXT_VECTOR: {
5183 if (Record.size() != 3) {
5184 Error("incorrect encoding of extended vector type in AST file");
5185 return QualType();
5186 }
5187
5188 QualType ElementType = readType(*Loc.F, Record, Idx);
5189 unsigned NumElements = Record[1];
5190 return Context.getExtVectorType(ElementType, NumElements);
5191 }
5192
5193 case TYPE_FUNCTION_NO_PROTO: {
5194 if (Record.size() != 6) {
5195 Error("incorrect encoding of no-proto function type");
5196 return QualType();
5197 }
5198 QualType ResultType = readType(*Loc.F, Record, Idx);
5199 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5200 (CallingConv)Record[4], Record[5]);
5201 return Context.getFunctionNoProtoType(ResultType, Info);
5202 }
5203
5204 case TYPE_FUNCTION_PROTO: {
5205 QualType ResultType = readType(*Loc.F, Record, Idx);
5206
5207 FunctionProtoType::ExtProtoInfo EPI;
5208 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5209 /*hasregparm*/ Record[2],
5210 /*regparm*/ Record[3],
5211 static_cast<CallingConv>(Record[4]),
5212 /*produces*/ Record[5]);
5213
5214 unsigned Idx = 6;
5215 unsigned NumParams = Record[Idx++];
5216 SmallVector<QualType, 16> ParamTypes;
5217 for (unsigned I = 0; I != NumParams; ++I)
5218 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5219
5220 EPI.Variadic = Record[Idx++];
5221 EPI.HasTrailingReturn = Record[Idx++];
5222 EPI.TypeQuals = Record[Idx++];
5223 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005224 SmallVector<QualType, 8> ExceptionStorage;
5225 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005226 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 }
5228
5229 case TYPE_UNRESOLVED_USING: {
5230 unsigned Idx = 0;
5231 return Context.getTypeDeclType(
5232 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5233 }
5234
5235 case TYPE_TYPEDEF: {
5236 if (Record.size() != 2) {
5237 Error("incorrect encoding of typedef type");
5238 return QualType();
5239 }
5240 unsigned Idx = 0;
5241 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5242 QualType Canonical = readType(*Loc.F, Record, Idx);
5243 if (!Canonical.isNull())
5244 Canonical = Context.getCanonicalType(Canonical);
5245 return Context.getTypedefType(Decl, Canonical);
5246 }
5247
5248 case TYPE_TYPEOF_EXPR:
5249 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5250
5251 case TYPE_TYPEOF: {
5252 if (Record.size() != 1) {
5253 Error("incorrect encoding of typeof(type) in AST file");
5254 return QualType();
5255 }
5256 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5257 return Context.getTypeOfType(UnderlyingType);
5258 }
5259
5260 case TYPE_DECLTYPE: {
5261 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5262 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5263 }
5264
5265 case TYPE_UNARY_TRANSFORM: {
5266 QualType BaseType = readType(*Loc.F, Record, Idx);
5267 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5268 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5269 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5270 }
5271
Richard Smith74aeef52013-04-26 16:15:35 +00005272 case TYPE_AUTO: {
5273 QualType Deduced = readType(*Loc.F, Record, Idx);
5274 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005275 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005276 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005277 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005278
5279 case TYPE_RECORD: {
5280 if (Record.size() != 2) {
5281 Error("incorrect encoding of record type");
5282 return QualType();
5283 }
5284 unsigned Idx = 0;
5285 bool IsDependent = Record[Idx++];
5286 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5287 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5288 QualType T = Context.getRecordType(RD);
5289 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5290 return T;
5291 }
5292
5293 case TYPE_ENUM: {
5294 if (Record.size() != 2) {
5295 Error("incorrect encoding of enum type");
5296 return QualType();
5297 }
5298 unsigned Idx = 0;
5299 bool IsDependent = Record[Idx++];
5300 QualType T
5301 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5302 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5303 return T;
5304 }
5305
5306 case TYPE_ATTRIBUTED: {
5307 if (Record.size() != 3) {
5308 Error("incorrect encoding of attributed type");
5309 return QualType();
5310 }
5311 QualType modifiedType = readType(*Loc.F, Record, Idx);
5312 QualType equivalentType = readType(*Loc.F, Record, Idx);
5313 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5314 return Context.getAttributedType(kind, modifiedType, equivalentType);
5315 }
5316
5317 case TYPE_PAREN: {
5318 if (Record.size() != 1) {
5319 Error("incorrect encoding of paren type");
5320 return QualType();
5321 }
5322 QualType InnerType = readType(*Loc.F, Record, Idx);
5323 return Context.getParenType(InnerType);
5324 }
5325
5326 case TYPE_PACK_EXPANSION: {
5327 if (Record.size() != 2) {
5328 Error("incorrect encoding of pack expansion type");
5329 return QualType();
5330 }
5331 QualType Pattern = readType(*Loc.F, Record, Idx);
5332 if (Pattern.isNull())
5333 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005334 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 if (Record[1])
5336 NumExpansions = Record[1] - 1;
5337 return Context.getPackExpansionType(Pattern, NumExpansions);
5338 }
5339
5340 case TYPE_ELABORATED: {
5341 unsigned Idx = 0;
5342 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5343 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5344 QualType NamedType = readType(*Loc.F, Record, Idx);
5345 return Context.getElaboratedType(Keyword, NNS, NamedType);
5346 }
5347
5348 case TYPE_OBJC_INTERFACE: {
5349 unsigned Idx = 0;
5350 ObjCInterfaceDecl *ItfD
5351 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5352 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5353 }
5354
5355 case TYPE_OBJC_OBJECT: {
5356 unsigned Idx = 0;
5357 QualType Base = readType(*Loc.F, Record, Idx);
5358 unsigned NumProtos = Record[Idx++];
5359 SmallVector<ObjCProtocolDecl*, 4> Protos;
5360 for (unsigned I = 0; I != NumProtos; ++I)
5361 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5362 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5363 }
5364
5365 case TYPE_OBJC_OBJECT_POINTER: {
5366 unsigned Idx = 0;
5367 QualType Pointee = readType(*Loc.F, Record, Idx);
5368 return Context.getObjCObjectPointerType(Pointee);
5369 }
5370
5371 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5372 unsigned Idx = 0;
5373 QualType Parm = readType(*Loc.F, Record, Idx);
5374 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005375 return Context.getSubstTemplateTypeParmType(
5376 cast<TemplateTypeParmType>(Parm),
5377 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 }
5379
5380 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5381 unsigned Idx = 0;
5382 QualType Parm = readType(*Loc.F, Record, Idx);
5383 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5384 return Context.getSubstTemplateTypeParmPackType(
5385 cast<TemplateTypeParmType>(Parm),
5386 ArgPack);
5387 }
5388
5389 case TYPE_INJECTED_CLASS_NAME: {
5390 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5391 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5392 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5393 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005394 const Type *T;
5395 if (const Type *Existing = D->getTypeForDecl())
5396 T = Existing;
5397 else if (auto *Prev = D->getPreviousDecl())
5398 T = Prev->getTypeForDecl();
5399 else
5400 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5401 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005402 }
5403
5404 case TYPE_TEMPLATE_TYPE_PARM: {
5405 unsigned Idx = 0;
5406 unsigned Depth = Record[Idx++];
5407 unsigned Index = Record[Idx++];
5408 bool Pack = Record[Idx++];
5409 TemplateTypeParmDecl *D
5410 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5411 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5412 }
5413
5414 case TYPE_DEPENDENT_NAME: {
5415 unsigned Idx = 0;
5416 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5417 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5418 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5419 QualType Canon = readType(*Loc.F, Record, Idx);
5420 if (!Canon.isNull())
5421 Canon = Context.getCanonicalType(Canon);
5422 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5423 }
5424
5425 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5426 unsigned Idx = 0;
5427 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5428 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5429 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5430 unsigned NumArgs = Record[Idx++];
5431 SmallVector<TemplateArgument, 8> Args;
5432 Args.reserve(NumArgs);
5433 while (NumArgs--)
5434 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5435 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5436 Args.size(), Args.data());
5437 }
5438
5439 case TYPE_DEPENDENT_SIZED_ARRAY: {
5440 unsigned Idx = 0;
5441
5442 // ArrayType
5443 QualType ElementType = readType(*Loc.F, Record, Idx);
5444 ArrayType::ArraySizeModifier ASM
5445 = (ArrayType::ArraySizeModifier)Record[Idx++];
5446 unsigned IndexTypeQuals = Record[Idx++];
5447
5448 // DependentSizedArrayType
5449 Expr *NumElts = ReadExpr(*Loc.F);
5450 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5451
5452 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5453 IndexTypeQuals, Brackets);
5454 }
5455
5456 case TYPE_TEMPLATE_SPECIALIZATION: {
5457 unsigned Idx = 0;
5458 bool IsDependent = Record[Idx++];
5459 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5460 SmallVector<TemplateArgument, 8> Args;
5461 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5462 QualType Underlying = readType(*Loc.F, Record, Idx);
5463 QualType T;
5464 if (Underlying.isNull())
5465 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5466 Args.size());
5467 else
5468 T = Context.getTemplateSpecializationType(Name, Args.data(),
5469 Args.size(), Underlying);
5470 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5471 return T;
5472 }
5473
5474 case TYPE_ATOMIC: {
5475 if (Record.size() != 1) {
5476 Error("Incorrect encoding of atomic type");
5477 return QualType();
5478 }
5479 QualType ValueType = readType(*Loc.F, Record, Idx);
5480 return Context.getAtomicType(ValueType);
5481 }
5482 }
5483 llvm_unreachable("Invalid TypeCode!");
5484}
5485
Richard Smith564417a2014-03-20 21:47:22 +00005486void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5487 SmallVectorImpl<QualType> &Exceptions,
5488 FunctionProtoType::ExtProtoInfo &EPI,
5489 const RecordData &Record, unsigned &Idx) {
5490 ExceptionSpecificationType EST =
5491 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5492 EPI.ExceptionSpecType = EST;
5493 if (EST == EST_Dynamic) {
5494 EPI.NumExceptions = Record[Idx++];
5495 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5496 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5497 EPI.Exceptions = Exceptions.data();
5498 } else if (EST == EST_ComputedNoexcept) {
5499 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5500 } else if (EST == EST_Uninstantiated) {
5501 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5502 EPI.ExceptionSpecTemplate =
5503 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5504 } else if (EST == EST_Unevaluated) {
5505 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5506 }
5507}
5508
Guy Benyei11169dd2012-12-18 14:30:41 +00005509class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5510 ASTReader &Reader;
5511 ModuleFile &F;
5512 const ASTReader::RecordData &Record;
5513 unsigned &Idx;
5514
5515 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5516 unsigned &I) {
5517 return Reader.ReadSourceLocation(F, R, I);
5518 }
5519
5520 template<typename T>
5521 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5522 return Reader.ReadDeclAs<T>(F, Record, Idx);
5523 }
5524
5525public:
5526 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5527 const ASTReader::RecordData &Record, unsigned &Idx)
5528 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5529 { }
5530
5531 // We want compile-time assurance that we've enumerated all of
5532 // these, so unfortunately we have to declare them first, then
5533 // define them out-of-line.
5534#define ABSTRACT_TYPELOC(CLASS, PARENT)
5535#define TYPELOC(CLASS, PARENT) \
5536 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5537#include "clang/AST/TypeLocNodes.def"
5538
5539 void VisitFunctionTypeLoc(FunctionTypeLoc);
5540 void VisitArrayTypeLoc(ArrayTypeLoc);
5541};
5542
5543void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5544 // nothing to do
5545}
5546void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5547 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5548 if (TL.needsExtraLocalData()) {
5549 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5550 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5551 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5552 TL.setModeAttr(Record[Idx++]);
5553 }
5554}
5555void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5556 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5557}
5558void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5559 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5560}
Reid Kleckner8a365022013-06-24 17:51:48 +00005561void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5562 // nothing to do
5563}
Reid Kleckner0503a872013-12-05 01:23:43 +00005564void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5565 // nothing to do
5566}
Guy Benyei11169dd2012-12-18 14:30:41 +00005567void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5568 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5569}
5570void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5571 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5574 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5575}
5576void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5577 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5578 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5579}
5580void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5581 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5582 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5583 if (Record[Idx++])
5584 TL.setSizeExpr(Reader.ReadExpr(F));
5585 else
Craig Toppera13603a2014-05-22 05:54:18 +00005586 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005587}
5588void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5589 VisitArrayTypeLoc(TL);
5590}
5591void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5592 VisitArrayTypeLoc(TL);
5593}
5594void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5595 VisitArrayTypeLoc(TL);
5596}
5597void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5598 DependentSizedArrayTypeLoc TL) {
5599 VisitArrayTypeLoc(TL);
5600}
5601void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5602 DependentSizedExtVectorTypeLoc TL) {
5603 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5604}
5605void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5606 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5610}
5611void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5612 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5613 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5614 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5615 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005616 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5617 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 }
5619}
5620void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5621 VisitFunctionTypeLoc(TL);
5622}
5623void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5624 VisitFunctionTypeLoc(TL);
5625}
5626void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5627 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628}
5629void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5630 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5631}
5632void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5633 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5634 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5635 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5636}
5637void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5638 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5639 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5640 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5641 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5642}
5643void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5644 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5645}
5646void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5647 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5648 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5649 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5650 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5651}
5652void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5654}
5655void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5656 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5657}
5658void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5659 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5660}
5661void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5662 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5663 if (TL.hasAttrOperand()) {
5664 SourceRange range;
5665 range.setBegin(ReadSourceLocation(Record, Idx));
5666 range.setEnd(ReadSourceLocation(Record, Idx));
5667 TL.setAttrOperandParensRange(range);
5668 }
5669 if (TL.hasAttrExprOperand()) {
5670 if (Record[Idx++])
5671 TL.setAttrExprOperand(Reader.ReadExpr(F));
5672 else
Craig Toppera13603a2014-05-22 05:54:18 +00005673 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 } else if (TL.hasAttrEnumOperand())
5675 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5676}
5677void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5679}
5680void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5681 SubstTemplateTypeParmTypeLoc TL) {
5682 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5683}
5684void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5685 SubstTemplateTypeParmPackTypeLoc TL) {
5686 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5687}
5688void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5689 TemplateSpecializationTypeLoc TL) {
5690 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5691 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5692 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5693 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5694 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5695 TL.setArgLocInfo(i,
5696 Reader.GetTemplateArgumentLocInfo(F,
5697 TL.getTypePtr()->getArg(i).getKind(),
5698 Record, Idx));
5699}
5700void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5701 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5702 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5703}
5704void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5705 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5706 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5707}
5708void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5709 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5710}
5711void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5712 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5713 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5714 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5715}
5716void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5717 DependentTemplateSpecializationTypeLoc TL) {
5718 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5719 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5720 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5721 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5722 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5723 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5724 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5725 TL.setArgLocInfo(I,
5726 Reader.GetTemplateArgumentLocInfo(F,
5727 TL.getTypePtr()->getArg(I).getKind(),
5728 Record, Idx));
5729}
5730void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5731 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5734 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5735}
5736void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5737 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5738 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5739 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5740 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5741 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5744 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5745}
5746void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5747 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5748 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5749 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5750}
5751
5752TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5753 const RecordData &Record,
5754 unsigned &Idx) {
5755 QualType InfoTy = readType(F, Record, Idx);
5756 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005757 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005758
5759 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5760 TypeLocReader TLR(*this, F, Record, Idx);
5761 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5762 TLR.Visit(TL);
5763 return TInfo;
5764}
5765
5766QualType ASTReader::GetType(TypeID ID) {
5767 unsigned FastQuals = ID & Qualifiers::FastMask;
5768 unsigned Index = ID >> Qualifiers::FastWidth;
5769
5770 if (Index < NUM_PREDEF_TYPE_IDS) {
5771 QualType T;
5772 switch ((PredefinedTypeIDs)Index) {
5773 case PREDEF_TYPE_NULL_ID: return QualType();
5774 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5775 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5776
5777 case PREDEF_TYPE_CHAR_U_ID:
5778 case PREDEF_TYPE_CHAR_S_ID:
5779 // FIXME: Check that the signedness of CharTy is correct!
5780 T = Context.CharTy;
5781 break;
5782
5783 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5784 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5785 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5786 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5787 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5788 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5789 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5790 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5791 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5792 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5793 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5794 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5795 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5796 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5797 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5798 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5799 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5800 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5801 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5802 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5803 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5804 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5805 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5806 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5807 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5808 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5809 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5810 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005811 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5812 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5813 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5814 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5815 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5816 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005817 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005818 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005819 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5820
5821 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5822 T = Context.getAutoRRefDeductType();
5823 break;
5824
5825 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5826 T = Context.ARCUnbridgedCastTy;
5827 break;
5828
5829 case PREDEF_TYPE_VA_LIST_TAG:
5830 T = Context.getVaListTagType();
5831 break;
5832
5833 case PREDEF_TYPE_BUILTIN_FN:
5834 T = Context.BuiltinFnTy;
5835 break;
5836 }
5837
5838 assert(!T.isNull() && "Unknown predefined type");
5839 return T.withFastQualifiers(FastQuals);
5840 }
5841
5842 Index -= NUM_PREDEF_TYPE_IDS;
5843 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5844 if (TypesLoaded[Index].isNull()) {
5845 TypesLoaded[Index] = readTypeRecord(Index);
5846 if (TypesLoaded[Index].isNull())
5847 return QualType();
5848
5849 TypesLoaded[Index]->setFromAST();
5850 if (DeserializationListener)
5851 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5852 TypesLoaded[Index]);
5853 }
5854
5855 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5856}
5857
5858QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5859 return GetType(getGlobalTypeID(F, LocalID));
5860}
5861
5862serialization::TypeID
5863ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5864 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5865 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5866
5867 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5868 return LocalID;
5869
5870 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5871 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5872 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5873
5874 unsigned GlobalIndex = LocalIndex + I->second;
5875 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5876}
5877
5878TemplateArgumentLocInfo
5879ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5880 TemplateArgument::ArgKind Kind,
5881 const RecordData &Record,
5882 unsigned &Index) {
5883 switch (Kind) {
5884 case TemplateArgument::Expression:
5885 return ReadExpr(F);
5886 case TemplateArgument::Type:
5887 return GetTypeSourceInfo(F, Record, Index);
5888 case TemplateArgument::Template: {
5889 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5890 Index);
5891 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5892 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5893 SourceLocation());
5894 }
5895 case TemplateArgument::TemplateExpansion: {
5896 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5897 Index);
5898 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5899 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5900 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5901 EllipsisLoc);
5902 }
5903 case TemplateArgument::Null:
5904 case TemplateArgument::Integral:
5905 case TemplateArgument::Declaration:
5906 case TemplateArgument::NullPtr:
5907 case TemplateArgument::Pack:
5908 // FIXME: Is this right?
5909 return TemplateArgumentLocInfo();
5910 }
5911 llvm_unreachable("unexpected template argument loc");
5912}
5913
5914TemplateArgumentLoc
5915ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5916 const RecordData &Record, unsigned &Index) {
5917 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5918
5919 if (Arg.getKind() == TemplateArgument::Expression) {
5920 if (Record[Index++]) // bool InfoHasSameExpr.
5921 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5922 }
5923 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5924 Record, Index));
5925}
5926
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005927const ASTTemplateArgumentListInfo*
5928ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5929 const RecordData &Record,
5930 unsigned &Index) {
5931 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5932 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5933 unsigned NumArgsAsWritten = Record[Index++];
5934 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5935 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5936 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5937 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5938}
5939
Guy Benyei11169dd2012-12-18 14:30:41 +00005940Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5941 return GetDecl(ID);
5942}
5943
Richard Smith053f6c62014-05-16 23:01:30 +00005944void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005945 if (NumCurrentElementsDeserializing) {
5946 // We arrange to not care about the complete redeclaration chain while we're
5947 // deserializing. Just remember that the AST has marked this one as complete
5948 // but that it's not actually complete yet, so we know we still need to
5949 // complete it later.
5950 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5951 return;
5952 }
5953
Richard Smith053f6c62014-05-16 23:01:30 +00005954 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5955
5956 // Recursively ensure that the decl context itself is complete
5957 // (in particular, this matters if the decl context is a namespace).
5958 //
5959 // FIXME: This should be performed by lookup instead of here.
5960 cast<Decl>(DC)->getMostRecentDecl();
5961
5962 // If this is a named declaration, complete it by looking it up
5963 // within its context.
5964 //
5965 // FIXME: We don't currently handle the cases where we can't do this;
5966 // merging a class definition that contains unnamed entities should merge
5967 // those entities. Likewise, merging a function definition should merge
5968 // all mergeable entities within it.
5969 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5970 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5971 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5972 auto *II = Name.getAsIdentifierInfo();
5973 if (isa<TranslationUnitDecl>(DC) && II) {
5974 // Outside of C++, we don't have a lookup table for the TU, so update
5975 // the identifier instead. In C++, either way should work fine.
5976 if (II->isOutOfDate())
5977 updateOutOfDateIdentifier(*II);
5978 } else
5979 DC->lookup(Name);
5980 }
5981 }
5982}
5983
Richard Smithcd45dbc2014-04-19 03:48:30 +00005984uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5985 const RecordData &Record,
5986 unsigned &Idx) {
5987 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5988 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005990 }
5991
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 unsigned LocalID = Record[Idx++];
5993 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5994}
5995
5996CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5997 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005998 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 SavedStreamPosition SavedPosition(Cursor);
6000 Cursor.JumpToBit(Loc.Offset);
6001 ReadingKindTracker ReadingKind(Read_Decl, *this);
6002 RecordData Record;
6003 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006004 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006006 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006007 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 }
6009
6010 unsigned Idx = 0;
6011 unsigned NumBases = Record[Idx++];
6012 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6013 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6014 for (unsigned I = 0; I != NumBases; ++I)
6015 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6016 return Bases;
6017}
6018
6019serialization::DeclID
6020ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6021 if (LocalID < NUM_PREDEF_DECL_IDS)
6022 return LocalID;
6023
6024 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6025 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6026 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6027
6028 return LocalID + I->second;
6029}
6030
6031bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6032 ModuleFile &M) const {
6033 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6034 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6035 return &M == I->second;
6036}
6037
Douglas Gregor9f782892013-01-21 15:25:38 +00006038ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006040 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6042 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6043 return I->second;
6044}
6045
6046SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6047 if (ID < NUM_PREDEF_DECL_IDS)
6048 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6051
6052 if (Index > DeclsLoaded.size()) {
6053 Error("declaration ID out-of-range for AST file");
6054 return SourceLocation();
6055 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 if (Decl *D = DeclsLoaded[Index])
6058 return D->getLocation();
6059
6060 unsigned RawLocation = 0;
6061 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6062 return ReadSourceLocation(*Rec.F, RawLocation);
6063}
6064
Richard Smithcd45dbc2014-04-19 03:48:30 +00006065Decl *ASTReader::GetExistingDecl(DeclID ID) {
6066 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 switch ((PredefinedDeclIDs)ID) {
6068 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006069 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006070
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6072 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 case PREDEF_DECL_OBJC_ID_ID:
6075 return Context.getObjCIdDecl();
6076
6077 case PREDEF_DECL_OBJC_SEL_ID:
6078 return Context.getObjCSelDecl();
6079
6080 case PREDEF_DECL_OBJC_CLASS_ID:
6081 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006082
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6084 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 case PREDEF_DECL_INT_128_ID:
6087 return Context.getInt128Decl();
6088
6089 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6090 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6093 return Context.getObjCInstanceTypeDecl();
6094
6095 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6096 return Context.getBuiltinVaListDecl();
6097 }
6098 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006099
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6101
6102 if (Index >= DeclsLoaded.size()) {
6103 assert(0 && "declaration ID out-of-range for AST file");
6104 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006105 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006107
6108 return DeclsLoaded[Index];
6109}
6110
6111Decl *ASTReader::GetDecl(DeclID ID) {
6112 if (ID < NUM_PREDEF_DECL_IDS)
6113 return GetExistingDecl(ID);
6114
6115 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6116
6117 if (Index >= DeclsLoaded.size()) {
6118 assert(0 && "declaration ID out-of-range for AST file");
6119 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006120 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006121 }
6122
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 if (!DeclsLoaded[Index]) {
6124 ReadDeclRecord(ID);
6125 if (DeserializationListener)
6126 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6127 }
6128
6129 return DeclsLoaded[Index];
6130}
6131
6132DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6133 DeclID GlobalID) {
6134 if (GlobalID < NUM_PREDEF_DECL_IDS)
6135 return GlobalID;
6136
6137 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6138 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6139 ModuleFile *Owner = I->second;
6140
6141 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6142 = M.GlobalToLocalDeclIDs.find(Owner);
6143 if (Pos == M.GlobalToLocalDeclIDs.end())
6144 return 0;
6145
6146 return GlobalID - Owner->BaseDeclID + Pos->second;
6147}
6148
6149serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6150 const RecordData &Record,
6151 unsigned &Idx) {
6152 if (Idx >= Record.size()) {
6153 Error("Corrupted AST file");
6154 return 0;
6155 }
6156
6157 return getGlobalDeclID(F, Record[Idx++]);
6158}
6159
6160/// \brief Resolve the offset of a statement into a statement.
6161///
6162/// This operation will read a new statement from the external
6163/// source each time it is called, and is meant to be used via a
6164/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6165Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6166 // Switch case IDs are per Decl.
6167 ClearSwitchCaseIDs();
6168
6169 // Offset here is a global offset across the entire chain.
6170 RecordLocation Loc = getLocalBitOffset(Offset);
6171 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6172 return ReadStmtFromStream(*Loc.F);
6173}
6174
6175namespace {
6176 class FindExternalLexicalDeclsVisitor {
6177 ASTReader &Reader;
6178 const DeclContext *DC;
6179 bool (*isKindWeWant)(Decl::Kind);
6180
6181 SmallVectorImpl<Decl*> &Decls;
6182 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6183
6184 public:
6185 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6186 bool (*isKindWeWant)(Decl::Kind),
6187 SmallVectorImpl<Decl*> &Decls)
6188 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6189 {
6190 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6191 PredefsVisited[I] = false;
6192 }
6193
6194 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6195 if (Preorder)
6196 return false;
6197
6198 FindExternalLexicalDeclsVisitor *This
6199 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6200
6201 ModuleFile::DeclContextInfosMap::iterator Info
6202 = M.DeclContextInfos.find(This->DC);
6203 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6204 return false;
6205
6206 // Load all of the declaration IDs
6207 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6208 *IDE = ID + Info->second.NumLexicalDecls;
6209 ID != IDE; ++ID) {
6210 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6211 continue;
6212
6213 // Don't add predefined declarations to the lexical context more
6214 // than once.
6215 if (ID->second < NUM_PREDEF_DECL_IDS) {
6216 if (This->PredefsVisited[ID->second])
6217 continue;
6218
6219 This->PredefsVisited[ID->second] = true;
6220 }
6221
6222 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6223 if (!This->DC->isDeclInLexicalTraversal(D))
6224 This->Decls.push_back(D);
6225 }
6226 }
6227
6228 return false;
6229 }
6230 };
6231}
6232
6233ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6234 bool (*isKindWeWant)(Decl::Kind),
6235 SmallVectorImpl<Decl*> &Decls) {
6236 // There might be lexical decls in multiple modules, for the TU at
6237 // least. Walk all of the modules in the order they were loaded.
6238 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6239 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6240 ++NumLexicalDeclContextsRead;
6241 return ELR_Success;
6242}
6243
6244namespace {
6245
6246class DeclIDComp {
6247 ASTReader &Reader;
6248 ModuleFile &Mod;
6249
6250public:
6251 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6252
6253 bool operator()(LocalDeclID L, LocalDeclID R) const {
6254 SourceLocation LHS = getLocation(L);
6255 SourceLocation RHS = getLocation(R);
6256 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6257 }
6258
6259 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6260 SourceLocation RHS = getLocation(R);
6261 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6262 }
6263
6264 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6265 SourceLocation LHS = getLocation(L);
6266 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6267 }
6268
6269 SourceLocation getLocation(LocalDeclID ID) const {
6270 return Reader.getSourceManager().getFileLoc(
6271 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6272 }
6273};
6274
6275}
6276
6277void ASTReader::FindFileRegionDecls(FileID File,
6278 unsigned Offset, unsigned Length,
6279 SmallVectorImpl<Decl *> &Decls) {
6280 SourceManager &SM = getSourceManager();
6281
6282 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6283 if (I == FileDeclIDs.end())
6284 return;
6285
6286 FileDeclsInfo &DInfo = I->second;
6287 if (DInfo.Decls.empty())
6288 return;
6289
6290 SourceLocation
6291 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6292 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6293
6294 DeclIDComp DIDComp(*this, *DInfo.Mod);
6295 ArrayRef<serialization::LocalDeclID>::iterator
6296 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6297 BeginLoc, DIDComp);
6298 if (BeginIt != DInfo.Decls.begin())
6299 --BeginIt;
6300
6301 // If we are pointing at a top-level decl inside an objc container, we need
6302 // to backtrack until we find it otherwise we will fail to report that the
6303 // region overlaps with an objc container.
6304 while (BeginIt != DInfo.Decls.begin() &&
6305 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6306 ->isTopLevelDeclInObjCContainer())
6307 --BeginIt;
6308
6309 ArrayRef<serialization::LocalDeclID>::iterator
6310 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6311 EndLoc, DIDComp);
6312 if (EndIt != DInfo.Decls.end())
6313 ++EndIt;
6314
6315 for (ArrayRef<serialization::LocalDeclID>::iterator
6316 DIt = BeginIt; DIt != EndIt; ++DIt)
6317 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6318}
6319
6320namespace {
6321 /// \brief ModuleFile visitor used to perform name lookup into a
6322 /// declaration context.
6323 class DeclContextNameLookupVisitor {
6324 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006325 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 DeclarationName Name;
6327 SmallVectorImpl<NamedDecl *> &Decls;
6328
6329 public:
6330 DeclContextNameLookupVisitor(ASTReader &Reader,
6331 SmallVectorImpl<const DeclContext *> &Contexts,
6332 DeclarationName Name,
6333 SmallVectorImpl<NamedDecl *> &Decls)
6334 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6335
6336 static bool visit(ModuleFile &M, void *UserData) {
6337 DeclContextNameLookupVisitor *This
6338 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6339
6340 // Check whether we have any visible declaration information for
6341 // this context in this module.
6342 ModuleFile::DeclContextInfosMap::iterator Info;
6343 bool FoundInfo = false;
6344 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6345 Info = M.DeclContextInfos.find(This->Contexts[I]);
6346 if (Info != M.DeclContextInfos.end() &&
6347 Info->second.NameLookupTableData) {
6348 FoundInfo = true;
6349 break;
6350 }
6351 }
6352
6353 if (!FoundInfo)
6354 return false;
6355
6356 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006357 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 Info->second.NameLookupTableData;
6359 ASTDeclContextNameLookupTable::iterator Pos
6360 = LookupTable->find(This->Name);
6361 if (Pos == LookupTable->end())
6362 return false;
6363
6364 bool FoundAnything = false;
6365 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6366 for (; Data.first != Data.second; ++Data.first) {
6367 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6368 if (!ND)
6369 continue;
6370
6371 if (ND->getDeclName() != This->Name) {
6372 // A name might be null because the decl's redeclarable part is
6373 // currently read before reading its name. The lookup is triggered by
6374 // building that decl (likely indirectly), and so it is later in the
6375 // sense of "already existing" and can be ignored here.
6376 continue;
6377 }
6378
6379 // Record this declaration.
6380 FoundAnything = true;
6381 This->Decls.push_back(ND);
6382 }
6383
6384 return FoundAnything;
6385 }
6386 };
6387}
6388
Douglas Gregor9f782892013-01-21 15:25:38 +00006389/// \brief Retrieve the "definitive" module file for the definition of the
6390/// given declaration context, if there is one.
6391///
6392/// The "definitive" module file is the only place where we need to look to
6393/// find information about the declarations within the given declaration
6394/// context. For example, C++ and Objective-C classes, C structs/unions, and
6395/// Objective-C protocols, categories, and extensions are all defined in a
6396/// single place in the source code, so they have definitive module files
6397/// associated with them. C++ namespaces, on the other hand, can have
6398/// definitions in multiple different module files.
6399///
6400/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6401/// NDEBUG checking.
6402static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6403 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006404 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6405 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006406
Craig Toppera13603a2014-05-22 05:54:18 +00006407 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006408}
6409
Richard Smith9ce12e32013-02-07 03:30:24 +00006410bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006411ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6412 DeclarationName Name) {
6413 assert(DC->hasExternalVisibleStorage() &&
6414 "DeclContext has no visible decls in storage");
6415 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006416 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006417
6418 SmallVector<NamedDecl *, 64> Decls;
6419
6420 // Compute the declaration contexts we need to look into. Multiple such
6421 // declaration contexts occur when two declaration contexts from disjoint
6422 // modules get merged, e.g., when two namespaces with the same name are
6423 // independently defined in separate modules.
6424 SmallVector<const DeclContext *, 2> Contexts;
6425 Contexts.push_back(DC);
6426
6427 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006428 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 if (Merged != MergedDecls.end()) {
6430 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6431 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6432 }
6433 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006434 if (isa<CXXRecordDecl>(DC)) {
6435 auto Merged = MergedLookups.find(DC);
6436 if (Merged != MergedLookups.end())
6437 Contexts.insert(Contexts.end(), Merged->second.begin(),
6438 Merged->second.end());
6439 }
6440
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006442
6443 // If we can definitively determine which module file to look into,
6444 // only look there. Otherwise, look in all module files.
6445 ModuleFile *Definitive;
6446 if (Contexts.size() == 1 &&
6447 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6448 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6449 } else {
6450 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6451 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 ++NumVisibleDeclContextsRead;
6453 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006454 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006455}
6456
6457namespace {
6458 /// \brief ModuleFile visitor used to retrieve all visible names in a
6459 /// declaration context.
6460 class DeclContextAllNamesVisitor {
6461 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006462 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006463 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006464 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006465
6466 public:
6467 DeclContextAllNamesVisitor(ASTReader &Reader,
6468 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006469 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006470 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006471
6472 static bool visit(ModuleFile &M, void *UserData) {
6473 DeclContextAllNamesVisitor *This
6474 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6475
6476 // Check whether we have any visible declaration information for
6477 // this context in this module.
6478 ModuleFile::DeclContextInfosMap::iterator Info;
6479 bool FoundInfo = false;
6480 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6481 Info = M.DeclContextInfos.find(This->Contexts[I]);
6482 if (Info != M.DeclContextInfos.end() &&
6483 Info->second.NameLookupTableData) {
6484 FoundInfo = true;
6485 break;
6486 }
6487 }
6488
6489 if (!FoundInfo)
6490 return false;
6491
Richard Smith52e3fba2014-03-11 07:17:35 +00006492 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 Info->second.NameLookupTableData;
6494 bool FoundAnything = false;
6495 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006496 I = LookupTable->data_begin(), E = LookupTable->data_end();
6497 I != E;
6498 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 ASTDeclContextNameLookupTrait::data_type Data = *I;
6500 for (; Data.first != Data.second; ++Data.first) {
6501 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6502 *Data.first);
6503 if (!ND)
6504 continue;
6505
6506 // Record this declaration.
6507 FoundAnything = true;
6508 This->Decls[ND->getDeclName()].push_back(ND);
6509 }
6510 }
6511
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006512 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 }
6514 };
6515}
6516
6517void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6518 if (!DC->hasExternalVisibleStorage())
6519 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006520 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006521
6522 // Compute the declaration contexts we need to look into. Multiple such
6523 // declaration contexts occur when two declaration contexts from disjoint
6524 // modules get merged, e.g., when two namespaces with the same name are
6525 // independently defined in separate modules.
6526 SmallVector<const DeclContext *, 2> Contexts;
6527 Contexts.push_back(DC);
6528
6529 if (DC->isNamespace()) {
6530 MergedDeclsMap::iterator Merged
6531 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6532 if (Merged != MergedDecls.end()) {
6533 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6534 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6535 }
6536 }
6537
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006538 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6539 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6541 ++NumVisibleDeclContextsRead;
6542
Craig Topper79be4cd2013-07-05 04:33:53 +00006543 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6545 }
6546 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6547}
6548
6549/// \brief Under non-PCH compilation the consumer receives the objc methods
6550/// before receiving the implementation, and codegen depends on this.
6551/// We simulate this by deserializing and passing to consumer the methods of the
6552/// implementation before passing the deserialized implementation decl.
6553static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6554 ASTConsumer *Consumer) {
6555 assert(ImplD && Consumer);
6556
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006557 for (auto *I : ImplD->methods())
6558 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006559
6560 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6561}
6562
6563void ASTReader::PassInterestingDeclsToConsumer() {
6564 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006565
6566 if (PassingDeclsToConsumer)
6567 return;
6568
6569 // Guard variable to avoid recursively redoing the process of passing
6570 // decls to consumer.
6571 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6572 true);
6573
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 while (!InterestingDecls.empty()) {
6575 Decl *D = InterestingDecls.front();
6576 InterestingDecls.pop_front();
6577
6578 PassInterestingDeclToConsumer(D);
6579 }
6580}
6581
6582void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6583 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6584 PassObjCImplDeclToConsumer(ImplD, Consumer);
6585 else
6586 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6587}
6588
6589void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6590 this->Consumer = Consumer;
6591
6592 if (!Consumer)
6593 return;
6594
Ben Langmuir332aafe2014-01-31 01:06:56 +00006595 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 // Force deserialization of this decl, which will cause it to be queued for
6597 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006598 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006599 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006600 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006601
6602 PassInterestingDeclsToConsumer();
6603}
6604
6605void ASTReader::PrintStats() {
6606 std::fprintf(stderr, "*** AST File Statistics:\n");
6607
6608 unsigned NumTypesLoaded
6609 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6610 QualType());
6611 unsigned NumDeclsLoaded
6612 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006613 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 unsigned NumIdentifiersLoaded
6615 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6616 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006617 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 unsigned NumMacrosLoaded
6619 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6620 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006621 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 unsigned NumSelectorsLoaded
6623 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6624 SelectorsLoaded.end(),
6625 Selector());
6626
6627 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6628 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6629 NumSLocEntriesRead, TotalNumSLocEntries,
6630 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6631 if (!TypesLoaded.empty())
6632 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6633 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6634 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6635 if (!DeclsLoaded.empty())
6636 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6637 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6638 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6639 if (!IdentifiersLoaded.empty())
6640 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6641 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6642 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6643 if (!MacrosLoaded.empty())
6644 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6645 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6646 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6647 if (!SelectorsLoaded.empty())
6648 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6649 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6650 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6651 if (TotalNumStatements)
6652 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6653 NumStatementsRead, TotalNumStatements,
6654 ((float)NumStatementsRead/TotalNumStatements * 100));
6655 if (TotalNumMacros)
6656 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6657 NumMacrosRead, TotalNumMacros,
6658 ((float)NumMacrosRead/TotalNumMacros * 100));
6659 if (TotalLexicalDeclContexts)
6660 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6661 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6662 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6663 * 100));
6664 if (TotalVisibleDeclContexts)
6665 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6666 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6667 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6668 * 100));
6669 if (TotalNumMethodPoolEntries) {
6670 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6671 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6672 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6673 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006675 if (NumMethodPoolLookups) {
6676 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6677 NumMethodPoolHits, NumMethodPoolLookups,
6678 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6679 }
6680 if (NumMethodPoolTableLookups) {
6681 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6682 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6683 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6684 * 100.0));
6685 }
6686
Douglas Gregor00a50f72013-01-25 00:38:33 +00006687 if (NumIdentifierLookupHits) {
6688 std::fprintf(stderr,
6689 " %u / %u identifier table lookups succeeded (%f%%)\n",
6690 NumIdentifierLookupHits, NumIdentifierLookups,
6691 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6692 }
6693
Douglas Gregore060e572013-01-25 01:03:03 +00006694 if (GlobalIndex) {
6695 std::fprintf(stderr, "\n");
6696 GlobalIndex->printStats();
6697 }
6698
Guy Benyei11169dd2012-12-18 14:30:41 +00006699 std::fprintf(stderr, "\n");
6700 dump();
6701 std::fprintf(stderr, "\n");
6702}
6703
6704template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6705static void
6706dumpModuleIDMap(StringRef Name,
6707 const ContinuousRangeMap<Key, ModuleFile *,
6708 InitialCapacity> &Map) {
6709 if (Map.begin() == Map.end())
6710 return;
6711
6712 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6713 llvm::errs() << Name << ":\n";
6714 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6715 I != IEnd; ++I) {
6716 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6717 << "\n";
6718 }
6719}
6720
6721void ASTReader::dump() {
6722 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6723 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6724 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6725 dumpModuleIDMap("Global type map", GlobalTypeMap);
6726 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6727 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6728 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6729 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6730 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6731 dumpModuleIDMap("Global preprocessed entity map",
6732 GlobalPreprocessedEntityMap);
6733
6734 llvm::errs() << "\n*** PCH/Modules Loaded:";
6735 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6736 MEnd = ModuleMgr.end();
6737 M != MEnd; ++M)
6738 (*M)->dump();
6739}
6740
6741/// Return the amount of memory used by memory buffers, breaking down
6742/// by heap-backed versus mmap'ed memory.
6743void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6744 for (ModuleConstIterator I = ModuleMgr.begin(),
6745 E = ModuleMgr.end(); I != E; ++I) {
6746 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6747 size_t bytes = buf->getBufferSize();
6748 switch (buf->getBufferKind()) {
6749 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6750 sizes.malloc_bytes += bytes;
6751 break;
6752 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6753 sizes.mmap_bytes += bytes;
6754 break;
6755 }
6756 }
6757 }
6758}
6759
6760void ASTReader::InitializeSema(Sema &S) {
6761 SemaObj = &S;
6762 S.addExternalSource(this);
6763
6764 // Makes sure any declarations that were deserialized "too early"
6765 // still get added to the identifier's declaration chains.
6766 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006767 pushExternalDeclIntoScope(PreloadedDecls[I],
6768 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006769 }
6770 PreloadedDecls.clear();
6771
Richard Smith3d8e97e2013-10-18 06:54:39 +00006772 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 if (!FPPragmaOptions.empty()) {
6774 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6775 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6776 }
6777
Richard Smith3d8e97e2013-10-18 06:54:39 +00006778 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 if (!OpenCLExtensions.empty()) {
6780 unsigned I = 0;
6781#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6782#include "clang/Basic/OpenCLExtensions.def"
6783
6784 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6785 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006786
6787 UpdateSema();
6788}
6789
6790void ASTReader::UpdateSema() {
6791 assert(SemaObj && "no Sema to update");
6792
6793 // Load the offsets of the declarations that Sema references.
6794 // They will be lazily deserialized when needed.
6795 if (!SemaDeclRefs.empty()) {
6796 assert(SemaDeclRefs.size() % 2 == 0);
6797 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6798 if (!SemaObj->StdNamespace)
6799 SemaObj->StdNamespace = SemaDeclRefs[I];
6800 if (!SemaObj->StdBadAlloc)
6801 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6802 }
6803 SemaDeclRefs.clear();
6804 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006805}
6806
6807IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6808 // Note that we are loading an identifier.
6809 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006810 StringRef Name(NameStart, NameEnd - NameStart);
6811
6812 // If there is a global index, look there first to determine which modules
6813 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006814 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006815 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006816 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006817 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6818 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006819 }
6820 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006821 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006822 NumIdentifierLookups,
6823 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006824 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 IdentifierInfo *II = Visitor.getIdentifierInfo();
6826 markIdentifierUpToDate(II);
6827 return II;
6828}
6829
6830namespace clang {
6831 /// \brief An identifier-lookup iterator that enumerates all of the
6832 /// identifiers stored within a set of AST files.
6833 class ASTIdentifierIterator : public IdentifierIterator {
6834 /// \brief The AST reader whose identifiers are being enumerated.
6835 const ASTReader &Reader;
6836
6837 /// \brief The current index into the chain of AST files stored in
6838 /// the AST reader.
6839 unsigned Index;
6840
6841 /// \brief The current position within the identifier lookup table
6842 /// of the current AST file.
6843 ASTIdentifierLookupTable::key_iterator Current;
6844
6845 /// \brief The end position within the identifier lookup table of
6846 /// the current AST file.
6847 ASTIdentifierLookupTable::key_iterator End;
6848
6849 public:
6850 explicit ASTIdentifierIterator(const ASTReader &Reader);
6851
Craig Topper3e89dfe2014-03-13 02:13:41 +00006852 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 };
6854}
6855
6856ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6857 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6858 ASTIdentifierLookupTable *IdTable
6859 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6860 Current = IdTable->key_begin();
6861 End = IdTable->key_end();
6862}
6863
6864StringRef ASTIdentifierIterator::Next() {
6865 while (Current == End) {
6866 // If we have exhausted all of our AST files, we're done.
6867 if (Index == 0)
6868 return StringRef();
6869
6870 --Index;
6871 ASTIdentifierLookupTable *IdTable
6872 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6873 IdentifierLookupTable;
6874 Current = IdTable->key_begin();
6875 End = IdTable->key_end();
6876 }
6877
6878 // We have any identifiers remaining in the current AST file; return
6879 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006880 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006882 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006883}
6884
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006885IdentifierIterator *ASTReader::getIdentifiers() {
6886 if (!loadGlobalIndex())
6887 return GlobalIndex->createIdentifierIterator();
6888
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 return new ASTIdentifierIterator(*this);
6890}
6891
6892namespace clang { namespace serialization {
6893 class ReadMethodPoolVisitor {
6894 ASTReader &Reader;
6895 Selector Sel;
6896 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006897 unsigned InstanceBits;
6898 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006899 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6900 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006901
6902 public:
6903 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6904 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006905 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6906 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006907
6908 static bool visit(ModuleFile &M, void *UserData) {
6909 ReadMethodPoolVisitor *This
6910 = static_cast<ReadMethodPoolVisitor *>(UserData);
6911
6912 if (!M.SelectorLookupTable)
6913 return false;
6914
6915 // If we've already searched this module file, skip it now.
6916 if (M.Generation <= This->PriorGeneration)
6917 return true;
6918
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006919 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 ASTSelectorLookupTable *PoolTable
6921 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6922 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6923 if (Pos == PoolTable->end())
6924 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006925
6926 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 ++This->Reader.NumSelectorsRead;
6928 // FIXME: Not quite happy with the statistics here. We probably should
6929 // disable this tracking when called via LoadSelector.
6930 // Also, should entries without methods count as misses?
6931 ++This->Reader.NumMethodPoolEntriesRead;
6932 ASTSelectorLookupTrait::data_type Data = *Pos;
6933 if (This->Reader.DeserializationListener)
6934 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6935 This->Sel);
6936
6937 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6938 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006939 This->InstanceBits = Data.InstanceBits;
6940 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 return true;
6942 }
6943
6944 /// \brief Retrieve the instance methods found by this visitor.
6945 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6946 return InstanceMethods;
6947 }
6948
6949 /// \brief Retrieve the instance methods found by this visitor.
6950 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6951 return FactoryMethods;
6952 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006953
6954 unsigned getInstanceBits() const { return InstanceBits; }
6955 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 };
6957} } // end namespace clang::serialization
6958
6959/// \brief Add the given set of methods to the method list.
6960static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6961 ObjCMethodList &List) {
6962 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6963 S.addMethodToGlobalList(&List, Methods[I]);
6964 }
6965}
6966
6967void ASTReader::ReadMethodPool(Selector Sel) {
6968 // Get the selector generation and update it to the current generation.
6969 unsigned &Generation = SelectorGeneration[Sel];
6970 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006971 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006972
6973 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006974 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6976 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6977
6978 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006979 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006981
6982 ++NumMethodPoolHits;
6983
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 if (!getSema())
6985 return;
6986
6987 Sema &S = *getSema();
6988 Sema::GlobalMethodPool::iterator Pos
6989 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6990
6991 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6992 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006993 Pos->second.first.setBits(Visitor.getInstanceBits());
6994 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006995}
6996
6997void ASTReader::ReadKnownNamespaces(
6998 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6999 Namespaces.clear();
7000
7001 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7002 if (NamespaceDecl *Namespace
7003 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7004 Namespaces.push_back(Namespace);
7005 }
7006}
7007
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007008void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007009 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007010 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7011 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007012 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007013 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007014 Undefined.insert(std::make_pair(D, Loc));
7015 }
7016}
Nick Lewycky8334af82013-01-26 00:35:08 +00007017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018void ASTReader::ReadTentativeDefinitions(
7019 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7020 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7021 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7022 if (Var)
7023 TentativeDefs.push_back(Var);
7024 }
7025 TentativeDefinitions.clear();
7026}
7027
7028void ASTReader::ReadUnusedFileScopedDecls(
7029 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7030 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7031 DeclaratorDecl *D
7032 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7033 if (D)
7034 Decls.push_back(D);
7035 }
7036 UnusedFileScopedDecls.clear();
7037}
7038
7039void ASTReader::ReadDelegatingConstructors(
7040 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7041 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7042 CXXConstructorDecl *D
7043 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7044 if (D)
7045 Decls.push_back(D);
7046 }
7047 DelegatingCtorDecls.clear();
7048}
7049
7050void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7051 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7052 TypedefNameDecl *D
7053 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7054 if (D)
7055 Decls.push_back(D);
7056 }
7057 ExtVectorDecls.clear();
7058}
7059
7060void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7061 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7062 CXXRecordDecl *D
7063 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7064 if (D)
7065 Decls.push_back(D);
7066 }
7067 DynamicClasses.clear();
7068}
7069
7070void
Richard Smith78165b52013-01-10 23:43:47 +00007071ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7072 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7073 NamedDecl *D
7074 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007075 if (D)
7076 Decls.push_back(D);
7077 }
Richard Smith78165b52013-01-10 23:43:47 +00007078 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007079}
7080
7081void ASTReader::ReadReferencedSelectors(
7082 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7083 if (ReferencedSelectorsData.empty())
7084 return;
7085
7086 // If there are @selector references added them to its pool. This is for
7087 // implementation of -Wselector.
7088 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7089 unsigned I = 0;
7090 while (I < DataSize) {
7091 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7092 SourceLocation SelLoc
7093 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7094 Sels.push_back(std::make_pair(Sel, SelLoc));
7095 }
7096 ReferencedSelectorsData.clear();
7097}
7098
7099void ASTReader::ReadWeakUndeclaredIdentifiers(
7100 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7101 if (WeakUndeclaredIdentifiers.empty())
7102 return;
7103
7104 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7105 IdentifierInfo *WeakId
7106 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7107 IdentifierInfo *AliasId
7108 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7109 SourceLocation Loc
7110 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7111 bool Used = WeakUndeclaredIdentifiers[I++];
7112 WeakInfo WI(AliasId, Loc);
7113 WI.setUsed(Used);
7114 WeakIDs.push_back(std::make_pair(WeakId, WI));
7115 }
7116 WeakUndeclaredIdentifiers.clear();
7117}
7118
7119void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7120 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7121 ExternalVTableUse VT;
7122 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7123 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7124 VT.DefinitionRequired = VTableUses[Idx++];
7125 VTables.push_back(VT);
7126 }
7127
7128 VTableUses.clear();
7129}
7130
7131void ASTReader::ReadPendingInstantiations(
7132 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7133 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7134 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7135 SourceLocation Loc
7136 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7137
7138 Pending.push_back(std::make_pair(D, Loc));
7139 }
7140 PendingInstantiations.clear();
7141}
7142
Richard Smithe40f2ba2013-08-07 21:41:30 +00007143void ASTReader::ReadLateParsedTemplates(
7144 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7145 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7146 /* In loop */) {
7147 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7148
7149 LateParsedTemplate *LT = new LateParsedTemplate;
7150 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7151
7152 ModuleFile *F = getOwningModuleFile(LT->D);
7153 assert(F && "No module");
7154
7155 unsigned TokN = LateParsedTemplates[Idx++];
7156 LT->Toks.reserve(TokN);
7157 for (unsigned T = 0; T < TokN; ++T)
7158 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7159
7160 LPTMap[FD] = LT;
7161 }
7162
7163 LateParsedTemplates.clear();
7164}
7165
Guy Benyei11169dd2012-12-18 14:30:41 +00007166void ASTReader::LoadSelector(Selector Sel) {
7167 // It would be complicated to avoid reading the methods anyway. So don't.
7168 ReadMethodPool(Sel);
7169}
7170
7171void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7172 assert(ID && "Non-zero identifier ID required");
7173 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7174 IdentifiersLoaded[ID - 1] = II;
7175 if (DeserializationListener)
7176 DeserializationListener->IdentifierRead(ID, II);
7177}
7178
7179/// \brief Set the globally-visible declarations associated with the given
7180/// identifier.
7181///
7182/// If the AST reader is currently in a state where the given declaration IDs
7183/// cannot safely be resolved, they are queued until it is safe to resolve
7184/// them.
7185///
7186/// \param II an IdentifierInfo that refers to one or more globally-visible
7187/// declarations.
7188///
7189/// \param DeclIDs the set of declaration IDs with the name @p II that are
7190/// visible at global scope.
7191///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007192/// \param Decls if non-null, this vector will be populated with the set of
7193/// deserialized declarations. These declarations will not be pushed into
7194/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007195void
7196ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7197 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007198 SmallVectorImpl<Decl *> *Decls) {
7199 if (NumCurrentElementsDeserializing && !Decls) {
7200 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 return;
7202 }
7203
7204 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7205 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7206 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007207 // If we're simply supposed to record the declarations, do so now.
7208 if (Decls) {
7209 Decls->push_back(D);
7210 continue;
7211 }
7212
Guy Benyei11169dd2012-12-18 14:30:41 +00007213 // Introduce this declaration into the translation-unit scope
7214 // and add it to the declaration chain for this identifier, so
7215 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007216 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 } else {
7218 // Queue this declaration so that it will be added to the
7219 // translation unit scope and identifier's declaration chain
7220 // once a Sema object is known.
7221 PreloadedDecls.push_back(D);
7222 }
7223 }
7224}
7225
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007226IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007228 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007229
7230 if (IdentifiersLoaded.empty()) {
7231 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007232 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 }
7234
7235 ID -= 1;
7236 if (!IdentifiersLoaded[ID]) {
7237 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7238 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7239 ModuleFile *M = I->second;
7240 unsigned Index = ID - M->BaseIdentifierID;
7241 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7242
7243 // All of the strings in the AST file are preceded by a 16-bit length.
7244 // Extract that 16-bit length to avoid having to execute strlen().
7245 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7246 // unsigned integers. This is important to avoid integer overflow when
7247 // we cast them to 'unsigned'.
7248 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7249 unsigned StrLen = (((unsigned) StrLenPtr[0])
7250 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007251 IdentifiersLoaded[ID]
7252 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 if (DeserializationListener)
7254 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7255 }
7256
7257 return IdentifiersLoaded[ID];
7258}
7259
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007260IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7261 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007262}
7263
7264IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7265 if (LocalID < NUM_PREDEF_IDENT_IDS)
7266 return LocalID;
7267
7268 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7269 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7270 assert(I != M.IdentifierRemap.end()
7271 && "Invalid index into identifier index remap");
7272
7273 return LocalID + I->second;
7274}
7275
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007276MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007278 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007279
7280 if (MacrosLoaded.empty()) {
7281 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007282 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 }
7284
7285 ID -= NUM_PREDEF_MACRO_IDS;
7286 if (!MacrosLoaded[ID]) {
7287 GlobalMacroMapType::iterator I
7288 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7289 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7290 ModuleFile *M = I->second;
7291 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007292 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7293
7294 if (DeserializationListener)
7295 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7296 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 }
7298
7299 return MacrosLoaded[ID];
7300}
7301
7302MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7303 if (LocalID < NUM_PREDEF_MACRO_IDS)
7304 return LocalID;
7305
7306 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7307 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7308 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7309
7310 return LocalID + I->second;
7311}
7312
7313serialization::SubmoduleID
7314ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7315 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7316 return LocalID;
7317
7318 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7319 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7320 assert(I != M.SubmoduleRemap.end()
7321 && "Invalid index into submodule index remap");
7322
7323 return LocalID + I->second;
7324}
7325
7326Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7327 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7328 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007329 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007330 }
7331
7332 if (GlobalID > SubmodulesLoaded.size()) {
7333 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007334 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 }
7336
7337 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7338}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007339
7340Module *ASTReader::getModule(unsigned ID) {
7341 return getSubmodule(ID);
7342}
7343
Guy Benyei11169dd2012-12-18 14:30:41 +00007344Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7345 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7346}
7347
7348Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7349 if (ID == 0)
7350 return Selector();
7351
7352 if (ID > SelectorsLoaded.size()) {
7353 Error("selector ID out of range in AST file");
7354 return Selector();
7355 }
7356
Craig Toppera13603a2014-05-22 05:54:18 +00007357 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007358 // Load this selector from the selector table.
7359 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7360 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7361 ModuleFile &M = *I->second;
7362 ASTSelectorLookupTrait Trait(*this, M);
7363 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7364 SelectorsLoaded[ID - 1] =
7365 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7366 if (DeserializationListener)
7367 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7368 }
7369
7370 return SelectorsLoaded[ID - 1];
7371}
7372
7373Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7374 return DecodeSelector(ID);
7375}
7376
7377uint32_t ASTReader::GetNumExternalSelectors() {
7378 // ID 0 (the null selector) is considered an external selector.
7379 return getTotalNumSelectors() + 1;
7380}
7381
7382serialization::SelectorID
7383ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7384 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7385 return LocalID;
7386
7387 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7388 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7389 assert(I != M.SelectorRemap.end()
7390 && "Invalid index into selector index remap");
7391
7392 return LocalID + I->second;
7393}
7394
7395DeclarationName
7396ASTReader::ReadDeclarationName(ModuleFile &F,
7397 const RecordData &Record, unsigned &Idx) {
7398 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7399 switch (Kind) {
7400 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007401 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007402
7403 case DeclarationName::ObjCZeroArgSelector:
7404 case DeclarationName::ObjCOneArgSelector:
7405 case DeclarationName::ObjCMultiArgSelector:
7406 return DeclarationName(ReadSelector(F, Record, Idx));
7407
7408 case DeclarationName::CXXConstructorName:
7409 return Context.DeclarationNames.getCXXConstructorName(
7410 Context.getCanonicalType(readType(F, Record, Idx)));
7411
7412 case DeclarationName::CXXDestructorName:
7413 return Context.DeclarationNames.getCXXDestructorName(
7414 Context.getCanonicalType(readType(F, Record, Idx)));
7415
7416 case DeclarationName::CXXConversionFunctionName:
7417 return Context.DeclarationNames.getCXXConversionFunctionName(
7418 Context.getCanonicalType(readType(F, Record, Idx)));
7419
7420 case DeclarationName::CXXOperatorName:
7421 return Context.DeclarationNames.getCXXOperatorName(
7422 (OverloadedOperatorKind)Record[Idx++]);
7423
7424 case DeclarationName::CXXLiteralOperatorName:
7425 return Context.DeclarationNames.getCXXLiteralOperatorName(
7426 GetIdentifierInfo(F, Record, Idx));
7427
7428 case DeclarationName::CXXUsingDirective:
7429 return DeclarationName::getUsingDirectiveName();
7430 }
7431
7432 llvm_unreachable("Invalid NameKind!");
7433}
7434
7435void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7436 DeclarationNameLoc &DNLoc,
7437 DeclarationName Name,
7438 const RecordData &Record, unsigned &Idx) {
7439 switch (Name.getNameKind()) {
7440 case DeclarationName::CXXConstructorName:
7441 case DeclarationName::CXXDestructorName:
7442 case DeclarationName::CXXConversionFunctionName:
7443 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7444 break;
7445
7446 case DeclarationName::CXXOperatorName:
7447 DNLoc.CXXOperatorName.BeginOpNameLoc
7448 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7449 DNLoc.CXXOperatorName.EndOpNameLoc
7450 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7451 break;
7452
7453 case DeclarationName::CXXLiteralOperatorName:
7454 DNLoc.CXXLiteralOperatorName.OpNameLoc
7455 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7456 break;
7457
7458 case DeclarationName::Identifier:
7459 case DeclarationName::ObjCZeroArgSelector:
7460 case DeclarationName::ObjCOneArgSelector:
7461 case DeclarationName::ObjCMultiArgSelector:
7462 case DeclarationName::CXXUsingDirective:
7463 break;
7464 }
7465}
7466
7467void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7468 DeclarationNameInfo &NameInfo,
7469 const RecordData &Record, unsigned &Idx) {
7470 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7471 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7472 DeclarationNameLoc DNLoc;
7473 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7474 NameInfo.setInfo(DNLoc);
7475}
7476
7477void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7478 const RecordData &Record, unsigned &Idx) {
7479 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7480 unsigned NumTPLists = Record[Idx++];
7481 Info.NumTemplParamLists = NumTPLists;
7482 if (NumTPLists) {
7483 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7484 for (unsigned i=0; i != NumTPLists; ++i)
7485 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7486 }
7487}
7488
7489TemplateName
7490ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7491 unsigned &Idx) {
7492 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7493 switch (Kind) {
7494 case TemplateName::Template:
7495 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7496
7497 case TemplateName::OverloadedTemplate: {
7498 unsigned size = Record[Idx++];
7499 UnresolvedSet<8> Decls;
7500 while (size--)
7501 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7502
7503 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7504 }
7505
7506 case TemplateName::QualifiedTemplate: {
7507 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7508 bool hasTemplKeyword = Record[Idx++];
7509 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7510 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7511 }
7512
7513 case TemplateName::DependentTemplate: {
7514 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7515 if (Record[Idx++]) // isIdentifier
7516 return Context.getDependentTemplateName(NNS,
7517 GetIdentifierInfo(F, Record,
7518 Idx));
7519 return Context.getDependentTemplateName(NNS,
7520 (OverloadedOperatorKind)Record[Idx++]);
7521 }
7522
7523 case TemplateName::SubstTemplateTemplateParm: {
7524 TemplateTemplateParmDecl *param
7525 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7526 if (!param) return TemplateName();
7527 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7528 return Context.getSubstTemplateTemplateParm(param, replacement);
7529 }
7530
7531 case TemplateName::SubstTemplateTemplateParmPack: {
7532 TemplateTemplateParmDecl *Param
7533 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7534 if (!Param)
7535 return TemplateName();
7536
7537 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7538 if (ArgPack.getKind() != TemplateArgument::Pack)
7539 return TemplateName();
7540
7541 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7542 }
7543 }
7544
7545 llvm_unreachable("Unhandled template name kind!");
7546}
7547
7548TemplateArgument
7549ASTReader::ReadTemplateArgument(ModuleFile &F,
7550 const RecordData &Record, unsigned &Idx) {
7551 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7552 switch (Kind) {
7553 case TemplateArgument::Null:
7554 return TemplateArgument();
7555 case TemplateArgument::Type:
7556 return TemplateArgument(readType(F, Record, Idx));
7557 case TemplateArgument::Declaration: {
7558 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7559 bool ForReferenceParam = Record[Idx++];
7560 return TemplateArgument(D, ForReferenceParam);
7561 }
7562 case TemplateArgument::NullPtr:
7563 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7564 case TemplateArgument::Integral: {
7565 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7566 QualType T = readType(F, Record, Idx);
7567 return TemplateArgument(Context, Value, T);
7568 }
7569 case TemplateArgument::Template:
7570 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7571 case TemplateArgument::TemplateExpansion: {
7572 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007573 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007574 if (unsigned NumExpansions = Record[Idx++])
7575 NumTemplateExpansions = NumExpansions - 1;
7576 return TemplateArgument(Name, NumTemplateExpansions);
7577 }
7578 case TemplateArgument::Expression:
7579 return TemplateArgument(ReadExpr(F));
7580 case TemplateArgument::Pack: {
7581 unsigned NumArgs = Record[Idx++];
7582 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7583 for (unsigned I = 0; I != NumArgs; ++I)
7584 Args[I] = ReadTemplateArgument(F, Record, Idx);
7585 return TemplateArgument(Args, NumArgs);
7586 }
7587 }
7588
7589 llvm_unreachable("Unhandled template argument kind!");
7590}
7591
7592TemplateParameterList *
7593ASTReader::ReadTemplateParameterList(ModuleFile &F,
7594 const RecordData &Record, unsigned &Idx) {
7595 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7596 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7597 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7598
7599 unsigned NumParams = Record[Idx++];
7600 SmallVector<NamedDecl *, 16> Params;
7601 Params.reserve(NumParams);
7602 while (NumParams--)
7603 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7604
7605 TemplateParameterList* TemplateParams =
7606 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7607 Params.data(), Params.size(), RAngleLoc);
7608 return TemplateParams;
7609}
7610
7611void
7612ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007613ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007614 ModuleFile &F, const RecordData &Record,
7615 unsigned &Idx) {
7616 unsigned NumTemplateArgs = Record[Idx++];
7617 TemplArgs.reserve(NumTemplateArgs);
7618 while (NumTemplateArgs--)
7619 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7620}
7621
7622/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007623void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 const RecordData &Record, unsigned &Idx) {
7625 unsigned NumDecls = Record[Idx++];
7626 Set.reserve(Context, NumDecls);
7627 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007628 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007630 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007631 }
7632}
7633
7634CXXBaseSpecifier
7635ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7636 const RecordData &Record, unsigned &Idx) {
7637 bool isVirtual = static_cast<bool>(Record[Idx++]);
7638 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7639 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7640 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7641 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7642 SourceRange Range = ReadSourceRange(F, Record, Idx);
7643 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7644 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7645 EllipsisLoc);
7646 Result.setInheritConstructors(inheritConstructors);
7647 return Result;
7648}
7649
7650std::pair<CXXCtorInitializer **, unsigned>
7651ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7652 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007653 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007654 unsigned NumInitializers = Record[Idx++];
7655 if (NumInitializers) {
7656 CtorInitializers
7657 = new (Context) CXXCtorInitializer*[NumInitializers];
7658 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007659 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007661 FieldDecl *Member = nullptr;
7662 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007663
7664 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7665 switch (Type) {
7666 case CTOR_INITIALIZER_BASE:
7667 TInfo = GetTypeSourceInfo(F, Record, Idx);
7668 IsBaseVirtual = Record[Idx++];
7669 break;
7670
7671 case CTOR_INITIALIZER_DELEGATING:
7672 TInfo = GetTypeSourceInfo(F, Record, Idx);
7673 break;
7674
7675 case CTOR_INITIALIZER_MEMBER:
7676 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7677 break;
7678
7679 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7680 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7681 break;
7682 }
7683
7684 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7685 Expr *Init = ReadExpr(F);
7686 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7687 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7688 bool IsWritten = Record[Idx++];
7689 unsigned SourceOrderOrNumArrayIndices;
7690 SmallVector<VarDecl *, 8> Indices;
7691 if (IsWritten) {
7692 SourceOrderOrNumArrayIndices = Record[Idx++];
7693 } else {
7694 SourceOrderOrNumArrayIndices = Record[Idx++];
7695 Indices.reserve(SourceOrderOrNumArrayIndices);
7696 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7697 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7698 }
7699
7700 CXXCtorInitializer *BOMInit;
7701 if (Type == CTOR_INITIALIZER_BASE) {
7702 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7703 LParenLoc, Init, RParenLoc,
7704 MemberOrEllipsisLoc);
7705 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7706 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7707 Init, RParenLoc);
7708 } else if (IsWritten) {
7709 if (Member)
7710 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7711 LParenLoc, Init, RParenLoc);
7712 else
7713 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7714 MemberOrEllipsisLoc, LParenLoc,
7715 Init, RParenLoc);
7716 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007717 if (IndirectMember) {
7718 assert(Indices.empty() && "Indirect field improperly initialized");
7719 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7720 MemberOrEllipsisLoc, LParenLoc,
7721 Init, RParenLoc);
7722 } else {
7723 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7724 LParenLoc, Init, RParenLoc,
7725 Indices.data(), Indices.size());
7726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007727 }
7728
7729 if (IsWritten)
7730 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7731 CtorInitializers[i] = BOMInit;
7732 }
7733 }
7734
7735 return std::make_pair(CtorInitializers, NumInitializers);
7736}
7737
7738NestedNameSpecifier *
7739ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7740 const RecordData &Record, unsigned &Idx) {
7741 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007742 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 for (unsigned I = 0; I != N; ++I) {
7744 NestedNameSpecifier::SpecifierKind Kind
7745 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7746 switch (Kind) {
7747 case NestedNameSpecifier::Identifier: {
7748 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7749 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7750 break;
7751 }
7752
7753 case NestedNameSpecifier::Namespace: {
7754 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7755 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7756 break;
7757 }
7758
7759 case NestedNameSpecifier::NamespaceAlias: {
7760 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7761 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7762 break;
7763 }
7764
7765 case NestedNameSpecifier::TypeSpec:
7766 case NestedNameSpecifier::TypeSpecWithTemplate: {
7767 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7768 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007769 return nullptr;
7770
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 bool Template = Record[Idx++];
7772 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7773 break;
7774 }
7775
7776 case NestedNameSpecifier::Global: {
7777 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7778 // No associated value, and there can't be a prefix.
7779 break;
7780 }
7781 }
7782 Prev = NNS;
7783 }
7784 return NNS;
7785}
7786
7787NestedNameSpecifierLoc
7788ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7789 unsigned &Idx) {
7790 unsigned N = Record[Idx++];
7791 NestedNameSpecifierLocBuilder Builder;
7792 for (unsigned I = 0; I != N; ++I) {
7793 NestedNameSpecifier::SpecifierKind Kind
7794 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7795 switch (Kind) {
7796 case NestedNameSpecifier::Identifier: {
7797 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7798 SourceRange Range = ReadSourceRange(F, Record, Idx);
7799 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7800 break;
7801 }
7802
7803 case NestedNameSpecifier::Namespace: {
7804 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7805 SourceRange Range = ReadSourceRange(F, Record, Idx);
7806 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7807 break;
7808 }
7809
7810 case NestedNameSpecifier::NamespaceAlias: {
7811 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7812 SourceRange Range = ReadSourceRange(F, Record, Idx);
7813 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7814 break;
7815 }
7816
7817 case NestedNameSpecifier::TypeSpec:
7818 case NestedNameSpecifier::TypeSpecWithTemplate: {
7819 bool Template = Record[Idx++];
7820 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7821 if (!T)
7822 return NestedNameSpecifierLoc();
7823 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7824
7825 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7826 Builder.Extend(Context,
7827 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7828 T->getTypeLoc(), ColonColonLoc);
7829 break;
7830 }
7831
7832 case NestedNameSpecifier::Global: {
7833 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7834 Builder.MakeGlobal(Context, ColonColonLoc);
7835 break;
7836 }
7837 }
7838 }
7839
7840 return Builder.getWithLocInContext(Context);
7841}
7842
7843SourceRange
7844ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7845 unsigned &Idx) {
7846 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7847 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7848 return SourceRange(beg, end);
7849}
7850
7851/// \brief Read an integral value
7852llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7853 unsigned BitWidth = Record[Idx++];
7854 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7855 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7856 Idx += NumWords;
7857 return Result;
7858}
7859
7860/// \brief Read a signed integral value
7861llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7862 bool isUnsigned = Record[Idx++];
7863 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7864}
7865
7866/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007867llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7868 const llvm::fltSemantics &Sem,
7869 unsigned &Idx) {
7870 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007871}
7872
7873// \brief Read a string
7874std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7875 unsigned Len = Record[Idx++];
7876 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7877 Idx += Len;
7878 return Result;
7879}
7880
7881VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7882 unsigned &Idx) {
7883 unsigned Major = Record[Idx++];
7884 unsigned Minor = Record[Idx++];
7885 unsigned Subminor = Record[Idx++];
7886 if (Minor == 0)
7887 return VersionTuple(Major);
7888 if (Subminor == 0)
7889 return VersionTuple(Major, Minor - 1);
7890 return VersionTuple(Major, Minor - 1, Subminor - 1);
7891}
7892
7893CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7894 const RecordData &Record,
7895 unsigned &Idx) {
7896 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7897 return CXXTemporary::Create(Context, Decl);
7898}
7899
7900DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007901 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007902}
7903
7904DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7905 return Diags.Report(Loc, DiagID);
7906}
7907
7908/// \brief Retrieve the identifier table associated with the
7909/// preprocessor.
7910IdentifierTable &ASTReader::getIdentifierTable() {
7911 return PP.getIdentifierTable();
7912}
7913
7914/// \brief Record that the given ID maps to the given switch-case
7915/// statement.
7916void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007917 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007918 "Already have a SwitchCase with this ID");
7919 (*CurrSwitchCaseStmts)[ID] = SC;
7920}
7921
7922/// \brief Retrieve the switch-case statement with the given ID.
7923SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007924 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007925 return (*CurrSwitchCaseStmts)[ID];
7926}
7927
7928void ASTReader::ClearSwitchCaseIDs() {
7929 CurrSwitchCaseStmts->clear();
7930}
7931
7932void ASTReader::ReadComments() {
7933 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007934 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 serialization::ModuleFile *> >::iterator
7936 I = CommentsCursors.begin(),
7937 E = CommentsCursors.end();
7938 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007939 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007940 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 serialization::ModuleFile &F = *I->second;
7942 SavedStreamPosition SavedPosition(Cursor);
7943
7944 RecordData Record;
7945 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007946 llvm::BitstreamEntry Entry =
7947 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007948
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007949 switch (Entry.Kind) {
7950 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7951 case llvm::BitstreamEntry::Error:
7952 Error("malformed block record in AST file");
7953 return;
7954 case llvm::BitstreamEntry::EndBlock:
7955 goto NextCursor;
7956 case llvm::BitstreamEntry::Record:
7957 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007959 }
7960
7961 // Read a record.
7962 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007963 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007964 case COMMENTS_RAW_COMMENT: {
7965 unsigned Idx = 0;
7966 SourceRange SR = ReadSourceRange(F, Record, Idx);
7967 RawComment::CommentKind Kind =
7968 (RawComment::CommentKind) Record[Idx++];
7969 bool IsTrailingComment = Record[Idx++];
7970 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007971 Comments.push_back(new (Context) RawComment(
7972 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7973 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 break;
7975 }
7976 }
7977 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007978 NextCursor:
7979 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007981}
7982
Richard Smithcd45dbc2014-04-19 03:48:30 +00007983std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7984 // If we know the owning module, use it.
7985 if (Module *M = D->getOwningModule())
7986 return M->getFullModuleName();
7987
7988 // Otherwise, use the name of the top-level module the decl is within.
7989 if (ModuleFile *M = getOwningModuleFile(D))
7990 return M->ModuleName;
7991
7992 // Not from a module.
7993 return "";
7994}
7995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00007997 while (!PendingIdentifierInfos.empty() ||
7998 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007999 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00008000 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 // If any identifiers with corresponding top-level declarations have
8002 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008003 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8004 TopLevelDeclsMap;
8005 TopLevelDeclsMap TopLevelDecls;
8006
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008008 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008009 SmallVector<uint32_t, 4> DeclIDs =
8010 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008011 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008012
8013 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008015
Richard Smith851072e2014-05-19 20:59:20 +00008016 // For each decl chain that we wanted to complete while deserializing, mark
8017 // it as "still needs to be completed".
8018 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8019 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8020 }
8021 PendingIncompleteDeclChains.clear();
8022
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 // Load pending declaration chains.
8024 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8025 loadPendingDeclChain(PendingDeclChains[I]);
8026 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8027 }
8028 PendingDeclChains.clear();
8029
Douglas Gregor6168bd22013-02-18 15:53:43 +00008030 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008031 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8032 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008033 IdentifierInfo *II = TLD->first;
8034 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008035 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008036 }
8037 }
8038
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 // Load any pending macro definitions.
8040 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008041 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8042 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8043 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8044 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008045 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008046 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008047 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8048 if (Info.M->Kind != MK_Module)
8049 resolvePendingMacro(II, Info);
8050 }
8051 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008052 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008053 ++IDIdx) {
8054 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8055 if (Info.M->Kind == MK_Module)
8056 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 }
8058 }
8059 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008060
8061 // Wire up the DeclContexts for Decls that we delayed setting until
8062 // recursive loading is completed.
8063 while (!PendingDeclContextInfos.empty()) {
8064 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8065 PendingDeclContextInfos.pop_front();
8066 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8067 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8068 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8069 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008070
Richard Smithd1c46742014-04-30 02:24:17 +00008071 // Perform any pending declaration updates.
8072 while (!PendingUpdateRecords.empty()) {
8073 auto Update = PendingUpdateRecords.pop_back_val();
8074 ReadingKindTracker ReadingKind(Read_Decl, *this);
8075 loadDeclUpdateRecords(Update.first, Update.second);
8076 }
8077
Richard Smithcd45dbc2014-04-19 03:48:30 +00008078 // Trigger the import of the full definition of each class that had any
8079 // odr-merging problems, so we can produce better diagnostics for them.
8080 for (auto &Merge : PendingOdrMergeFailures) {
8081 Merge.first->buildLookup();
8082 Merge.first->decls_begin();
8083 Merge.first->bases_begin();
8084 Merge.first->vbases_begin();
8085 for (auto *RD : Merge.second) {
8086 RD->decls_begin();
8087 RD->bases_begin();
8088 RD->vbases_begin();
8089 }
8090 }
8091
Richard Smith2b9e3e32013-10-18 06:05:18 +00008092 // For each declaration from a merged context, check that the canonical
8093 // definition of that context also contains a declaration of the same
8094 // entity.
8095 while (!PendingOdrMergeChecks.empty()) {
8096 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8097
8098 // FIXME: Skip over implicit declarations for now. This matters for things
8099 // like implicitly-declared special member functions. This isn't entirely
8100 // correct; we can end up with multiple unmerged declarations of the same
8101 // implicit entity.
8102 if (D->isImplicit())
8103 continue;
8104
8105 DeclContext *CanonDef = D->getDeclContext();
8106 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8107
8108 bool Found = false;
8109 const Decl *DCanon = D->getCanonicalDecl();
8110
8111 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8112 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8113 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008114 for (auto RI : (*I)->redecls()) {
8115 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008116 // This declaration is present in the canonical definition. If it's
8117 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008118 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008119 Found = true;
8120 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008121 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008122 break;
8123 }
8124 }
8125 }
8126
8127 if (!Found) {
8128 D->setInvalidDecl();
8129
Richard Smithcd45dbc2014-04-19 03:48:30 +00008130 std::string CanonDefModule =
8131 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008132 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008133 << D << getOwningModuleNameForDiagnostic(D)
8134 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008135
8136 if (Candidates.empty())
8137 Diag(cast<Decl>(CanonDef)->getLocation(),
8138 diag::note_module_odr_violation_no_possible_decls) << D;
8139 else {
8140 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8141 Diag(Candidates[I]->getLocation(),
8142 diag::note_module_odr_violation_possible_decl)
8143 << Candidates[I];
8144 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008145
8146 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008147 }
8148 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 }
8150
8151 // If we deserialized any C++ or Objective-C class definitions, any
8152 // Objective-C protocol definitions, or any redeclarable templates, make sure
8153 // that all redeclarations point to the definitions. Note that this can only
8154 // happen now, after the redeclaration chains have been fully wired.
8155 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8156 DEnd = PendingDefinitions.end();
8157 D != DEnd; ++D) {
8158 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008159 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 // Make sure that the TagType points at the definition.
8161 const_cast<TagType*>(TagT)->decl = TD;
8162 }
8163
Aaron Ballman86c93902014-03-06 23:45:36 +00008164 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8165 for (auto R : RD->redecls())
8166 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008167 }
8168
8169 continue;
8170 }
8171
Aaron Ballman86c93902014-03-06 23:45:36 +00008172 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 // Make sure that the ObjCInterfaceType points at the definition.
8174 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8175 ->Decl = ID;
8176
Aaron Ballman86c93902014-03-06 23:45:36 +00008177 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 R->Data = ID->Data;
8179
8180 continue;
8181 }
8182
Aaron Ballman86c93902014-03-06 23:45:36 +00008183 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8184 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 R->Data = PD->Data;
8186
8187 continue;
8188 }
8189
Aaron Ballman86c93902014-03-06 23:45:36 +00008190 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8191 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 R->Common = RTD->Common;
8193 }
8194 PendingDefinitions.clear();
8195
8196 // Load the bodies of any functions or methods we've encountered. We do
8197 // this now (delayed) so that we can be sure that the declaration chains
8198 // have been fully wired up.
8199 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8200 PBEnd = PendingBodies.end();
8201 PB != PBEnd; ++PB) {
8202 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8203 // FIXME: Check for =delete/=default?
8204 // FIXME: Complain about ODR violations here?
8205 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8206 FD->setLazyBody(PB->second);
8207 continue;
8208 }
8209
8210 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8211 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8212 MD->setLazyBody(PB->second);
8213 }
8214 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008215
8216 // Issue any pending ODR-failure diagnostics.
8217 for (auto &Merge : PendingOdrMergeFailures) {
8218 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8219 continue;
8220
8221 bool Diagnosed = false;
8222 for (auto *RD : Merge.second) {
8223 // Multiple different declarations got merged together; tell the user
8224 // where they came from.
8225 if (Merge.first != RD) {
8226 // FIXME: Walk the definition, figure out what's different,
8227 // and diagnose that.
8228 if (!Diagnosed) {
8229 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8230 Diag(Merge.first->getLocation(),
8231 diag::err_module_odr_violation_different_definitions)
8232 << Merge.first << Module.empty() << Module;
8233 Diagnosed = true;
8234 }
8235
8236 Diag(RD->getLocation(),
8237 diag::note_module_odr_violation_different_definitions)
8238 << getOwningModuleNameForDiagnostic(RD);
8239 }
8240 }
8241
8242 if (!Diagnosed) {
8243 // All definitions are updates to the same declaration. This happens if a
8244 // module instantiates the declaration of a class template specialization
8245 // and two or more other modules instantiate its definition.
8246 //
8247 // FIXME: Indicate which modules had instantiations of this definition.
8248 // FIXME: How can this even happen?
8249 Diag(Merge.first->getLocation(),
8250 diag::err_module_odr_violation_different_instantiations)
8251 << Merge.first;
8252 }
8253 }
8254 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008255}
8256
8257void ASTReader::FinishedDeserializing() {
8258 assert(NumCurrentElementsDeserializing &&
8259 "FinishedDeserializing not paired with StartedDeserializing");
8260 if (NumCurrentElementsDeserializing == 1) {
8261 // We decrease NumCurrentElementsDeserializing only after pending actions
8262 // are finished, to avoid recursively re-calling finishPendingActions().
8263 finishPendingActions();
8264 }
8265 --NumCurrentElementsDeserializing;
8266
Richard Smith04d05b52014-03-23 00:27:18 +00008267 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8268 // We are not in recursive loading, so it's safe to pass the "interesting"
8269 // decls to the consumer.
8270 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 }
8272}
8273
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008274void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008275 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008276
8277 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8278 SemaObj->TUScope->AddDecl(D);
8279 } else if (SemaObj->TUScope) {
8280 // Adding the decl to IdResolver may have failed because it was already in
8281 // (even though it was not added in scope). If it is already in, make sure
8282 // it gets in the scope as well.
8283 if (std::find(SemaObj->IdResolver.begin(Name),
8284 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8285 SemaObj->TUScope->AddDecl(D);
8286 }
8287}
8288
Nico Weber824285e2014-05-08 04:26:47 +00008289ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8290 bool DisableValidation, bool AllowASTWithCompilerErrors,
8291 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008292 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008293 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008294 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008295 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8296 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8297 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8298 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008299 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8300 AllowConfigurationMismatch(AllowConfigurationMismatch),
8301 ValidateSystemInputs(ValidateSystemInputs),
8302 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008303 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008304 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8305 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8306 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8307 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8308 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8309 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8310 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8311 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8312 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8313 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8314 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 SourceMgr.setExternalSLocEntrySource(this);
8316}
8317
8318ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008319 if (OwnsDeserializationListener)
8320 delete DeserializationListener;
8321
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 for (DeclContextVisibleUpdatesPending::iterator
8323 I = PendingVisibleUpdates.begin(),
8324 E = PendingVisibleUpdates.end();
8325 I != E; ++I) {
8326 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8327 F = I->second.end();
8328 J != F; ++J)
8329 delete J->first;
8330 }
8331}