1 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "clang/Serialization/ASTDeserializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Frontend/FrontendDiagnostic.h"
18 #include "clang/Frontend/Utils.h"
19 #include "clang/Sema/Sema.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/Type.h"
28 #include "clang/AST/TypeLocVisitor.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/OnDiskHashTable.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/SourceManagerInternals.h"
36 #include "clang/Basic/FileManager.h"
37 #include "clang/Basic/FileSystemStatCache.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Basic/VersionTuple.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/Bitcode/BitstreamReader.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/system_error.h"
53 using namespace clang;
54 using namespace clang::serialization;
56 //===----------------------------------------------------------------------===//
57 // PCH validator implementation
58 //===----------------------------------------------------------------------===//
60 ASTReaderListener::~ASTReaderListener() {}
63 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
64 const LangOptions &PPLangOpts = PP.getLangOptions();
65 #define PARSE_LANGOPT_BENIGN(Option)
66 #define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
67 if (PPLangOpts.Option != LangOpts.Option) { \
68 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
72 PARSE_LANGOPT_BENIGN(Trigraphs);
73 PARSE_LANGOPT_BENIGN(BCPLComment);
74 PARSE_LANGOPT_BENIGN(DollarIdents);
75 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
76 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
77 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
78 PARSE_LANGOPT_BENIGN(ImplicitInt);
79 PARSE_LANGOPT_BENIGN(Digraphs);
80 PARSE_LANGOPT_BENIGN(HexFloats);
81 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
82 PARSE_LANGOPT_IMPORTANT(C1X, diag::warn_pch_c1x);
83 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
84 PARSE_LANGOPT_BENIGN(MSCVersion);
85 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
86 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
87 PARSE_LANGOPT_BENIGN(CXXOperatorName);
88 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
89 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
90 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
91 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
92 PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext);
93 PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties,
94 diag::warn_pch_objc_auto_properties);
95 PARSE_LANGOPT_BENIGN(ObjCInferRelatedResultType)
96 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
97 diag::warn_pch_no_constant_cfstrings);
98 PARSE_LANGOPT_BENIGN(PascalStrings);
99 PARSE_LANGOPT_BENIGN(WritableStrings);
100 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
101 diag::warn_pch_lax_vector_conversions);
102 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
103 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
104 PARSE_LANGOPT_IMPORTANT(ObjCExceptions, diag::warn_pch_objc_exceptions);
105 PARSE_LANGOPT_IMPORTANT(CXXExceptions, diag::warn_pch_cxx_exceptions);
106 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
107 PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields);
108 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
109 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
110 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
111 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
112 diag::warn_pch_thread_safe_statics);
113 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
114 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
115 PARSE_LANGOPT_BENIGN(EmitAllDecls);
116 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
117 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
118 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
119 diag::warn_pch_heinous_extensions);
120 // FIXME: Most of the options below are benign if the macro wasn't
121 // used. Unfortunately, this means that a PCH compiled without
122 // optimization can't be used with optimization turned on, even
123 // though the only thing that changes is whether __OPTIMIZE__ was
124 // defined... but if __OPTIMIZE__ never showed up in the header, it
125 // doesn't matter. We could consider making this some special kind
127 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
128 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
129 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
130 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
131 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
132 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
133 PARSE_LANGOPT_IMPORTANT(Deprecated, diag::warn_pch_deprecated);
134 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
135 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
136 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
137 PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums);
138 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
139 Reader.Diag(diag::warn_pch_gc_mode)
140 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
143 PARSE_LANGOPT_BENIGN(getVisibilityMode());
144 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
145 diag::warn_pch_stack_protector);
146 PARSE_LANGOPT_BENIGN(InstantiationDepth);
147 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
148 PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda);
149 PARSE_LANGOPT_BENIGN(CatchUndefined);
150 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
151 PARSE_LANGOPT_BENIGN(SpellChecking);
152 PARSE_LANGOPT_BENIGN(DefaultFPContract);
153 #undef PARSE_LANGOPT_IMPORTANT
154 #undef PARSE_LANGOPT_BENIGN
159 bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
160 if (Triple == PP.getTargetInfo().getTriple().str())
163 Reader.Diag(diag::warn_pch_target_triple)
164 << Triple << PP.getTargetInfo().getTriple().str();
169 struct EmptyStringRef {
170 bool operator ()(llvm::StringRef r) const { return r.empty(); }
173 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
177 static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
178 PCHPredefinesBlocks R) {
179 // First, sum up the lengths.
180 unsigned LL = 0, RL = 0;
181 for (unsigned I = 0, N = L.size(); I != N; ++I) {
184 for (unsigned I = 0, N = R.size(); I != N; ++I) {
185 RL += R[I].Data.size();
189 if (LL == 0 && RL == 0)
192 // Kick out empty parts, they confuse the algorithm below.
193 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
194 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
196 // Do it the hard way. At this point, both vectors must be non-empty.
197 llvm::StringRef LR = L[0], RR = R[0].Data;
198 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
201 // Compare the current pieces.
202 if (LR.size() == RR.size()) {
203 // If they're the same length, it's pretty easy.
206 // Both pieces are done, advance.
209 // If either string is done, they're both done, since they're the same
212 assert(RI == RN && "Strings not the same length after all?");
217 } else if (LR.size() < RR.size()) {
218 // Right piece is longer.
219 if (!RR.startswith(LR))
222 assert(LI != LN && "Strings not the same length after all?");
223 RR = RR.substr(LR.size());
226 // Left piece is longer.
227 if (!LR.startswith(RR))
230 assert(RI != RN && "Strings not the same length after all?");
231 LR = LR.substr(RR.size());
237 static std::pair<FileID, llvm::StringRef::size_type>
238 FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
239 std::pair<FileID, llvm::StringRef::size_type> Res;
240 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
241 Res.second = Buffers[I].Data.find(MacroDef);
242 if (Res.second != llvm::StringRef::npos) {
243 Res.first = Buffers[I].BufferID;
250 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
251 llvm::StringRef OriginalFileName,
252 std::string &SuggestedPredefines,
253 FileManager &FileMgr) {
254 // We are in the context of an implicit include, so the predefines buffer will
255 // have a #include entry for the PCH file itself (as normalized by the
256 // preprocessor initialization). Find it and skip over it in the checking
258 llvm::SmallString<256> PCHInclude;
259 PCHInclude += "#include \"";
260 PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
261 PCHInclude += "\"\n";
262 std::pair<llvm::StringRef,llvm::StringRef> Split =
263 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
264 llvm::StringRef Left = Split.first, Right = Split.second;
265 if (Left == PP.getPredefines()) {
266 Error("Missing PCH include entry!");
270 // If the concatenation of all the PCH buffers is equal to the adjusted
271 // command line, we're done.
272 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
273 CommandLine.push_back(Left);
274 CommandLine.push_back(Right);
275 if (EqualConcatenations(CommandLine, Buffers))
278 SourceManager &SourceMgr = PP.getSourceManager();
280 // The predefines buffers are different. Determine what the differences are,
281 // and whether they require us to reject the PCH file.
282 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
283 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
284 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
286 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
287 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
289 // Pick out implicit #includes after the PCH and don't consider them for
290 // validation; we will insert them into SuggestedPredefines so that the
291 // preprocessor includes them.
292 std::string IncludesAfterPCH;
293 llvm::SmallVector<llvm::StringRef, 8> AfterPCHLines;
294 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
295 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
296 if (AfterPCHLines[i].startswith("#include ")) {
297 IncludesAfterPCH += AfterPCHLines[i];
298 IncludesAfterPCH += '\n';
300 CmdLineLines.push_back(AfterPCHLines[i]);
304 // Make sure we add the includes last into SuggestedPredefines before we
305 // exit this function.
306 struct AddIncludesRAII {
307 std::string &SuggestedPredefines;
308 std::string &IncludesAfterPCH;
310 AddIncludesRAII(std::string &SuggestedPredefines,
311 std::string &IncludesAfterPCH)
312 : SuggestedPredefines(SuggestedPredefines),
313 IncludesAfterPCH(IncludesAfterPCH) { }
315 SuggestedPredefines += IncludesAfterPCH;
317 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
319 // Sort both sets of predefined buffer lines, since we allow some extra
320 // definitions and they may appear at any point in the output.
321 std::sort(CmdLineLines.begin(), CmdLineLines.end());
322 std::sort(PCHLines.begin(), PCHLines.end());
324 // Determine which predefines that were used to build the PCH file are missing
325 // from the command line.
326 std::vector<llvm::StringRef> MissingPredefines;
327 std::set_difference(PCHLines.begin(), PCHLines.end(),
328 CmdLineLines.begin(), CmdLineLines.end(),
329 std::back_inserter(MissingPredefines));
331 bool MissingDefines = false;
332 bool ConflictingDefines = false;
333 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
334 llvm::StringRef Missing = MissingPredefines[I];
335 if (Missing.startswith("#include ")) {
336 // An -include was specified when generating the PCH; it is included in
337 // the PCH, just ignore it.
340 if (!Missing.startswith("#define ")) {
341 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
345 // This is a macro definition. Determine the name of the macro we're
347 std::string::size_type StartOfMacroName = strlen("#define ");
348 std::string::size_type EndOfMacroName
349 = Missing.find_first_of("( \n\r", StartOfMacroName);
350 assert(EndOfMacroName != std::string::npos &&
351 "Couldn't find the end of the macro name");
352 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
354 // Determine whether this macro was given a different definition on the
356 std::string MacroDefStart = "#define " + MacroName.str();
357 std::string::size_type MacroDefLen = MacroDefStart.size();
358 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
359 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
361 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
362 if (!ConflictPos->startswith(MacroDefStart)) {
363 // Different macro; we're done.
364 ConflictPos = CmdLineLines.end();
368 assert(ConflictPos->size() > MacroDefLen &&
369 "Invalid #define in predefines buffer?");
370 if ((*ConflictPos)[MacroDefLen] != ' ' &&
371 (*ConflictPos)[MacroDefLen] != '(')
372 continue; // Longer macro name; keep trying.
374 // We found a conflicting macro definition.
378 if (ConflictPos != CmdLineLines.end()) {
379 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
382 // Show the definition of this macro within the PCH file.
383 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
384 FindMacro(Buffers, Missing);
385 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
386 SourceLocation PCHMissingLoc =
387 SourceMgr.getLocForStartOfFile(MacroLoc.first)
388 .getFileLocWithOffset(MacroLoc.second);
389 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
391 ConflictingDefines = true;
395 // If the macro doesn't conflict, then we'll just pick up the macro
396 // definition from the PCH file. Warn the user that they made a mistake.
397 if (ConflictingDefines)
398 continue; // Don't complain if there are already conflicting defs
400 if (!MissingDefines) {
401 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
402 MissingDefines = true;
405 // Show the definition of this macro within the PCH file.
406 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
407 FindMacro(Buffers, Missing);
408 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
409 SourceLocation PCHMissingLoc =
410 SourceMgr.getLocForStartOfFile(MacroLoc.first)
411 .getFileLocWithOffset(MacroLoc.second);
412 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
415 if (ConflictingDefines)
418 // Determine what predefines were introduced based on command-line
419 // parameters that were not present when building the PCH
420 // file. Extra #defines are okay, so long as the identifiers being
421 // defined were not used within the precompiled header.
422 std::vector<llvm::StringRef> ExtraPredefines;
423 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
424 PCHLines.begin(), PCHLines.end(),
425 std::back_inserter(ExtraPredefines));
426 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
427 llvm::StringRef &Extra = ExtraPredefines[I];
428 if (!Extra.startswith("#define ")) {
429 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
433 // This is an extra macro definition. Determine the name of the
434 // macro we're defining.
435 std::string::size_type StartOfMacroName = strlen("#define ");
436 std::string::size_type EndOfMacroName
437 = Extra.find_first_of("( \n\r", StartOfMacroName);
438 assert(EndOfMacroName != std::string::npos &&
439 "Couldn't find the end of the macro name");
440 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
442 // Check whether this name was used somewhere in the PCH file. If
443 // so, defining it as a macro could change behavior, so we reject
445 if (IdentifierInfo *II = Reader.get(MacroName)) {
446 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
450 // Add this definition to the suggested predefines buffer.
451 SuggestedPredefines += Extra;
452 SuggestedPredefines += '\n';
455 // If we get here, it's because the predefines buffer had compatible
456 // contents. Accept the PCH file.
460 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
462 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
466 void PCHValidator::ReadCounter(unsigned Value) {
467 PP.setCounterValue(Value);
470 //===----------------------------------------------------------------------===//
471 // AST reader implementation
472 //===----------------------------------------------------------------------===//
475 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
476 DeserializationListener = Listener;
481 class ASTSelectorLookupTrait {
487 ObjCMethodList Instance, Factory;
490 typedef Selector external_key_type;
491 typedef external_key_type internal_key_type;
493 explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { }
495 static bool EqualKey(const internal_key_type& a,
496 const internal_key_type& b) {
500 static unsigned ComputeHash(Selector Sel) {
501 return serialization::ComputeHash(Sel);
504 // This hopefully will just get inlined and removed by the optimizer.
505 static const internal_key_type&
506 GetInternalKey(const external_key_type& x) { return x; }
508 static std::pair<unsigned, unsigned>
509 ReadKeyDataLength(const unsigned char*& d) {
510 using namespace clang::io;
511 unsigned KeyLen = ReadUnalignedLE16(d);
512 unsigned DataLen = ReadUnalignedLE16(d);
513 return std::make_pair(KeyLen, DataLen);
516 internal_key_type ReadKey(const unsigned char* d, unsigned) {
517 using namespace clang::io;
518 SelectorTable &SelTable = Reader.getContext()->Selectors;
519 unsigned N = ReadUnalignedLE16(d);
520 IdentifierInfo *FirstII
521 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
523 return SelTable.getNullarySelector(FirstII);
525 return SelTable.getUnarySelector(FirstII);
527 llvm::SmallVector<IdentifierInfo *, 16> Args;
528 Args.push_back(FirstII);
529 for (unsigned I = 1; I != N; ++I)
530 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
532 return SelTable.getSelector(N, Args.data());
535 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
536 using namespace clang::io;
540 Result.ID = ReadUnalignedLE32(d);
541 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
542 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
544 // Load instance methods
545 ObjCMethodList *Prev = 0;
546 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
547 ObjCMethodDecl *Method
548 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
549 if (!Result.Instance.Method) {
550 // This is the first method, which is the easy case.
551 Result.Instance.Method = Method;
552 Prev = &Result.Instance;
556 ObjCMethodList *Mem =
557 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
558 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
562 // Load factory methods
564 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
565 ObjCMethodDecl *Method
566 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
567 if (!Result.Factory.Method) {
568 // This is the first method, which is the easy case.
569 Result.Factory.Method = Method;
570 Prev = &Result.Factory;
574 ObjCMethodList *Mem =
575 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
576 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
584 } // end anonymous namespace
586 /// \brief The on-disk hash table used for the global method pool.
587 typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
588 ASTSelectorLookupTable;
591 class ASTIdentifierLookupTrait {
593 ASTReader::PerFileData &F;
595 // If we know the IdentifierInfo in advance, it is here and we will
596 // not build a new one. Used when deserializing information about an
597 // identifier that was constructed before the AST file was read.
598 IdentifierInfo *KnownII;
601 typedef IdentifierInfo * data_type;
603 typedef const std::pair<const char*, unsigned> external_key_type;
605 typedef external_key_type internal_key_type;
607 ASTIdentifierLookupTrait(ASTReader &Reader, ASTReader::PerFileData &F,
608 IdentifierInfo *II = 0)
609 : Reader(Reader), F(F), KnownII(II) { }
611 static bool EqualKey(const internal_key_type& a,
612 const internal_key_type& b) {
613 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
617 static unsigned ComputeHash(const internal_key_type& a) {
618 return llvm::HashString(llvm::StringRef(a.first, a.second));
621 // This hopefully will just get inlined and removed by the optimizer.
622 static const internal_key_type&
623 GetInternalKey(const external_key_type& x) { return x; }
625 // This hopefully will just get inlined and removed by the optimizer.
626 static const external_key_type&
627 GetExternalKey(const internal_key_type& x) { return x; }
629 static std::pair<unsigned, unsigned>
630 ReadKeyDataLength(const unsigned char*& d) {
631 using namespace clang::io;
632 unsigned DataLen = ReadUnalignedLE16(d);
633 unsigned KeyLen = ReadUnalignedLE16(d);
634 return std::make_pair(KeyLen, DataLen);
637 static std::pair<const char*, unsigned>
638 ReadKey(const unsigned char* d, unsigned n) {
639 assert(n >= 2 && d[n-1] == '\0');
640 return std::make_pair((const char*) d, n-1);
643 IdentifierInfo *ReadData(const internal_key_type& k,
644 const unsigned char* d,
646 using namespace clang::io;
647 IdentID ID = ReadUnalignedLE32(d);
648 bool IsInteresting = ID & 0x01;
650 // Wipe out the "is interesting" bit.
653 if (!IsInteresting) {
654 // For uninteresting identifiers, just build the IdentifierInfo
655 // and associate it with the persistent ID.
656 IdentifierInfo *II = KnownII;
658 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
659 Reader.SetIdentifierInfo(ID, II);
664 unsigned Bits = ReadUnalignedLE16(d);
665 bool CPlusPlusOperatorKeyword = Bits & 0x01;
667 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
669 bool Poisoned = Bits & 0x01;
671 bool ExtensionToken = Bits & 0x01;
673 bool hasMacroDefinition = Bits & 0x01;
675 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
678 assert(Bits == 0 && "Extra bits in the identifier?");
681 // Build the IdentifierInfo itself and link the identifier ID with
682 // the new IdentifierInfo.
683 IdentifierInfo *II = KnownII;
685 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
686 Reader.SetIdentifierInfo(ID, II);
688 // Set or check the various bits in the IdentifierInfo structure.
689 // Token IDs are read-only.
690 if (HasRevertedTokenIDToIdentifier)
691 II->RevertTokenIDToIdentifier();
692 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
693 assert(II->isExtensionToken() == ExtensionToken &&
694 "Incorrect extension token flag");
695 (void)ExtensionToken;
696 II->setIsPoisoned(Poisoned);
697 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
698 "Incorrect C++ operator keyword flag");
699 (void)CPlusPlusOperatorKeyword;
701 // If this identifier is a macro, deserialize the macro
703 if (hasMacroDefinition) {
704 uint32_t Offset = ReadUnalignedLE32(d);
705 Reader.SetIdentifierIsMacro(II, F, Offset);
709 // Read all of the declarations visible at global scope with this
711 if (Reader.getContext() == 0) return II;
713 llvm::SmallVector<uint32_t, 4> DeclIDs;
714 for (; DataLen > 0; DataLen -= 4)
715 DeclIDs.push_back(ReadUnalignedLE32(d));
716 Reader.SetGloballyVisibleDecls(II, DeclIDs);
724 } // end anonymous namespace
726 /// \brief The on-disk hash table used to contain information about
727 /// all of the identifiers in the program.
728 typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
729 ASTIdentifierLookupTable;
732 class ASTDeclContextNameLookupTrait {
736 /// \brief Pair of begin/end iterators for DeclIDs.
737 typedef std::pair<DeclID *, DeclID *> data_type;
739 /// \brief Special internal key for declaration names.
740 /// The hash table creates keys for comparison; we do not create
741 /// a DeclarationName for the internal key to avoid deserializing types.
743 DeclarationName::NameKind Kind;
745 DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { }
748 typedef DeclarationName external_key_type;
749 typedef DeclNameKey internal_key_type;
751 explicit ASTDeclContextNameLookupTrait(ASTReader &Reader) : Reader(Reader) { }
753 static bool EqualKey(const internal_key_type& a,
754 const internal_key_type& b) {
755 return a.Kind == b.Kind && a.Data == b.Data;
758 unsigned ComputeHash(const DeclNameKey &Key) const {
759 llvm::FoldingSetNodeID ID;
760 ID.AddInteger(Key.Kind);
763 case DeclarationName::Identifier:
764 case DeclarationName::CXXLiteralOperatorName:
765 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
767 case DeclarationName::ObjCZeroArgSelector:
768 case DeclarationName::ObjCOneArgSelector:
769 case DeclarationName::ObjCMultiArgSelector:
770 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
772 case DeclarationName::CXXConstructorName:
773 case DeclarationName::CXXDestructorName:
774 case DeclarationName::CXXConversionFunctionName:
775 ID.AddInteger((TypeID)Key.Data);
777 case DeclarationName::CXXOperatorName:
778 ID.AddInteger((OverloadedOperatorKind)Key.Data);
780 case DeclarationName::CXXUsingDirective:
784 return ID.ComputeHash();
787 internal_key_type GetInternalKey(const external_key_type& Name) const {
789 Key.Kind = Name.getNameKind();
790 switch (Name.getNameKind()) {
791 case DeclarationName::Identifier:
792 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
794 case DeclarationName::ObjCZeroArgSelector:
795 case DeclarationName::ObjCOneArgSelector:
796 case DeclarationName::ObjCMultiArgSelector:
797 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
799 case DeclarationName::CXXConstructorName:
800 case DeclarationName::CXXDestructorName:
801 case DeclarationName::CXXConversionFunctionName:
802 Key.Data = Reader.GetTypeID(Name.getCXXNameType());
804 case DeclarationName::CXXOperatorName:
805 Key.Data = Name.getCXXOverloadedOperator();
807 case DeclarationName::CXXLiteralOperatorName:
808 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
810 case DeclarationName::CXXUsingDirective:
817 external_key_type GetExternalKey(const internal_key_type& Key) const {
818 ASTContext *Context = Reader.getContext();
820 case DeclarationName::Identifier:
821 return DeclarationName((IdentifierInfo*)Key.Data);
823 case DeclarationName::ObjCZeroArgSelector:
824 case DeclarationName::ObjCOneArgSelector:
825 case DeclarationName::ObjCMultiArgSelector:
826 return DeclarationName(Selector(Key.Data));
828 case DeclarationName::CXXConstructorName:
829 return Context->DeclarationNames.getCXXConstructorName(
830 Context->getCanonicalType(Reader.GetType(Key.Data)));
832 case DeclarationName::CXXDestructorName:
833 return Context->DeclarationNames.getCXXDestructorName(
834 Context->getCanonicalType(Reader.GetType(Key.Data)));
836 case DeclarationName::CXXConversionFunctionName:
837 return Context->DeclarationNames.getCXXConversionFunctionName(
838 Context->getCanonicalType(Reader.GetType(Key.Data)));
840 case DeclarationName::CXXOperatorName:
841 return Context->DeclarationNames.getCXXOperatorName(
842 (OverloadedOperatorKind)Key.Data);
844 case DeclarationName::CXXLiteralOperatorName:
845 return Context->DeclarationNames.getCXXLiteralOperatorName(
846 (IdentifierInfo*)Key.Data);
848 case DeclarationName::CXXUsingDirective:
849 return DeclarationName::getUsingDirectiveName();
852 llvm_unreachable("Invalid Name Kind ?");
855 static std::pair<unsigned, unsigned>
856 ReadKeyDataLength(const unsigned char*& d) {
857 using namespace clang::io;
858 unsigned KeyLen = ReadUnalignedLE16(d);
859 unsigned DataLen = ReadUnalignedLE16(d);
860 return std::make_pair(KeyLen, DataLen);
863 internal_key_type ReadKey(const unsigned char* d, unsigned) {
864 using namespace clang::io;
867 Key.Kind = (DeclarationName::NameKind)*d++;
869 case DeclarationName::Identifier:
870 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
872 case DeclarationName::ObjCZeroArgSelector:
873 case DeclarationName::ObjCOneArgSelector:
874 case DeclarationName::ObjCMultiArgSelector:
876 (uint64_t)Reader.DecodeSelector(ReadUnalignedLE32(d)).getAsOpaquePtr();
878 case DeclarationName::CXXConstructorName:
879 case DeclarationName::CXXDestructorName:
880 case DeclarationName::CXXConversionFunctionName:
881 Key.Data = ReadUnalignedLE32(d); // TypeID
883 case DeclarationName::CXXOperatorName:
884 Key.Data = *d++; // OverloadedOperatorKind
886 case DeclarationName::CXXLiteralOperatorName:
887 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
889 case DeclarationName::CXXUsingDirective:
896 data_type ReadData(internal_key_type, const unsigned char* d,
898 using namespace clang::io;
899 unsigned NumDecls = ReadUnalignedLE16(d);
900 DeclID *Start = (DeclID *)d;
901 return std::make_pair(Start, Start + NumDecls);
905 } // end anonymous namespace
907 /// \brief The on-disk hash table used for the DeclContext's Name lookup table.
908 typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
909 ASTDeclContextNameLookupTable;
911 bool ASTReader::ReadDeclContextStorage(llvm::BitstreamCursor &Cursor,
912 const std::pair<uint64_t, uint64_t> &Offsets,
913 DeclContextInfo &Info) {
914 SavedStreamPosition SavedPosition(Cursor);
915 // First the lexical decls.
916 if (Offsets.first != 0) {
917 Cursor.JumpToBit(Offsets.first);
922 unsigned Code = Cursor.ReadCode();
923 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
924 if (RecCode != DECL_CONTEXT_LEXICAL) {
925 Error("Expected lexical block");
929 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
930 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
932 Info.LexicalDecls = 0;
933 Info.NumLexicalDecls = 0;
936 // Now the lookup table.
937 if (Offsets.second != 0) {
938 Cursor.JumpToBit(Offsets.second);
943 unsigned Code = Cursor.ReadCode();
944 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
945 if (RecCode != DECL_CONTEXT_VISIBLE) {
946 Error("Expected visible lookup table block");
949 Info.NameLookupTableData
950 = ASTDeclContextNameLookupTable::Create(
951 (const unsigned char *)Blob + Record[0],
952 (const unsigned char *)Blob,
953 ASTDeclContextNameLookupTrait(*this));
955 Info.NameLookupTableData = 0;
961 void ASTReader::Error(llvm::StringRef Msg) {
962 Error(diag::err_fe_pch_malformed, Msg);
965 void ASTReader::Error(unsigned DiagID,
966 llvm::StringRef Arg1, llvm::StringRef Arg2) {
967 if (Diags.isDiagnosticInFlight())
968 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
970 Diag(DiagID) << Arg1 << Arg2;
973 /// \brief Tell the AST listener about the predefines buffers in the chain.
974 bool ASTReader::CheckPredefinesBuffers() {
976 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
977 ActualOriginalFileName,
983 //===----------------------------------------------------------------------===//
984 // Source Manager Deserialization
985 //===----------------------------------------------------------------------===//
987 /// \brief Read the line table in the source manager block.
988 /// \returns true if there was an error.
989 bool ASTReader::ParseLineTable(PerFileData &F,
990 llvm::SmallVectorImpl<uint64_t> &Record) {
992 LineTableInfo &LineTable = SourceMgr.getLineTable();
994 // Parse the file names
995 std::map<int, int> FileIDs;
996 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
997 // Extract the file name
998 unsigned FilenameLen = Record[Idx++];
999 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1001 MaybeAddSystemRootToFilename(Filename);
1002 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
1006 // Parse the line entries
1007 std::vector<LineEntry> Entries;
1008 while (Idx < Record.size()) {
1009 int FID = Record[Idx++];
1011 // Extract the line entries
1012 unsigned NumEntries = Record[Idx++];
1013 assert(NumEntries && "Numentries is 00000");
1015 Entries.reserve(NumEntries);
1016 for (unsigned I = 0; I != NumEntries; ++I) {
1017 unsigned FileOffset = Record[Idx++];
1018 unsigned LineNo = Record[Idx++];
1019 int FilenameID = FileIDs[Record[Idx++]];
1020 SrcMgr::CharacteristicKind FileKind
1021 = (SrcMgr::CharacteristicKind)Record[Idx++];
1022 unsigned IncludeOffset = Record[Idx++];
1023 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1024 FileKind, IncludeOffset));
1026 LineTable.AddEntry(FID, Entries);
1042 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
1043 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
1046 class ASTStatLookupTrait {
1048 typedef const char *external_key_type;
1049 typedef const char *internal_key_type;
1051 typedef ASTStatData data_type;
1053 static unsigned ComputeHash(const char *path) {
1054 return llvm::HashString(path);
1057 static internal_key_type GetInternalKey(const char *path) { return path; }
1059 static bool EqualKey(internal_key_type a, internal_key_type b) {
1060 return strcmp(a, b) == 0;
1063 static std::pair<unsigned, unsigned>
1064 ReadKeyDataLength(const unsigned char*& d) {
1065 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1066 unsigned DataLen = (unsigned) *d++;
1067 return std::make_pair(KeyLen + 1, DataLen);
1070 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1071 return (const char *)d;
1074 static data_type ReadData(const internal_key_type, const unsigned char *d,
1075 unsigned /*DataLen*/) {
1076 using namespace clang::io;
1078 ino_t ino = (ino_t) ReadUnalignedLE32(d);
1079 dev_t dev = (dev_t) ReadUnalignedLE32(d);
1080 mode_t mode = (mode_t) ReadUnalignedLE16(d);
1081 time_t mtime = (time_t) ReadUnalignedLE64(d);
1082 off_t size = (off_t) ReadUnalignedLE64(d);
1083 return data_type(ino, dev, mode, mtime, size);
1087 /// \brief stat() cache for precompiled headers.
1089 /// This cache is very similar to the stat cache used by pretokenized
1091 class ASTStatCache : public FileSystemStatCache {
1092 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
1095 unsigned &NumStatHits, &NumStatMisses;
1097 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1098 unsigned &NumStatHits, unsigned &NumStatMisses)
1099 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1100 Cache = CacheTy::Create(Buckets, Base);
1103 ~ASTStatCache() { delete Cache; }
1105 LookupResult getStat(const char *Path, struct stat &StatBuf,
1106 int *FileDescriptor) {
1107 // Do the lookup for the file's data in the AST file.
1108 CacheTy::iterator I = Cache->find(Path);
1110 // If we don't get a hit in the AST file just forward to 'stat'.
1111 if (I == Cache->end()) {
1113 return statChained(Path, StatBuf, FileDescriptor);
1117 ASTStatData Data = *I;
1119 StatBuf.st_ino = Data.ino;
1120 StatBuf.st_dev = Data.dev;
1121 StatBuf.st_mtime = Data.mtime;
1122 StatBuf.st_mode = Data.mode;
1123 StatBuf.st_size = Data.size;
1127 } // end anonymous namespace
1130 /// \brief Read a source manager block
1131 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) {
1132 using namespace SrcMgr;
1134 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1136 // Set the source-location entry cursor to the current position in
1137 // the stream. This cursor will be used to read the contents of the
1138 // source manager block initially, and then lazily read
1139 // source-location entries as needed.
1140 SLocEntryCursor = F.Stream;
1142 // The stream itself is going to skip over the source manager block.
1143 if (F.Stream.SkipBlock()) {
1144 Error("malformed block record in AST file");
1148 // Enter the source manager block.
1149 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1150 Error("malformed source manager block record in AST file");
1156 unsigned Code = SLocEntryCursor.ReadCode();
1157 if (Code == llvm::bitc::END_BLOCK) {
1158 if (SLocEntryCursor.ReadBlockEnd()) {
1159 Error("error at end of Source Manager block in AST file");
1165 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1166 // No known subblocks, always skip them.
1167 SLocEntryCursor.ReadSubBlockID();
1168 if (SLocEntryCursor.SkipBlock()) {
1169 Error("malformed block record in AST file");
1175 if (Code == llvm::bitc::DEFINE_ABBREV) {
1176 SLocEntryCursor.ReadAbbrevRecord();
1181 const char *BlobStart;
1184 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1185 default: // Default behavior: ignore.
1189 if (ParseLineTable(F, Record))
1193 case SM_SLOC_FILE_ENTRY:
1194 case SM_SLOC_BUFFER_ENTRY:
1195 case SM_SLOC_INSTANTIATION_ENTRY:
1196 // Once we hit one of the source location entries, we're done.
1202 /// \brief If a header file is not found at the path that we expect it to be
1203 /// and the PCH file was moved from its original location, try to resolve the
1204 /// file by assuming that header+PCH were moved together and the header is in
1205 /// the same place relative to the PCH.
1207 resolveFileRelativeToOriginalDir(const std::string &Filename,
1208 const std::string &OriginalDir,
1209 const std::string &CurrDir) {
1210 assert(OriginalDir != CurrDir &&
1211 "No point trying to resolve the file if the PCH dir didn't change");
1212 using namespace llvm::sys;
1213 llvm::SmallString<128> filePath(Filename);
1214 fs::make_absolute(filePath);
1215 assert(path::is_absolute(OriginalDir));
1216 llvm::SmallString<128> currPCHPath(CurrDir);
1218 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1219 fileDirE = path::end(path::parent_path(filePath));
1220 path::const_iterator origDirI = path::begin(OriginalDir),
1221 origDirE = path::end(OriginalDir);
1222 // Skip the common path components from filePath and OriginalDir.
1223 while (fileDirI != fileDirE && origDirI != origDirE &&
1224 *fileDirI == *origDirI) {
1228 for (; origDirI != origDirE; ++origDirI)
1229 path::append(currPCHPath, "..");
1230 path::append(currPCHPath, fileDirI, fileDirE);
1231 path::append(currPCHPath, path::filename(Filename));
1232 return currPCHPath.str();
1235 /// \brief Get a cursor that's correctly positioned for reading the source
1236 /// location entry with the given ID.
1237 ASTReader::PerFileData *ASTReader::SLocCursorForID(unsigned ID) {
1238 assert(ID != 0 && ID <= TotalNumSLocEntries &&
1239 "SLocCursorForID should only be called for real IDs.");
1243 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1244 F = Chain[N - I - 1];
1245 if (ID < F->LocalNumSLocEntries)
1247 ID -= F->LocalNumSLocEntries;
1249 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
1251 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
1255 /// \brief Read in the source location entry with the given ID.
1256 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(unsigned ID) {
1260 if (ID > TotalNumSLocEntries) {
1261 Error("source location entry ID out-of-range for AST file");
1265 PerFileData *F = SLocCursorForID(ID);
1266 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1268 ++NumSLocEntriesRead;
1269 unsigned Code = SLocEntryCursor.ReadCode();
1270 if (Code == llvm::bitc::END_BLOCK ||
1271 Code == llvm::bitc::ENTER_SUBBLOCK ||
1272 Code == llvm::bitc::DEFINE_ABBREV) {
1273 Error("incorrectly-formatted source location entry in AST file");
1278 const char *BlobStart;
1280 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1282 Error("incorrectly-formatted source location entry in AST file");
1285 case SM_SLOC_FILE_ENTRY: {
1286 std::string Filename(BlobStart, BlobStart + BlobLen);
1287 MaybeAddSystemRootToFilename(Filename);
1288 const FileEntry *File = FileMgr.getFile(Filename);
1289 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1290 OriginalDir != CurrentDir) {
1291 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1294 if (!resolved.empty())
1295 File = FileMgr.getFile(resolved);
1298 File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1301 std::string ErrorStr = "could not find file '";
1302 ErrorStr += Filename;
1303 ErrorStr += "' referenced by AST file";
1304 Error(ErrorStr.c_str());
1308 if (Record.size() < 6) {
1309 Error("source location entry is incorrect");
1313 if (!DisableValidation &&
1314 ((off_t)Record[4] != File->getSize()
1315 #if !defined(LLVM_ON_WIN32)
1316 // In our regression testing, the Windows file system seems to
1317 // have inconsistent modification times that sometimes
1318 // erroneously trigger this error-handling path.
1319 || (time_t)Record[5] != File->getModificationTime()
1322 Error(diag::err_fe_pch_file_modified, Filename);
1326 FileID FID = SourceMgr.createFileID(File, ReadSourceLocation(*F, Record[1]),
1327 (SrcMgr::CharacteristicKind)Record[2],
1330 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1331 .setHasLineDirectives();
1336 case SM_SLOC_BUFFER_ENTRY: {
1337 const char *Name = BlobStart;
1338 unsigned Offset = Record[0];
1339 unsigned Code = SLocEntryCursor.ReadCode();
1342 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1344 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1345 Error("AST record has invalid code");
1349 llvm::MemoryBuffer *Buffer
1350 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1352 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
1354 if (strcmp(Name, "<built-in>") == 0) {
1355 PCHPredefinesBlock Block = {
1357 llvm::StringRef(BlobStart, BlobLen - 1)
1359 PCHPredefinesBuffers.push_back(Block);
1365 case SM_SLOC_INSTANTIATION_ENTRY: {
1366 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1367 SourceMgr.createInstantiationLoc(SpellingLoc,
1368 ReadSourceLocation(*F, Record[2]),
1369 ReadSourceLocation(*F, Record[3]),
1380 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1381 /// specified cursor. Read the abbreviations that are at the top of the block
1382 /// and then leave the cursor pointing into the block.
1383 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1385 if (Cursor.EnterSubBlock(BlockID)) {
1386 Error("malformed block record in AST file");
1391 uint64_t Offset = Cursor.GetCurrentBitNo();
1392 unsigned Code = Cursor.ReadCode();
1394 // We expect all abbrevs to be at the start of the block.
1395 if (Code != llvm::bitc::DEFINE_ABBREV) {
1396 Cursor.JumpToBit(Offset);
1399 Cursor.ReadAbbrevRecord();
1403 PreprocessedEntity *ASTReader::ReadMacroRecord(PerFileData &F, uint64_t Offset) {
1404 assert(PP && "Forgot to set Preprocessor ?");
1405 llvm::BitstreamCursor &Stream = F.MacroCursor;
1407 // Keep track of where we are in the stream, then jump back there
1408 // after reading this macro.
1409 SavedStreamPosition SavedPosition(Stream);
1411 Stream.JumpToBit(Offset);
1413 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1414 MacroInfo *Macro = 0;
1417 unsigned Code = Stream.ReadCode();
1419 case llvm::bitc::END_BLOCK:
1422 case llvm::bitc::ENTER_SUBBLOCK:
1423 // No known subblocks, always skip them.
1424 Stream.ReadSubBlockID();
1425 if (Stream.SkipBlock()) {
1426 Error("malformed block record in AST file");
1431 case llvm::bitc::DEFINE_ABBREV:
1432 Stream.ReadAbbrevRecord();
1438 const char *BlobStart = 0;
1439 unsigned BlobLen = 0;
1441 PreprocessorRecordTypes RecType =
1442 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1445 case PP_MACRO_OBJECT_LIKE:
1446 case PP_MACRO_FUNCTION_LIKE: {
1447 // If we already have a macro, that means that we've hit the end
1448 // of the definition of the macro we were looking for. We're
1453 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1455 Error("macro must have a name in AST file");
1458 SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1459 bool isUsed = Record[2];
1461 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1462 MI->setIsUsed(isUsed);
1465 unsigned NextIndex = 3;
1466 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1467 // Decode function-like macro info.
1468 bool isC99VarArgs = Record[3];
1469 bool isGNUVarArgs = Record[4];
1471 unsigned NumArgs = Record[5];
1472 NextIndex = 6 + NumArgs;
1473 for (unsigned i = 0; i != NumArgs; ++i)
1474 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1476 // Install function-like macro info.
1477 MI->setIsFunctionLike();
1478 if (isC99VarArgs) MI->setIsC99Varargs();
1479 if (isGNUVarArgs) MI->setIsGNUVarargs();
1480 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1481 PP->getPreprocessorAllocator());
1484 // Finally, install the macro.
1485 PP->setMacroInfo(II, MI);
1487 // Remember that we saw this macro last so that we add the tokens that
1488 // form its body to it.
1491 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1492 // We have a macro definition. Load it now.
1493 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1494 getMacroDefinition(Record[NextIndex]));
1502 // If we see a TOKEN before a PP_MACRO_*, then the file is
1503 // erroneous, just pretend we didn't see this.
1504 if (Macro == 0) break;
1508 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1509 Tok.setLength(Record[1]);
1510 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1511 Tok.setIdentifierInfo(II);
1512 Tok.setKind((tok::TokenKind)Record[3]);
1513 Tok.setFlag((Token::TokenFlags)Record[4]);
1514 Macro->AddTokenToBody(Tok);
1523 PreprocessedEntity *ASTReader::LoadPreprocessedEntity(PerFileData &F) {
1524 assert(PP && "Forgot to set Preprocessor ?");
1525 unsigned Code = F.PreprocessorDetailCursor.ReadCode();
1527 case llvm::bitc::END_BLOCK:
1530 case llvm::bitc::ENTER_SUBBLOCK:
1531 Error("unexpected subblock record in preprocessor detail block");
1534 case llvm::bitc::DEFINE_ABBREV:
1535 Error("unexpected abbrevation record in preprocessor detail block");
1542 if (!PP->getPreprocessingRecord()) {
1543 Error("no preprocessing record");
1548 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1549 const char *BlobStart = 0;
1550 unsigned BlobLen = 0;
1552 PreprocessorDetailRecordTypes RecType =
1553 (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord(
1554 Code, Record, BlobStart, BlobLen);
1556 case PPD_MACRO_INSTANTIATION: {
1557 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1560 MacroInstantiation *MI
1561 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1562 SourceRange(ReadSourceLocation(F, Record[1]),
1563 ReadSourceLocation(F, Record[2])),
1564 getMacroDefinition(Record[4]));
1565 PPRec.SetPreallocatedEntity(Record[0], MI);
1569 case PPD_MACRO_DEFINITION: {
1570 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1573 if (Record[1] > MacroDefinitionsLoaded.size()) {
1574 Error("out-of-bounds macro definition record");
1578 // Decode the identifier info and then check again; if the macro is
1579 // still defined and associated with the identifier,
1580 IdentifierInfo *II = DecodeIdentifierInfo(Record[4]);
1581 if (!MacroDefinitionsLoaded[Record[1] - 1]) {
1583 = new (PPRec) MacroDefinition(II,
1584 ReadSourceLocation(F, Record[5]),
1586 ReadSourceLocation(F, Record[2]),
1587 ReadSourceLocation(F, Record[3])));
1589 PPRec.SetPreallocatedEntity(Record[0], MD);
1590 MacroDefinitionsLoaded[Record[1] - 1] = MD;
1592 if (DeserializationListener)
1593 DeserializationListener->MacroDefinitionRead(Record[1], MD);
1596 return MacroDefinitionsLoaded[Record[1] - 1];
1599 case PPD_INCLUSION_DIRECTIVE: {
1600 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1603 const char *FullFileNameStart = BlobStart + Record[3];
1604 const FileEntry *File
1605 = PP->getFileManager().getFile(llvm::StringRef(FullFileNameStart,
1606 BlobLen - Record[3]));
1608 // FIXME: Stable encoding
1609 InclusionDirective::InclusionKind Kind
1610 = static_cast<InclusionDirective::InclusionKind>(Record[5]);
1611 InclusionDirective *ID
1612 = new (PPRec) InclusionDirective(PPRec, Kind,
1613 llvm::StringRef(BlobStart, Record[3]),
1616 SourceRange(ReadSourceLocation(F, Record[1]),
1617 ReadSourceLocation(F, Record[2])));
1618 PPRec.SetPreallocatedEntity(Record[0], ID);
1623 Error("invalid offset in preprocessor detail block");
1628 /// \brief Trait class used to search the on-disk hash table containing all of
1629 /// the header search information.
1631 /// The on-disk hash table contains a mapping from each header path to
1632 /// information about that header (how many times it has been included, its
1633 /// controlling macro, etc.). Note that we actually hash based on the
1634 /// filename, and support "deep" comparisons of file names based on current
1635 /// inode numbers, so that the search can cope with non-normalized path names
1637 class HeaderFileInfoTrait {
1638 const char *SearchPath;
1639 struct stat SearchPathStatBuf;
1640 llvm::Optional<int> SearchPathStatResult;
1642 int StatSimpleCache(const char *Path, struct stat *StatBuf) {
1643 if (Path == SearchPath) {
1644 if (!SearchPathStatResult)
1645 SearchPathStatResult = stat(Path, &SearchPathStatBuf);
1647 *StatBuf = SearchPathStatBuf;
1648 return *SearchPathStatResult;
1651 return stat(Path, StatBuf);
1655 typedef const char *external_key_type;
1656 typedef const char *internal_key_type;
1658 typedef HeaderFileInfo data_type;
1660 HeaderFileInfoTrait(const char *SearchPath = 0) : SearchPath(SearchPath) { }
1662 static unsigned ComputeHash(const char *path) {
1663 return llvm::HashString(llvm::sys::path::filename(path));
1666 static internal_key_type GetInternalKey(const char *path) { return path; }
1668 bool EqualKey(internal_key_type a, internal_key_type b) {
1669 if (strcmp(a, b) == 0)
1672 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1675 // The file names match, but the path names don't. stat() the files to
1676 // see if they are the same.
1677 struct stat StatBufA, StatBufB;
1678 if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1681 return StatBufA.st_ino == StatBufB.st_ino;
1684 static std::pair<unsigned, unsigned>
1685 ReadKeyDataLength(const unsigned char*& d) {
1686 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1687 unsigned DataLen = (unsigned) *d++;
1688 return std::make_pair(KeyLen + 1, DataLen);
1691 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1692 return (const char *)d;
1695 static data_type ReadData(const internal_key_type, const unsigned char *d,
1697 const unsigned char *End = d + DataLen;
1698 using namespace clang::io;
1700 unsigned Flags = *d++;
1701 HFI.isImport = (Flags >> 4) & 0x01;
1702 HFI.isPragmaOnce = (Flags >> 3) & 0x01;
1703 HFI.DirInfo = (Flags >> 1) & 0x03;
1704 HFI.Resolved = Flags & 0x01;
1705 HFI.NumIncludes = ReadUnalignedLE16(d);
1706 HFI.ControllingMacroID = ReadUnalignedLE32(d);
1707 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1710 // This HeaderFileInfo was externally loaded.
1711 HFI.External = true;
1717 /// \brief The on-disk hash table used for the global method pool.
1718 typedef OnDiskChainedHashTable<HeaderFileInfoTrait>
1719 HeaderFileInfoLookupTable;
1721 void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, PerFileData &F,
1723 // Note that this identifier has a macro definition.
1724 II->setHasMacroDefinition(true);
1726 // Adjust the offset based on our position in the chain.
1727 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1731 Offset += Chain[I]->SizeInBits;
1734 UnreadMacroRecordOffsets[II] = Offset;
1737 void ASTReader::ReadDefinedMacros() {
1738 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1739 PerFileData &F = *Chain[N - I - 1];
1740 llvm::BitstreamCursor &MacroCursor = F.MacroCursor;
1742 // If there was no preprocessor block, skip this file.
1743 if (!MacroCursor.getBitStreamReader())
1746 llvm::BitstreamCursor Cursor = MacroCursor;
1747 Cursor.JumpToBit(F.MacroStartOffset);
1751 unsigned Code = Cursor.ReadCode();
1752 if (Code == llvm::bitc::END_BLOCK)
1755 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1756 // No known subblocks, always skip them.
1757 Cursor.ReadSubBlockID();
1758 if (Cursor.SkipBlock()) {
1759 Error("malformed block record in AST file");
1765 if (Code == llvm::bitc::DEFINE_ABBREV) {
1766 Cursor.ReadAbbrevRecord();
1771 const char *BlobStart;
1774 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1775 default: // Default behavior: ignore.
1778 case PP_MACRO_OBJECT_LIKE:
1779 case PP_MACRO_FUNCTION_LIKE:
1780 DecodeIdentifierInfo(Record[0]);
1790 // Drain the unread macro-record offsets map.
1791 while (!UnreadMacroRecordOffsets.empty())
1792 LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1795 void ASTReader::LoadMacroDefinition(
1796 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1797 assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1799 uint64_t Offset = Pos->second;
1800 UnreadMacroRecordOffsets.erase(Pos);
1802 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1803 if (Offset < Chain[I]->SizeInBits) {
1808 Offset -= Chain[I]->SizeInBits;
1811 Error("Malformed macro record offset");
1815 ReadMacroRecord(*F, Offset);
1818 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1819 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1820 = UnreadMacroRecordOffsets.find(II);
1821 LoadMacroDefinition(Pos);
1824 MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
1825 if (ID == 0 || ID > MacroDefinitionsLoaded.size())
1828 if (!MacroDefinitionsLoaded[ID - 1]) {
1829 unsigned Index = ID - 1;
1830 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1831 PerFileData &F = *Chain[N - I - 1];
1832 if (Index < F.LocalNumMacroDefinitions) {
1833 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
1834 F.PreprocessorDetailCursor.JumpToBit(F.MacroDefinitionOffsets[Index]);
1835 LoadPreprocessedEntity(F);
1838 Index -= F.LocalNumMacroDefinitions;
1840 assert(MacroDefinitionsLoaded[ID - 1] && "Broken chain");
1843 return MacroDefinitionsLoaded[ID - 1];
1846 const FileEntry *ASTReader::getFileEntry(llvm::StringRef filenameStrRef) {
1847 std::string Filename = filenameStrRef;
1848 MaybeAddSystemRootToFilename(Filename);
1849 const FileEntry *File = FileMgr.getFile(Filename);
1850 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1851 OriginalDir != CurrentDir) {
1852 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1855 if (!resolved.empty())
1856 File = FileMgr.getFile(resolved);
1862 /// \brief If we are loading a relocatable PCH file, and the filename is
1863 /// not an absolute path, add the system root to the beginning of the file
1865 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1866 // If this is not a relocatable PCH file, there's nothing to do.
1867 if (!RelocatablePCH)
1870 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1873 if (isysroot == 0) {
1874 // If no system root was given, default to '/'
1875 Filename.insert(Filename.begin(), '/');
1879 unsigned Length = strlen(isysroot);
1880 if (isysroot[Length - 1] != '/')
1881 Filename.insert(Filename.begin(), '/');
1883 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1886 ASTReader::ASTReadResult
1887 ASTReader::ReadASTBlock(PerFileData &F) {
1888 llvm::BitstreamCursor &Stream = F.Stream;
1890 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1891 Error("malformed block record in AST file");
1895 // Read all of the records and blocks for the ASt file.
1898 while (!Stream.AtEndOfStream()) {
1899 unsigned Code = Stream.ReadCode();
1900 if (Code == llvm::bitc::END_BLOCK) {
1901 if (Stream.ReadBlockEnd()) {
1902 Error("error at end of module block in AST file");
1909 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1910 switch (Stream.ReadSubBlockID()) {
1911 case DECLTYPES_BLOCK_ID:
1912 // We lazily load the decls block, but we want to set up the
1913 // DeclsCursor cursor to point into it. Clone our current bitcode
1914 // cursor to it, enter the block and read the abbrevs in that block.
1915 // With the main cursor, we just skip over it.
1916 F.DeclsCursor = Stream;
1917 if (Stream.SkipBlock() || // Skip with the main cursor.
1918 // Read the abbrevs.
1919 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1920 Error("malformed block record in AST file");
1925 case DECL_UPDATES_BLOCK_ID:
1926 if (Stream.SkipBlock()) {
1927 Error("malformed block record in AST file");
1932 case PREPROCESSOR_BLOCK_ID:
1933 F.MacroCursor = Stream;
1935 PP->setExternalSource(this);
1937 if (Stream.SkipBlock() ||
1938 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1939 Error("malformed block record in AST file");
1942 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1945 case PREPROCESSOR_DETAIL_BLOCK_ID:
1946 F.PreprocessorDetailCursor = Stream;
1947 if (Stream.SkipBlock() ||
1948 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1949 PREPROCESSOR_DETAIL_BLOCK_ID)) {
1950 Error("malformed preprocessor detail record in AST file");
1953 F.PreprocessorDetailStartOffset
1954 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1957 case SOURCE_MANAGER_BLOCK_ID:
1958 switch (ReadSourceManagerBlock(F)) {
1963 Error("malformed source manager block in AST file");
1975 if (Code == llvm::bitc::DEFINE_ABBREV) {
1976 Stream.ReadAbbrevRecord();
1980 // Read and process a record.
1982 const char *BlobStart = 0;
1983 unsigned BlobLen = 0;
1984 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1985 &BlobStart, &BlobLen)) {
1986 default: // Default behavior: ignore.
1990 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1991 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1992 : diag::warn_pch_version_too_new);
1996 RelocatablePCH = Record[4];
1998 std::string TargetTriple(BlobStart, BlobLen);
1999 if (Listener->ReadTargetTriple(TargetTriple))
2005 case CHAINED_METADATA: {
2007 Error("CHAINED_METADATA is not first record in block");
2010 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2011 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
2012 : diag::warn_pch_version_too_new);
2016 // Load the chained file, which is always a PCH file.
2017 switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen), PCH)) {
2018 case Failure: return Failure;
2019 // If we have to ignore the dependency, we'll have to ignore this too.
2020 case IgnorePCH: return IgnorePCH;
2021 case Success: break;
2027 if (F.LocalNumTypes != 0) {
2028 Error("duplicate TYPE_OFFSET record in AST file");
2031 F.TypeOffsets = (const uint32_t *)BlobStart;
2032 F.LocalNumTypes = Record[0];
2036 if (F.LocalNumDecls != 0) {
2037 Error("duplicate DECL_OFFSET record in AST file");
2040 F.DeclOffsets = (const uint32_t *)BlobStart;
2041 F.LocalNumDecls = Record[0];
2044 case TU_UPDATE_LEXICAL: {
2045 DeclContextInfo Info = {
2046 /* No visible information */ 0,
2047 reinterpret_cast<const KindDeclIDPair *>(BlobStart),
2048 BlobLen / sizeof(KindDeclIDPair)
2050 DeclContextOffsets[Context ? Context->getTranslationUnitDecl() : 0]
2055 case UPDATE_VISIBLE: {
2056 serialization::DeclID ID = Record[0];
2057 void *Table = ASTDeclContextNameLookupTable::Create(
2058 (const unsigned char *)BlobStart + Record[1],
2059 (const unsigned char *)BlobStart,
2060 ASTDeclContextNameLookupTrait(*this));
2061 if (ID == 1 && Context) { // Is it the TU?
2062 DeclContextInfo Info = {
2063 Table, /* No lexical inforamtion */ 0, 0
2065 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
2067 PendingVisibleUpdates[ID].push_back(Table);
2071 case REDECLS_UPDATE_LATEST: {
2072 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
2073 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
2074 DeclID First = Record[i], Latest = Record[i+1];
2075 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
2076 Latest > FirstLatestDeclIDs[First]) &&
2077 "The new latest is supposed to come after the previous latest");
2078 FirstLatestDeclIDs[First] = Latest;
2083 case LANGUAGE_OPTIONS:
2084 if (ParseLanguageOptions(Record) && !DisableValidation)
2088 case IDENTIFIER_TABLE:
2089 F.IdentifierTableData = BlobStart;
2091 F.IdentifierLookupTable
2092 = ASTIdentifierLookupTable::Create(
2093 (const unsigned char *)F.IdentifierTableData + Record[0],
2094 (const unsigned char *)F.IdentifierTableData,
2095 ASTIdentifierLookupTrait(*this, F));
2097 PP->getIdentifierTable().setExternalIdentifierLookup(this);
2101 case IDENTIFIER_OFFSET:
2102 if (F.LocalNumIdentifiers != 0) {
2103 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2106 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2107 F.LocalNumIdentifiers = Record[0];
2110 case EXTERNAL_DEFINITIONS:
2111 // Optimization for the first block.
2112 if (ExternalDefinitions.empty())
2113 ExternalDefinitions.swap(Record);
2115 ExternalDefinitions.insert(ExternalDefinitions.end(),
2116 Record.begin(), Record.end());
2120 // Optimization for the first block
2121 if (SpecialTypes.empty())
2122 SpecialTypes.swap(Record);
2124 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
2128 TotalNumStatements += Record[0];
2129 TotalNumMacros += Record[1];
2130 TotalLexicalDeclContexts += Record[2];
2131 TotalVisibleDeclContexts += Record[3];
2134 case UNUSED_FILESCOPED_DECLS:
2135 // Optimization for the first block.
2136 if (UnusedFileScopedDecls.empty())
2137 UnusedFileScopedDecls.swap(Record);
2139 UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(),
2140 Record.begin(), Record.end());
2143 case DELEGATING_CTORS:
2144 // Optimization for the first block.
2145 if (DelegatingCtorDecls.empty())
2146 DelegatingCtorDecls.swap(Record);
2148 DelegatingCtorDecls.insert(DelegatingCtorDecls.end(),
2149 Record.begin(), Record.end());
2152 case WEAK_UNDECLARED_IDENTIFIERS:
2153 // Later blocks overwrite earlier ones.
2154 WeakUndeclaredIdentifiers.swap(Record);
2157 case LOCALLY_SCOPED_EXTERNAL_DECLS:
2158 // Optimization for the first block.
2159 if (LocallyScopedExternalDecls.empty())
2160 LocallyScopedExternalDecls.swap(Record);
2162 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
2163 Record.begin(), Record.end());
2166 case SELECTOR_OFFSETS:
2167 F.SelectorOffsets = (const uint32_t *)BlobStart;
2168 F.LocalNumSelectors = Record[0];
2172 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2174 F.SelectorLookupTable
2175 = ASTSelectorLookupTable::Create(
2176 F.SelectorLookupTableData + Record[0],
2177 F.SelectorLookupTableData,
2178 ASTSelectorLookupTrait(*this));
2179 TotalNumMethodPoolEntries += Record[1];
2182 case REFERENCED_SELECTOR_POOL:
2183 F.ReferencedSelectorsData.swap(Record);
2186 case PP_COUNTER_VALUE:
2187 if (!Record.empty() && Listener)
2188 Listener->ReadCounter(Record[0]);
2191 case SOURCE_LOCATION_OFFSETS:
2192 F.SLocOffsets = (const uint32_t *)BlobStart;
2193 F.LocalNumSLocEntries = Record[0];
2194 F.LocalSLocSize = Record[1];
2197 case FILE_SOURCE_LOCATION_OFFSETS:
2198 F.SLocFileOffsets = (const uint32_t *)BlobStart;
2199 F.LocalNumSLocFileEntries = Record[0];
2202 case SOURCE_LOCATION_PRELOADS:
2203 if (PreloadSLocEntries.empty())
2204 PreloadSLocEntries.swap(Record);
2206 PreloadSLocEntries.insert(PreloadSLocEntries.end(),
2207 Record.begin(), Record.end());
2211 if (!DisableStatCache) {
2212 ASTStatCache *MyStatCache =
2213 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2214 (const unsigned char *)BlobStart,
2215 NumStatHits, NumStatMisses);
2216 FileMgr.addStatCache(MyStatCache);
2217 F.StatCache = MyStatCache;
2222 case EXT_VECTOR_DECLS:
2223 // Optimization for the first block.
2224 if (ExtVectorDecls.empty())
2225 ExtVectorDecls.swap(Record);
2227 ExtVectorDecls.insert(ExtVectorDecls.end(),
2228 Record.begin(), Record.end());
2232 // Later tables overwrite earlier ones.
2233 VTableUses.swap(Record);
2236 case DYNAMIC_CLASSES:
2237 // Optimization for the first block.
2238 if (DynamicClasses.empty())
2239 DynamicClasses.swap(Record);
2241 DynamicClasses.insert(DynamicClasses.end(),
2242 Record.begin(), Record.end());
2245 case PENDING_IMPLICIT_INSTANTIATIONS:
2246 F.PendingInstantiations.swap(Record);
2249 case SEMA_DECL_REFS:
2250 // Later tables overwrite earlier ones.
2251 SemaDeclRefs.swap(Record);
2254 case ORIGINAL_FILE_NAME:
2255 // The primary AST will be the last to get here, so it will be the one
2257 ActualOriginalFileName.assign(BlobStart, BlobLen);
2258 OriginalFileName = ActualOriginalFileName;
2259 MaybeAddSystemRootToFilename(OriginalFileName);
2262 case ORIGINAL_FILE_ID:
2263 OriginalFileID = FileID::get(Record[0]);
2266 case ORIGINAL_PCH_DIR:
2267 // The primary AST will be the last to get here, so it will be the one
2269 OriginalDir.assign(BlobStart, BlobLen);
2272 case VERSION_CONTROL_BRANCH_REVISION: {
2273 const std::string &CurBranch = getClangFullRepositoryVersion();
2274 llvm::StringRef ASTBranch(BlobStart, BlobLen);
2275 if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2276 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2282 case MACRO_DEFINITION_OFFSETS:
2283 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
2284 F.NumPreallocatedPreprocessingEntities = Record[0];
2285 F.LocalNumMacroDefinitions = Record[1];
2288 case DECL_UPDATE_OFFSETS: {
2289 if (Record.size() % 2 != 0) {
2290 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2293 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2294 DeclUpdateOffsets[static_cast<DeclID>(Record[I])]
2295 .push_back(std::make_pair(&F, Record[I+1]));
2299 case DECL_REPLACEMENTS: {
2300 if (Record.size() % 2 != 0) {
2301 Error("invalid DECL_REPLACEMENTS block in AST file");
2304 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2305 ReplacedDecls[static_cast<DeclID>(Record[I])] =
2306 std::make_pair(&F, Record[I+1]);
2310 case CXX_BASE_SPECIFIER_OFFSETS: {
2311 if (F.LocalNumCXXBaseSpecifiers != 0) {
2312 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2316 F.LocalNumCXXBaseSpecifiers = Record[0];
2317 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2321 case DIAG_PRAGMA_MAPPINGS:
2322 if (Record.size() % 2 != 0) {
2323 Error("invalid DIAG_USER_MAPPINGS block in AST file");
2326 if (PragmaDiagMappings.empty())
2327 PragmaDiagMappings.swap(Record);
2329 PragmaDiagMappings.insert(PragmaDiagMappings.end(),
2330 Record.begin(), Record.end());
2333 case CUDA_SPECIAL_DECL_REFS:
2334 // Later tables overwrite earlier ones.
2335 CUDASpecialDeclRefs.swap(Record);
2338 case HEADER_SEARCH_TABLE:
2339 F.HeaderFileInfoTableData = BlobStart;
2340 F.LocalNumHeaderFileInfos = Record[1];
2342 F.HeaderFileInfoTable
2343 = HeaderFileInfoLookupTable::Create(
2344 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2345 (const unsigned char *)F.HeaderFileInfoTableData);
2347 PP->getHeaderSearchInfo().SetExternalSource(this);
2351 case FP_PRAGMA_OPTIONS:
2352 // Later tables overwrite earlier ones.
2353 FPPragmaOptions.swap(Record);
2356 case OPENCL_EXTENSIONS:
2357 // Later tables overwrite earlier ones.
2358 OpenCLExtensions.swap(Record);
2361 case TENTATIVE_DEFINITIONS:
2362 // Optimization for the first block.
2363 if (TentativeDefinitions.empty())
2364 TentativeDefinitions.swap(Record);
2366 TentativeDefinitions.insert(TentativeDefinitions.end(),
2367 Record.begin(), Record.end());
2372 Error("premature end of bitstream in AST file");
2376 ASTReader::ASTReadResult ASTReader::validateFileEntries() {
2377 for (unsigned CI = 0, CN = Chain.size(); CI != CN; ++CI) {
2378 PerFileData *F = Chain[CI];
2379 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
2381 for (unsigned i = 0, e = F->LocalNumSLocFileEntries; i != e; ++i) {
2382 SLocEntryCursor.JumpToBit(F->SLocFileOffsets[i]);
2383 unsigned Code = SLocEntryCursor.ReadCode();
2384 if (Code == llvm::bitc::END_BLOCK ||
2385 Code == llvm::bitc::ENTER_SUBBLOCK ||
2386 Code == llvm::bitc::DEFINE_ABBREV) {
2387 Error("incorrectly-formatted source location entry in AST file");
2392 const char *BlobStart;
2394 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
2396 Error("incorrectly-formatted source location entry in AST file");
2399 case SM_SLOC_FILE_ENTRY: {
2400 llvm::StringRef Filename(BlobStart, BlobLen);
2401 const FileEntry *File = getFileEntry(Filename);
2404 std::string ErrorStr = "could not find file '";
2405 ErrorStr += Filename;
2406 ErrorStr += "' referenced by AST file";
2407 Error(ErrorStr.c_str());
2411 if (Record.size() < 6) {
2412 Error("source location entry is incorrect");
2416 // The stat info from the FileEntry came from the cached stat
2417 // info of the PCH, so we cannot trust it.
2418 struct stat StatBuf;
2419 if (::stat(File->getName(), &StatBuf) != 0) {
2420 StatBuf.st_size = File->getSize();
2421 StatBuf.st_mtime = File->getModificationTime();
2424 if (((off_t)Record[4] != StatBuf.st_size
2425 #if !defined(LLVM_ON_WIN32)
2426 // In our regression testing, the Windows file system seems to
2427 // have inconsistent modification times that sometimes
2428 // erroneously trigger this error-handling path.
2429 || (time_t)Record[5] != StatBuf.st_mtime
2432 Error(diag::err_fe_pch_file_modified, Filename);
2445 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2447 switch(ReadASTCore(FileName, Type)) {
2448 case Failure: return Failure;
2449 case IgnorePCH: return IgnorePCH;
2450 case Success: break;
2453 // Here comes stuff that we only do once the entire chain is loaded.
2455 if (!DisableValidation) {
2456 switch(validateFileEntries()) {
2457 case Failure: return Failure;
2458 case IgnorePCH: return IgnorePCH;
2459 case Success: break;
2463 // Allocate space for loaded slocentries, identifiers, decls and types.
2464 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
2465 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
2466 TotalNumSelectors = 0;
2467 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2468 TotalNumSLocEntries += Chain[I]->LocalNumSLocEntries;
2469 NextSLocOffset += Chain[I]->LocalSLocSize;
2470 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
2471 TotalNumTypes += Chain[I]->LocalNumTypes;
2472 TotalNumDecls += Chain[I]->LocalNumDecls;
2473 TotalNumPreallocatedPreprocessingEntities +=
2474 Chain[I]->NumPreallocatedPreprocessingEntities;
2475 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
2476 TotalNumSelectors += Chain[I]->LocalNumSelectors;
2478 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, NextSLocOffset);
2479 IdentifiersLoaded.resize(TotalNumIdentifiers);
2480 TypesLoaded.resize(TotalNumTypes);
2481 DeclsLoaded.resize(TotalNumDecls);
2482 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
2484 if (TotalNumIdentifiers > 0)
2485 PP->getHeaderSearchInfo().SetExternalLookup(this);
2486 if (TotalNumPreallocatedPreprocessingEntities > 0) {
2487 if (!PP->getPreprocessingRecord())
2488 PP->createPreprocessingRecord(true);
2489 PP->getPreprocessingRecord()->SetExternalSource(*this,
2490 TotalNumPreallocatedPreprocessingEntities);
2493 SelectorsLoaded.resize(TotalNumSelectors);
2494 // Preload SLocEntries.
2495 for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) {
2496 ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]);
2497 if (Result != Success)
2501 // Check the predefines buffers.
2502 if (!DisableValidation && CheckPredefinesBuffers())
2506 // Initialization of keywords and pragmas occurs before the
2507 // AST file is read, so there may be some identifiers that were
2508 // loaded into the IdentifierTable before we intercepted the
2509 // creation of identifiers. Iterate through the list of known
2510 // identifiers and determine whether we have to establish
2511 // preprocessor definitions or top-level identifier declaration
2512 // chains for those identifiers.
2514 // We copy the IdentifierInfo pointers to a small vector first,
2515 // since de-serializing declarations or macro definitions can add
2516 // new entries into the identifier table, invalidating the
2518 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
2519 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
2520 IdEnd = PP->getIdentifierTable().end();
2522 Identifiers.push_back(Id->second);
2523 // We need to search the tables in all files.
2524 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
2525 ASTIdentifierLookupTable *IdTable
2526 = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
2527 // Not all AST files necessarily have identifier tables, only the useful
2531 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2532 IdentifierInfo *II = Identifiers[I];
2533 // Look in the on-disk hash tables for an entry for this identifier
2534 ASTIdentifierLookupTrait Info(*this, *Chain[J], II);
2535 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
2536 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
2537 if (Pos == IdTable->end())
2540 // Dereferencing the iterator has the effect of populating the
2541 // IdentifierInfo node with the various declarations it needs.
2548 InitializeContext(*Context);
2550 if (DeserializationListener)
2551 DeserializationListener->ReaderInitialized(this);
2553 // If this AST file is a precompiled preamble, then set the main file ID of
2554 // the source manager to the file source file from which the preamble was
2555 // built. This is the only valid way to use a precompiled preamble.
2556 if (Type == Preamble) {
2557 if (OriginalFileID.isInvalid()) {
2559 = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1);
2561 OriginalFileID = SourceMgr.getDecomposedLoc(Loc).first;
2564 if (!OriginalFileID.isInvalid())
2565 SourceMgr.SetPreambleFileID(OriginalFileID);
2571 ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName,
2573 PerFileData *Prev = Chain.empty() ? 0 : Chain.back();
2574 Chain.push_back(new PerFileData(Type));
2575 PerFileData &F = *Chain.back();
2577 Prev->NextInSource = &F;
2580 F.Loaders.push_back(Prev);
2582 // Set the AST file name.
2583 F.FileName = FileName;
2585 if (FileName != "-") {
2586 CurrentDir = llvm::sys::path::parent_path(FileName);
2587 if (CurrentDir.empty()) CurrentDir = ".";
2590 if (!ASTBuffers.empty()) {
2591 F.Buffer.reset(ASTBuffers.back());
2592 ASTBuffers.pop_back();
2593 assert(F.Buffer && "Passed null buffer");
2595 // Open the AST file.
2597 // FIXME: This shouldn't be here, we should just take a raw_ostream.
2599 llvm::error_code ec;
2600 if (FileName == "-") {
2601 ec = llvm::MemoryBuffer::getSTDIN(F.Buffer);
2603 ErrStr = ec.message();
2605 F.Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrStr));
2607 Error(ErrStr.c_str());
2612 // Initialize the stream
2613 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
2614 (const unsigned char *)F.Buffer->getBufferEnd());
2615 llvm::BitstreamCursor &Stream = F.Stream;
2616 Stream.init(F.StreamFile);
2617 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2619 // Sniff for the signature.
2620 if (Stream.Read(8) != 'C' ||
2621 Stream.Read(8) != 'P' ||
2622 Stream.Read(8) != 'C' ||
2623 Stream.Read(8) != 'H') {
2624 Diag(diag::err_not_a_pch_file) << FileName;
2628 while (!Stream.AtEndOfStream()) {
2629 unsigned Code = Stream.ReadCode();
2631 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2632 Error("invalid record at top-level of AST file");
2636 unsigned BlockID = Stream.ReadSubBlockID();
2638 // We only know the AST subblock ID.
2640 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2641 if (Stream.ReadBlockInfoBlock()) {
2642 Error("malformed BlockInfoBlock in AST file");
2647 switch (ReadASTBlock(F)) {
2655 // FIXME: We could consider reading through to the end of this
2656 // AST block, skipping subblocks, to see if there are other
2657 // AST blocks elsewhere.
2659 // Clear out any preallocated source location entries, so that
2660 // the source manager does not try to resolve them later.
2661 SourceMgr.ClearPreallocatedSLocEntries();
2663 // Remove the stat cache.
2665 FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2671 if (Stream.SkipBlock()) {
2672 Error("malformed block record in AST file");
2682 void ASTReader::setPreprocessor(Preprocessor &pp) {
2685 unsigned TotalNum = 0;
2686 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
2687 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
2689 if (!PP->getPreprocessingRecord())
2690 PP->createPreprocessingRecord(true);
2691 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
2695 void ASTReader::InitializeContext(ASTContext &Ctx) {
2697 assert(Context && "Passed null context!");
2699 assert(PP && "Forgot to set Preprocessor ?");
2700 PP->getIdentifierTable().setExternalIdentifierLookup(this);
2701 PP->getHeaderSearchInfo().SetExternalLookup(this);
2702 PP->setExternalSource(this);
2703 PP->getHeaderSearchInfo().SetExternalSource(this);
2705 // If we have an update block for the TU waiting, we have to add it before
2706 // deserializing the decl.
2707 DeclContextOffsetsMap::iterator DCU = DeclContextOffsets.find(0);
2708 if (DCU != DeclContextOffsets.end()) {
2709 // Insertion could invalidate map, so grab vector.
2711 T.swap(DCU->second);
2712 DeclContextOffsets.erase(DCU);
2713 DeclContextOffsets[Ctx.getTranslationUnitDecl()].swap(T);
2716 // Load the translation unit declaration
2717 GetTranslationUnitDecl();
2719 // Load the special types.
2720 Context->setBuiltinVaListType(
2721 GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2722 if (unsigned Id = SpecialTypes[SPECIAL_TYPE_OBJC_ID])
2723 Context->setObjCIdType(GetType(Id));
2724 if (unsigned Sel = SpecialTypes[SPECIAL_TYPE_OBJC_SELECTOR])
2725 Context->setObjCSelType(GetType(Sel));
2726 if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL])
2727 Context->setObjCProtoType(GetType(Proto));
2728 if (unsigned Class = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS])
2729 Context->setObjCClassType(GetType(Class));
2731 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING])
2732 Context->setCFConstantStringType(GetType(String));
2733 if (unsigned FastEnum
2734 = SpecialTypes[SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2735 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
2736 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2737 QualType FileType = GetType(File);
2738 if (FileType.isNull()) {
2739 Error("FILE type is NULL");
2742 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2743 Context->setFILEDecl(Typedef->getDecl());
2745 const TagType *Tag = FileType->getAs<TagType>();
2747 Error("Invalid FILE type in AST file");
2750 Context->setFILEDecl(Tag->getDecl());
2753 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2754 QualType Jmp_bufType = GetType(Jmp_buf);
2755 if (Jmp_bufType.isNull()) {
2756 Error("jmp_bug type is NULL");
2759 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2760 Context->setjmp_bufDecl(Typedef->getDecl());
2762 const TagType *Tag = Jmp_bufType->getAs<TagType>();
2764 Error("Invalid jmp_buf type in AST file");
2767 Context->setjmp_bufDecl(Tag->getDecl());
2770 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2771 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2772 if (Sigjmp_bufType.isNull()) {
2773 Error("sigjmp_buf type is NULL");
2776 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2777 Context->setsigjmp_bufDecl(Typedef->getDecl());
2779 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2780 assert(Tag && "Invalid sigjmp_buf type in AST file");
2781 Context->setsigjmp_bufDecl(Tag->getDecl());
2784 if (unsigned ObjCIdRedef
2785 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2786 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2787 if (unsigned ObjCClassRedef
2788 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2789 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2790 if (unsigned String = SpecialTypes[SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2791 Context->setBlockDescriptorType(GetType(String));
2793 = SpecialTypes[SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2794 Context->setBlockDescriptorExtendedType(GetType(String));
2795 if (unsigned ObjCSelRedef
2796 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2797 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2798 if (unsigned String = SpecialTypes[SPECIAL_TYPE_NS_CONSTANT_STRING])
2799 Context->setNSConstantStringType(GetType(String));
2801 if (SpecialTypes[SPECIAL_TYPE_INT128_INSTALLED])
2802 Context->setInt128Installed();
2804 if (unsigned AutoDeduct = SpecialTypes[SPECIAL_TYPE_AUTO_DEDUCT])
2805 Context->AutoDeductTy = GetType(AutoDeduct);
2806 if (unsigned AutoRRefDeduct = SpecialTypes[SPECIAL_TYPE_AUTO_RREF_DEDUCT])
2807 Context->AutoRRefDeductTy = GetType(AutoRRefDeduct);
2809 ReadPragmaDiagnosticMappings(Context->getDiagnostics());
2811 // If there were any CUDA special declarations, deserialize them.
2812 if (!CUDASpecialDeclRefs.empty()) {
2813 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2814 Context->setcudaConfigureCallDecl(
2815 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2819 /// \brief Retrieve the name of the original source file name
2820 /// directly from the AST file, without actually loading the AST
2822 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2823 FileManager &FileMgr,
2824 Diagnostic &Diags) {
2825 // Open the AST file.
2827 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2828 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2830 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2831 return std::string();
2834 // Initialize the stream
2835 llvm::BitstreamReader StreamFile;
2836 llvm::BitstreamCursor Stream;
2837 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2838 (const unsigned char *)Buffer->getBufferEnd());
2839 Stream.init(StreamFile);
2841 // Sniff for the signature.
2842 if (Stream.Read(8) != 'C' ||
2843 Stream.Read(8) != 'P' ||
2844 Stream.Read(8) != 'C' ||
2845 Stream.Read(8) != 'H') {
2846 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2847 return std::string();
2851 while (!Stream.AtEndOfStream()) {
2852 unsigned Code = Stream.ReadCode();
2854 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2855 unsigned BlockID = Stream.ReadSubBlockID();
2857 // We only know the AST subblock ID.
2860 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2861 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2862 return std::string();
2867 if (Stream.SkipBlock()) {
2868 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2869 return std::string();
2876 if (Code == llvm::bitc::END_BLOCK) {
2877 if (Stream.ReadBlockEnd()) {
2878 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2879 return std::string();
2884 if (Code == llvm::bitc::DEFINE_ABBREV) {
2885 Stream.ReadAbbrevRecord();
2890 const char *BlobStart = 0;
2891 unsigned BlobLen = 0;
2892 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2893 == ORIGINAL_FILE_NAME)
2894 return std::string(BlobStart, BlobLen);
2897 return std::string();
2900 /// \brief Parse the record that corresponds to a LangOptions data
2903 /// This routine parses the language options from the AST file and then gives
2904 /// them to the AST listener if one is set.
2906 /// \returns true if the listener deems the file unacceptable, false otherwise.
2907 bool ASTReader::ParseLanguageOptions(
2908 const llvm::SmallVectorImpl<uint64_t> &Record) {
2910 LangOptions LangOpts;
2912 #define PARSE_LANGOPT(Option) \
2913 LangOpts.Option = Record[Idx]; \
2917 PARSE_LANGOPT(Trigraphs);
2918 PARSE_LANGOPT(BCPLComment);
2919 PARSE_LANGOPT(DollarIdents);
2920 PARSE_LANGOPT(AsmPreprocessor);
2921 PARSE_LANGOPT(GNUMode);
2922 PARSE_LANGOPT(GNUKeywords);
2923 PARSE_LANGOPT(ImplicitInt);
2924 PARSE_LANGOPT(Digraphs);
2925 PARSE_LANGOPT(HexFloats);
2928 PARSE_LANGOPT(Microsoft);
2929 PARSE_LANGOPT(CPlusPlus);
2930 PARSE_LANGOPT(CPlusPlus0x);
2931 PARSE_LANGOPT(CXXOperatorNames);
2932 PARSE_LANGOPT(ObjC1);
2933 PARSE_LANGOPT(ObjC2);
2934 PARSE_LANGOPT(ObjCNonFragileABI);
2935 PARSE_LANGOPT(ObjCNonFragileABI2);
2936 PARSE_LANGOPT(AppleKext);
2937 PARSE_LANGOPT(ObjCDefaultSynthProperties);
2938 PARSE_LANGOPT(ObjCInferRelatedResultType);
2939 PARSE_LANGOPT(NoConstantCFStrings);
2940 PARSE_LANGOPT(PascalStrings);
2941 PARSE_LANGOPT(WritableStrings);
2942 PARSE_LANGOPT(LaxVectorConversions);
2943 PARSE_LANGOPT(AltiVec);
2944 PARSE_LANGOPT(Exceptions);
2945 PARSE_LANGOPT(ObjCExceptions);
2946 PARSE_LANGOPT(CXXExceptions);
2947 PARSE_LANGOPT(SjLjExceptions);
2948 PARSE_LANGOPT(MSBitfields);
2949 PARSE_LANGOPT(NeXTRuntime);
2950 PARSE_LANGOPT(Freestanding);
2951 PARSE_LANGOPT(NoBuiltin);
2952 PARSE_LANGOPT(ThreadsafeStatics);
2953 PARSE_LANGOPT(POSIXThreads);
2954 PARSE_LANGOPT(Blocks);
2955 PARSE_LANGOPT(EmitAllDecls);
2956 PARSE_LANGOPT(MathErrno);
2957 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2959 PARSE_LANGOPT(HeinousExtensions);
2960 PARSE_LANGOPT(Optimize);
2961 PARSE_LANGOPT(OptimizeSize);
2962 PARSE_LANGOPT(Static);
2963 PARSE_LANGOPT(PICLevel);
2964 PARSE_LANGOPT(GNUInline);
2965 PARSE_LANGOPT(NoInline);
2966 PARSE_LANGOPT(Deprecated);
2967 PARSE_LANGOPT(AccessControl);
2968 PARSE_LANGOPT(CharIsSigned);
2969 PARSE_LANGOPT(ShortWChar);
2970 PARSE_LANGOPT(ShortEnums);
2971 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2972 LangOpts.setVisibilityMode((Visibility)Record[Idx++]);
2973 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
2975 PARSE_LANGOPT(InstantiationDepth);
2976 PARSE_LANGOPT(OpenCL);
2977 PARSE_LANGOPT(CUDA);
2978 PARSE_LANGOPT(CatchUndefined);
2979 PARSE_LANGOPT(DefaultFPContract);
2980 PARSE_LANGOPT(ElideConstructors);
2981 PARSE_LANGOPT(SpellChecking);
2982 PARSE_LANGOPT(MRTD);
2983 #undef PARSE_LANGOPT
2985 return Listener->ReadLanguageOptions(LangOpts);
2991 void ASTReader::ReadPreprocessedEntities() {
2992 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2993 PerFileData &F = *Chain[I];
2994 if (!F.PreprocessorDetailCursor.getBitStreamReader())
2997 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
2998 F.PreprocessorDetailCursor.JumpToBit(F.PreprocessorDetailStartOffset);
2999 while (LoadPreprocessedEntity(F)) { }
3003 PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) {
3005 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3006 if (Offset < Chain[I]->SizeInBits) {
3011 Offset -= Chain[I]->SizeInBits;
3015 Error("Malformed preprocessed entity offset");
3019 // Keep track of where we are in the stream, then jump back there
3020 // after reading this entity.
3021 SavedStreamPosition SavedPosition(F->PreprocessorDetailCursor);
3022 F->PreprocessorDetailCursor.JumpToBit(Offset);
3023 return LoadPreprocessedEntity(*F);
3026 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
3027 HeaderFileInfoTrait Trait(FE->getName());
3028 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3029 PerFileData &F = *Chain[I];
3030 HeaderFileInfoLookupTable *Table
3031 = static_cast<HeaderFileInfoLookupTable *>(F.HeaderFileInfoTable);
3035 // Look in the on-disk hash table for an entry for this file name.
3036 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE->getName(),
3038 if (Pos == Table->end())
3041 HeaderFileInfo HFI = *Pos;
3043 Listener->ReadHeaderFileInfo(HFI, FE->getUID());
3048 return HeaderFileInfo();
3051 void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) {
3053 while (Idx < PragmaDiagMappings.size()) {
3055 Loc = SourceLocation::getFromRawEncoding(PragmaDiagMappings[Idx++]);
3057 assert(Idx < PragmaDiagMappings.size() &&
3058 "Invalid data, didn't find '-1' marking end of diag/map pairs");
3059 if (Idx >= PragmaDiagMappings.size())
3060 break; // Something is messed up but at least avoid infinite loop in
3062 unsigned DiagID = PragmaDiagMappings[Idx++];
3063 if (DiagID == (unsigned)-1)
3064 break; // no more diag/map pairs for this location.
3065 diag::Mapping Map = (diag::Mapping)PragmaDiagMappings[Idx++];
3066 Diag.setDiagnosticMapping(DiagID, Map, Loc);
3071 /// \brief Get the correct cursor and offset for loading a type.
3072 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
3074 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3075 F = Chain[N - I - 1];
3076 if (Index < F->LocalNumTypes)
3078 Index -= F->LocalNumTypes;
3080 assert(F && F->LocalNumTypes > Index && "Broken chain");
3081 return RecordLocation(F, F->TypeOffsets[Index]);
3084 /// \brief Read and return the type with the given index..
3086 /// The index is the type ID, shifted and minus the number of predefs. This
3087 /// routine actually reads the record corresponding to the type at the given
3088 /// location. It is a helper routine for GetType, which deals with reading type
3090 QualType ASTReader::ReadTypeRecord(unsigned Index) {
3091 RecordLocation Loc = TypeCursorForIndex(Index);
3092 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3094 // Keep track of where we are in the stream, then jump back there
3095 // after reading this type.
3096 SavedStreamPosition SavedPosition(DeclsCursor);
3098 ReadingKindTracker ReadingKind(Read_Type, *this);
3100 // Note that we are loading a type record.
3101 Deserializing AType(this);
3103 DeclsCursor.JumpToBit(Loc.Offset);
3105 unsigned Code = DeclsCursor.ReadCode();
3106 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
3107 case TYPE_EXT_QUAL: {
3108 if (Record.size() != 2) {
3109 Error("Incorrect encoding of extended qualifier type");
3112 QualType Base = GetType(Record[0]);
3113 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
3114 return Context->getQualifiedType(Base, Quals);
3117 case TYPE_COMPLEX: {
3118 if (Record.size() != 1) {
3119 Error("Incorrect encoding of complex type");
3122 QualType ElemType = GetType(Record[0]);
3123 return Context->getComplexType(ElemType);
3126 case TYPE_POINTER: {
3127 if (Record.size() != 1) {
3128 Error("Incorrect encoding of pointer type");
3131 QualType PointeeType = GetType(Record[0]);
3132 return Context->getPointerType(PointeeType);
3135 case TYPE_BLOCK_POINTER: {
3136 if (Record.size() != 1) {
3137 Error("Incorrect encoding of block pointer type");
3140 QualType PointeeType = GetType(Record[0]);
3141 return Context->getBlockPointerType(PointeeType);
3144 case TYPE_LVALUE_REFERENCE: {
3145 if (Record.size() != 2) {
3146 Error("Incorrect encoding of lvalue reference type");
3149 QualType PointeeType = GetType(Record[0]);
3150 return Context->getLValueReferenceType(PointeeType, Record[1]);
3153 case TYPE_RVALUE_REFERENCE: {
3154 if (Record.size() != 1) {
3155 Error("Incorrect encoding of rvalue reference type");
3158 QualType PointeeType = GetType(Record[0]);
3159 return Context->getRValueReferenceType(PointeeType);
3162 case TYPE_MEMBER_POINTER: {
3163 if (Record.size() != 2) {
3164 Error("Incorrect encoding of member pointer type");
3167 QualType PointeeType = GetType(Record[0]);
3168 QualType ClassType = GetType(Record[1]);
3169 if (PointeeType.isNull() || ClassType.isNull())
3172 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
3175 case TYPE_CONSTANT_ARRAY: {
3176 QualType ElementType = GetType(Record[0]);
3177 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3178 unsigned IndexTypeQuals = Record[2];
3180 llvm::APInt Size = ReadAPInt(Record, Idx);
3181 return Context->getConstantArrayType(ElementType, Size,
3182 ASM, IndexTypeQuals);
3185 case TYPE_INCOMPLETE_ARRAY: {
3186 QualType ElementType = GetType(Record[0]);
3187 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3188 unsigned IndexTypeQuals = Record[2];
3189 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3192 case TYPE_VARIABLE_ARRAY: {
3193 QualType ElementType = GetType(Record[0]);
3194 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3195 unsigned IndexTypeQuals = Record[2];
3196 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3197 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3198 return Context->getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3199 ASM, IndexTypeQuals,
3200 SourceRange(LBLoc, RBLoc));
3204 if (Record.size() != 3) {
3205 Error("incorrect encoding of vector type in AST file");
3209 QualType ElementType = GetType(Record[0]);
3210 unsigned NumElements = Record[1];
3211 unsigned VecKind = Record[2];
3212 return Context->getVectorType(ElementType, NumElements,
3213 (VectorType::VectorKind)VecKind);
3216 case TYPE_EXT_VECTOR: {
3217 if (Record.size() != 3) {
3218 Error("incorrect encoding of extended vector type in AST file");
3222 QualType ElementType = GetType(Record[0]);
3223 unsigned NumElements = Record[1];
3224 return Context->getExtVectorType(ElementType, NumElements);
3227 case TYPE_FUNCTION_NO_PROTO: {
3228 if (Record.size() != 5) {
3229 Error("incorrect encoding of no-proto function type");
3232 QualType ResultType = GetType(Record[0]);
3233 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], (CallingConv)Record[4]);
3234 return Context->getFunctionNoProtoType(ResultType, Info);
3237 case TYPE_FUNCTION_PROTO: {
3238 QualType ResultType = GetType(Record[0]);
3240 FunctionProtoType::ExtProtoInfo EPI;
3241 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3242 /*hasregparm*/ Record[2],
3243 /*regparm*/ Record[3],
3244 static_cast<CallingConv>(Record[4]));
3247 unsigned NumParams = Record[Idx++];
3248 llvm::SmallVector<QualType, 16> ParamTypes;
3249 for (unsigned I = 0; I != NumParams; ++I)
3250 ParamTypes.push_back(GetType(Record[Idx++]));
3252 EPI.Variadic = Record[Idx++];
3253 EPI.TypeQuals = Record[Idx++];
3254 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3255 ExceptionSpecificationType EST =
3256 static_cast<ExceptionSpecificationType>(Record[Idx++]);
3257 EPI.ExceptionSpecType = EST;
3258 if (EST == EST_Dynamic) {
3259 EPI.NumExceptions = Record[Idx++];
3260 llvm::SmallVector<QualType, 2> Exceptions;
3261 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3262 Exceptions.push_back(GetType(Record[Idx++]));
3263 EPI.Exceptions = Exceptions.data();
3264 } else if (EST == EST_ComputedNoexcept) {
3265 EPI.NoexceptExpr = ReadExpr(*Loc.F);
3267 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
3271 case TYPE_UNRESOLVED_USING:
3272 return Context->getTypeDeclType(
3273 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
3275 case TYPE_TYPEDEF: {
3276 if (Record.size() != 2) {
3277 Error("incorrect encoding of typedef type");
3280 TypedefNameDecl *Decl = cast<TypedefNameDecl>(GetDecl(Record[0]));
3281 QualType Canonical = GetType(Record[1]);
3282 if (!Canonical.isNull())
3283 Canonical = Context->getCanonicalType(Canonical);
3284 return Context->getTypedefType(Decl, Canonical);
3287 case TYPE_TYPEOF_EXPR:
3288 return Context->getTypeOfExprType(ReadExpr(*Loc.F));
3291 if (Record.size() != 1) {
3292 Error("incorrect encoding of typeof(type) in AST file");
3295 QualType UnderlyingType = GetType(Record[0]);
3296 return Context->getTypeOfType(UnderlyingType);
3300 return Context->getDecltypeType(ReadExpr(*Loc.F));
3302 case TYPE_UNARY_TRANSFORM: {
3303 QualType BaseType = GetType(Record[0]);
3304 QualType UnderlyingType = GetType(Record[1]);
3305 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
3306 return Context->getUnaryTransformType(BaseType, UnderlyingType, UKind);
3310 return Context->getAutoType(GetType(Record[0]));
3313 if (Record.size() != 2) {
3314 Error("incorrect encoding of record type");
3317 bool IsDependent = Record[0];
3318 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
3319 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3324 if (Record.size() != 2) {
3325 Error("incorrect encoding of enum type");
3328 bool IsDependent = Record[0];
3329 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
3330 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3334 case TYPE_ATTRIBUTED: {
3335 if (Record.size() != 3) {
3336 Error("incorrect encoding of attributed type");
3339 QualType modifiedType = GetType(Record[0]);
3340 QualType equivalentType = GetType(Record[1]);
3341 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3342 return Context->getAttributedType(kind, modifiedType, equivalentType);
3346 if (Record.size() != 1) {
3347 Error("incorrect encoding of paren type");
3350 QualType InnerType = GetType(Record[0]);
3351 return Context->getParenType(InnerType);
3354 case TYPE_PACK_EXPANSION: {
3355 if (Record.size() != 2) {
3356 Error("incorrect encoding of pack expansion type");
3359 QualType Pattern = GetType(Record[0]);
3360 if (Pattern.isNull())
3362 llvm::Optional<unsigned> NumExpansions;
3364 NumExpansions = Record[1] - 1;
3365 return Context->getPackExpansionType(Pattern, NumExpansions);
3368 case TYPE_ELABORATED: {
3370 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3371 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3372 QualType NamedType = GetType(Record[Idx++]);
3373 return Context->getElaboratedType(Keyword, NNS, NamedType);
3376 case TYPE_OBJC_INTERFACE: {
3378 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
3379 return Context->getObjCInterfaceType(ItfD);
3382 case TYPE_OBJC_OBJECT: {
3384 QualType Base = GetType(Record[Idx++]);
3385 unsigned NumProtos = Record[Idx++];
3386 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
3387 for (unsigned I = 0; I != NumProtos; ++I)
3388 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
3389 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
3392 case TYPE_OBJC_OBJECT_POINTER: {
3394 QualType Pointee = GetType(Record[Idx++]);
3395 return Context->getObjCObjectPointerType(Pointee);
3398 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3400 QualType Parm = GetType(Record[Idx++]);
3401 QualType Replacement = GetType(Record[Idx++]);
3403 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3407 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3409 QualType Parm = GetType(Record[Idx++]);
3410 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3411 return Context->getSubstTemplateTypeParmPackType(
3412 cast<TemplateTypeParmType>(Parm),
3416 case TYPE_INJECTED_CLASS_NAME: {
3417 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
3418 QualType TST = GetType(Record[1]); // probably derivable
3419 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3420 // for AST reading, too much interdependencies.
3422 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3425 case TYPE_TEMPLATE_TYPE_PARM: {
3427 unsigned Depth = Record[Idx++];
3428 unsigned Index = Record[Idx++];
3429 bool Pack = Record[Idx++];
3430 TemplateTypeParmDecl *D =
3431 cast_or_null<TemplateTypeParmDecl>(GetDecl(Record[Idx++]));
3432 return Context->getTemplateTypeParmType(Depth, Index, Pack, D);
3435 case TYPE_DEPENDENT_NAME: {
3437 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3438 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3439 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3440 QualType Canon = GetType(Record[Idx++]);
3441 if (!Canon.isNull())
3442 Canon = Context->getCanonicalType(Canon);
3443 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
3446 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3448 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3449 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3450 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3451 unsigned NumArgs = Record[Idx++];
3452 llvm::SmallVector<TemplateArgument, 8> Args;
3453 Args.reserve(NumArgs);
3455 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3456 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
3457 Args.size(), Args.data());
3460 case TYPE_DEPENDENT_SIZED_ARRAY: {
3464 QualType ElementType = GetType(Record[Idx++]);
3465 ArrayType::ArraySizeModifier ASM
3466 = (ArrayType::ArraySizeModifier)Record[Idx++];
3467 unsigned IndexTypeQuals = Record[Idx++];
3469 // DependentSizedArrayType
3470 Expr *NumElts = ReadExpr(*Loc.F);
3471 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3473 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
3474 IndexTypeQuals, Brackets);
3477 case TYPE_TEMPLATE_SPECIALIZATION: {
3479 bool IsDependent = Record[Idx++];
3480 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3481 llvm::SmallVector<TemplateArgument, 8> Args;
3482 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3483 QualType Underlying = GetType(Record[Idx++]);
3485 if (Underlying.isNull())
3486 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
3489 T = Context->getTemplateSpecializationType(Name, Args.data(),
3490 Args.size(), Underlying);
3491 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3495 // Suppress a GCC warning
3499 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3501 ASTReader::PerFileData &F;
3502 llvm::BitstreamCursor &DeclsCursor;
3503 const ASTReader::RecordData &Record;
3506 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3508 return Reader.ReadSourceLocation(F, R, I);
3512 TypeLocReader(ASTReader &Reader, ASTReader::PerFileData &F,
3513 const ASTReader::RecordData &Record, unsigned &Idx)
3514 : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3517 // We want compile-time assurance that we've enumerated all of
3518 // these, so unfortunately we have to declare them first, then
3519 // define them out-of-line.
3520 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3521 #define TYPELOC(CLASS, PARENT) \
3522 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3523 #include "clang/AST/TypeLocNodes.def"
3525 void VisitFunctionTypeLoc(FunctionTypeLoc);
3526 void VisitArrayTypeLoc(ArrayTypeLoc);
3529 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3532 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3533 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3534 if (TL.needsExtraLocalData()) {
3535 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3536 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3537 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3538 TL.setModeAttr(Record[Idx++]);
3541 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3542 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3544 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3545 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3547 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3548 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3550 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3551 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3553 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3554 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3556 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3557 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3558 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3560 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3561 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3562 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3564 TL.setSizeExpr(Reader.ReadExpr(F));
3568 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3569 VisitArrayTypeLoc(TL);
3571 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3572 VisitArrayTypeLoc(TL);
3574 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3575 VisitArrayTypeLoc(TL);
3577 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3578 DependentSizedArrayTypeLoc TL) {
3579 VisitArrayTypeLoc(TL);
3581 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3582 DependentSizedExtVectorTypeLoc TL) {
3583 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3585 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3586 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3588 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3589 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3591 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3592 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
3593 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
3594 TL.setTrailingReturn(Record[Idx++]);
3595 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3596 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
3599 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3600 VisitFunctionTypeLoc(TL);
3602 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3603 VisitFunctionTypeLoc(TL);
3605 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3606 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3608 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3611 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3612 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3613 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3614 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3616 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3617 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3618 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3619 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3620 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3622 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3623 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3625 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3626 TL.setKWLoc(ReadSourceLocation(Record, Idx));
3627 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3628 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3629 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3631 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3634 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3637 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3638 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3640 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3641 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3642 if (TL.hasAttrOperand()) {
3644 range.setBegin(ReadSourceLocation(Record, Idx));
3645 range.setEnd(ReadSourceLocation(Record, Idx));
3646 TL.setAttrOperandParensRange(range);
3648 if (TL.hasAttrExprOperand()) {
3650 TL.setAttrExprOperand(Reader.ReadExpr(F));
3652 TL.setAttrExprOperand(0);
3653 } else if (TL.hasAttrEnumOperand())
3654 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3656 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3657 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3659 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3660 SubstTemplateTypeParmTypeLoc TL) {
3661 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3663 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3664 SubstTemplateTypeParmPackTypeLoc TL) {
3665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3667 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3668 TemplateSpecializationTypeLoc TL) {
3669 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3670 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3671 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3672 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3674 Reader.GetTemplateArgumentLocInfo(F,
3675 TL.getTypePtr()->getArg(i).getKind(),
3678 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3679 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3680 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3682 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3683 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3684 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3686 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3687 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3689 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3690 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3691 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3692 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3694 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3695 DependentTemplateSpecializationTypeLoc TL) {
3696 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3697 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3698 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3699 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3700 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3701 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3703 Reader.GetTemplateArgumentLocInfo(F,
3704 TL.getTypePtr()->getArg(I).getKind(),
3707 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3708 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3710 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3711 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3713 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3714 TL.setHasBaseTypeAsWritten(Record[Idx++]);
3715 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3716 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3717 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3718 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3720 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3721 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3724 TypeSourceInfo *ASTReader::GetTypeSourceInfo(PerFileData &F,
3725 const RecordData &Record,
3727 QualType InfoTy = GetType(Record[Idx++]);
3728 if (InfoTy.isNull())
3731 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
3732 TypeLocReader TLR(*this, F, Record, Idx);
3733 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3738 QualType ASTReader::GetType(TypeID ID) {
3739 unsigned FastQuals = ID & Qualifiers::FastMask;
3740 unsigned Index = ID >> Qualifiers::FastWidth;
3742 if (Index < NUM_PREDEF_TYPE_IDS) {
3744 switch ((PredefinedTypeIDs)Index) {
3745 case PREDEF_TYPE_NULL_ID: return QualType();
3746 case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
3747 case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
3749 case PREDEF_TYPE_CHAR_U_ID:
3750 case PREDEF_TYPE_CHAR_S_ID:
3751 // FIXME: Check that the signedness of CharTy is correct!
3752 T = Context->CharTy;
3755 case PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
3756 case PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
3757 case PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
3758 case PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
3759 case PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
3760 case PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
3761 case PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
3762 case PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
3763 case PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
3764 case PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
3765 case PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
3766 case PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
3767 case PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
3768 case PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
3769 case PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
3770 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
3771 case PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
3772 case PREDEF_TYPE_BOUND_MEMBER: T = Context->BoundMemberTy; break;
3773 case PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
3774 case PREDEF_TYPE_UNKNOWN_ANY: T = Context->UnknownAnyTy; break;
3775 case PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
3776 case PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
3777 case PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
3778 case PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
3779 case PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
3780 case PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
3783 assert(!T.isNull() && "Unknown predefined type");
3784 return T.withFastQualifiers(FastQuals);
3787 Index -= NUM_PREDEF_TYPE_IDS;
3788 assert(Index < TypesLoaded.size() && "Type index out-of-range");
3789 if (TypesLoaded[Index].isNull()) {
3790 TypesLoaded[Index] = ReadTypeRecord(Index);
3791 if (TypesLoaded[Index].isNull())
3794 TypesLoaded[Index]->setFromAST();
3795 TypeIdxs[TypesLoaded[Index]] = TypeIdx::fromTypeID(ID);
3796 if (DeserializationListener)
3797 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3798 TypesLoaded[Index]);
3801 return TypesLoaded[Index].withFastQualifiers(FastQuals);
3804 TypeID ASTReader::GetTypeID(QualType T) const {
3805 return MakeTypeID(T,
3806 std::bind1st(std::mem_fun(&ASTReader::GetTypeIdx), this));
3809 TypeIdx ASTReader::GetTypeIdx(QualType T) const {
3812 assert(!T.getLocalFastQualifiers());
3814 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3815 // GetTypeIdx is mostly used for computing the hash of DeclarationNames and
3816 // comparing keys of ASTDeclContextNameLookupTable.
3817 // If the type didn't come from the AST file use a specially marked index
3818 // so that any hash/key comparison fail since no such index is stored
3820 if (I == TypeIdxs.end())
3825 unsigned ASTReader::getTotalNumCXXBaseSpecifiers() const {
3826 unsigned Result = 0;
3827 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
3828 Result += Chain[I]->LocalNumCXXBaseSpecifiers;
3833 TemplateArgumentLocInfo
3834 ASTReader::GetTemplateArgumentLocInfo(PerFileData &F,
3835 TemplateArgument::ArgKind Kind,
3836 const RecordData &Record,
3839 case TemplateArgument::Expression:
3841 case TemplateArgument::Type:
3842 return GetTypeSourceInfo(F, Record, Index);
3843 case TemplateArgument::Template: {
3844 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3846 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3847 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3850 case TemplateArgument::TemplateExpansion: {
3851 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3853 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3854 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3855 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3858 case TemplateArgument::Null:
3859 case TemplateArgument::Integral:
3860 case TemplateArgument::Declaration:
3861 case TemplateArgument::Pack:
3862 return TemplateArgumentLocInfo();
3864 llvm_unreachable("unexpected template argument loc");
3865 return TemplateArgumentLocInfo();
3869 ASTReader::ReadTemplateArgumentLoc(PerFileData &F,
3870 const RecordData &Record, unsigned &Index) {
3871 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
3873 if (Arg.getKind() == TemplateArgument::Expression) {
3874 if (Record[Index++]) // bool InfoHasSameExpr.
3875 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
3877 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
3881 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
3886 ASTReader::GetCXXBaseSpecifiersOffset(serialization::CXXBaseSpecifiersID ID) {
3891 uint64_t Offset = 0;
3892 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3893 PerFileData &F = *Chain[N - I - 1];
3895 if (ID < F.LocalNumCXXBaseSpecifiers)
3896 return Offset + F.CXXBaseSpecifiersOffsets[ID];
3898 ID -= F.LocalNumCXXBaseSpecifiers;
3899 Offset += F.SizeInBits;
3902 assert(false && "CXXBaseSpecifiers not found");
3906 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
3907 // Figure out which AST file contains this offset.
3909 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3910 if (Offset < Chain[N - I - 1]->SizeInBits) {
3911 F = Chain[N - I - 1];
3915 Offset -= Chain[N - I - 1]->SizeInBits;
3919 Error("Malformed AST file: C++ base specifiers at impossible offset");
3923 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3924 SavedStreamPosition SavedPosition(Cursor);
3925 Cursor.JumpToBit(Offset);
3926 ReadingKindTracker ReadingKind(Read_Decl, *this);
3928 unsigned Code = Cursor.ReadCode();
3929 unsigned RecCode = Cursor.ReadRecord(Code, Record);
3930 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
3931 Error("Malformed AST file: missing C++ base specifiers");
3936 unsigned NumBases = Record[Idx++];
3937 void *Mem = Context->Allocate(sizeof(CXXBaseSpecifier) * NumBases);
3938 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
3939 for (unsigned I = 0; I != NumBases; ++I)
3940 Bases[I] = ReadCXXBaseSpecifier(*F, Record, Idx);
3944 TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() {
3945 if (!DeclsLoaded[0]) {
3946 ReadDeclRecord(0, 1);
3947 if (DeserializationListener)
3948 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
3951 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
3954 Decl *ASTReader::GetDecl(DeclID ID) {
3958 if (ID > DeclsLoaded.size()) {
3959 Error("declaration ID out-of-range for AST file");
3963 unsigned Index = ID - 1;
3964 if (!DeclsLoaded[Index]) {
3965 ReadDeclRecord(Index, ID);
3966 if (DeserializationListener)
3967 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
3970 return DeclsLoaded[Index];
3973 /// \brief Resolve the offset of a statement into a statement.
3975 /// This operation will read a new statement from the external
3976 /// source each time it is called, and is meant to be used via a
3977 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
3978 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
3979 // Switch case IDs are per Decl.
3980 ClearSwitchCaseIDs();
3982 // Offset here is a global offset across the entire chain.
3983 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3984 PerFileData &F = *Chain[N - I - 1];
3985 if (Offset < F.SizeInBits) {
3986 // Since we know that this statement is part of a decl, make sure to use
3987 // the decl cursor to read it.
3988 F.DeclsCursor.JumpToBit(Offset);
3989 return ReadStmtFromStream(F);
3991 Offset -= F.SizeInBits;
3993 llvm_unreachable("Broken chain");
3996 bool ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
3997 bool (*isKindWeWant)(Decl::Kind),
3998 llvm::SmallVectorImpl<Decl*> &Decls) {
3999 assert(DC->hasExternalLexicalStorage() &&
4000 "DeclContext has no lexical decls in storage");
4002 // There might be lexical decls in multiple parts of the chain, for the TU
4004 // DeclContextOffsets might reallocate as we load additional decls below,
4005 // so make a copy of the vector.
4006 DeclContextInfos Infos = DeclContextOffsets[DC];
4007 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
4009 // IDs can be 0 if this context doesn't contain declarations.
4010 if (!I->LexicalDecls)
4013 // Load all of the declaration IDs
4014 for (const KindDeclIDPair *ID = I->LexicalDecls,
4015 *IDE = ID + I->NumLexicalDecls; ID != IDE; ++ID) {
4016 if (isKindWeWant && !isKindWeWant((Decl::Kind)ID->first))
4019 Decl *D = GetDecl(ID->second);
4020 assert(D && "Null decl in lexical decls");
4025 ++NumLexicalDeclContextsRead;
4029 DeclContext::lookup_result
4030 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
4031 DeclarationName Name) {
4032 assert(DC->hasExternalVisibleStorage() &&
4033 "DeclContext has no visible decls in storage");
4035 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
4036 DeclContext::lookup_iterator(0));
4038 llvm::SmallVector<NamedDecl *, 64> Decls;
4039 // There might be visible decls in multiple parts of the chain, for the TU
4040 // and namespaces. For any given name, the last available results replace
4041 // all earlier ones. For this reason, we walk in reverse.
4042 DeclContextInfos &Infos = DeclContextOffsets[DC];
4043 for (DeclContextInfos::reverse_iterator I = Infos.rbegin(), E = Infos.rend();
4045 if (!I->NameLookupTableData)
4048 ASTDeclContextNameLookupTable *LookupTable =
4049 (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
4050 ASTDeclContextNameLookupTable::iterator Pos = LookupTable->find(Name);
4051 if (Pos == LookupTable->end())
4054 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
4055 for (; Data.first != Data.second; ++Data.first)
4056 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
4060 ++NumVisibleDeclContextsRead;
4062 SetExternalVisibleDeclsForName(DC, Name, Decls);
4063 return const_cast<DeclContext*>(DC)->lookup(Name);
4066 void ASTReader::MaterializeVisibleDecls(const DeclContext *DC) {
4067 assert(DC->hasExternalVisibleStorage() &&
4068 "DeclContext has no visible decls in storage");
4070 llvm::SmallVector<NamedDecl *, 64> Decls;
4071 // There might be visible decls in multiple parts of the chain, for the TU
4073 DeclContextInfos &Infos = DeclContextOffsets[DC];
4074 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
4076 if (!I->NameLookupTableData)
4079 ASTDeclContextNameLookupTable *LookupTable =
4080 (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
4081 for (ASTDeclContextNameLookupTable::item_iterator
4082 ItemI = LookupTable->item_begin(),
4083 ItemEnd = LookupTable->item_end() ; ItemI != ItemEnd; ++ItemI) {
4084 ASTDeclContextNameLookupTable::item_iterator::value_type Val
4086 ASTDeclContextNameLookupTrait::data_type Data = Val.second;
4088 for (; Data.first != Data.second; ++Data.first)
4089 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
4090 MaterializeVisibleDeclsForName(DC, Val.first, Decls);
4095 void ASTReader::PassInterestingDeclsToConsumer() {
4097 while (!InterestingDecls.empty()) {
4098 DeclGroupRef DG(InterestingDecls.front());
4099 InterestingDecls.pop_front();
4100 Consumer->HandleInterestingDecl(DG);
4104 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
4105 this->Consumer = Consumer;
4110 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
4111 // Force deserialization of this decl, which will cause it to be queued for
4112 // passing to the consumer.
4113 GetDecl(ExternalDefinitions[I]);
4116 PassInterestingDeclsToConsumer();
4119 void ASTReader::PrintStats() {
4120 std::fprintf(stderr, "*** AST File Statistics:\n");
4122 unsigned NumTypesLoaded
4123 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
4125 unsigned NumDeclsLoaded
4126 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
4128 unsigned NumIdentifiersLoaded
4129 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
4130 IdentifiersLoaded.end(),
4131 (IdentifierInfo *)0);
4132 unsigned NumSelectorsLoaded
4133 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
4134 SelectorsLoaded.end(),
4137 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
4138 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
4139 if (TotalNumSLocEntries)
4140 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
4141 NumSLocEntriesRead, TotalNumSLocEntries,
4142 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
4143 if (!TypesLoaded.empty())
4144 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
4145 NumTypesLoaded, (unsigned)TypesLoaded.size(),
4146 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
4147 if (!DeclsLoaded.empty())
4148 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
4149 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
4150 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
4151 if (!IdentifiersLoaded.empty())
4152 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
4153 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
4154 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
4155 if (!SelectorsLoaded.empty())
4156 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
4157 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
4158 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
4159 if (TotalNumStatements)
4160 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
4161 NumStatementsRead, TotalNumStatements,
4162 ((float)NumStatementsRead/TotalNumStatements * 100));
4164 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
4165 NumMacrosRead, TotalNumMacros,
4166 ((float)NumMacrosRead/TotalNumMacros * 100));
4167 if (TotalLexicalDeclContexts)
4168 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
4169 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4170 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4172 if (TotalVisibleDeclContexts)
4173 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
4174 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4175 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4177 if (TotalNumMethodPoolEntries) {
4178 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
4179 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4180 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
4182 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
4184 std::fprintf(stderr, "\n");
4187 /// Return the amount of memory used by memory buffers, breaking down
4188 /// by heap-backed versus mmap'ed memory.
4189 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
4190 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
4191 if (llvm::MemoryBuffer *buf = Chain[i]->Buffer.get()) {
4192 size_t bytes = buf->getBufferSize();
4193 switch (buf->getBufferKind()) {
4194 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
4195 sizes.malloc_bytes += bytes;
4197 case llvm::MemoryBuffer::MemoryBuffer_MMap:
4198 sizes.mmap_bytes += bytes;
4204 void ASTReader::InitializeSema(Sema &S) {
4206 S.ExternalSource = this;
4208 // Makes sure any declarations that were deserialized "too early"
4209 // still get added to the identifier's declaration chains.
4210 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4211 if (SemaObj->TUScope)
4212 SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
4214 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
4216 PreloadedDecls.clear();
4218 // If there were any tentative definitions, deserialize them and add
4219 // them to Sema's list of tentative definitions.
4220 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4221 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
4222 SemaObj->TentativeDefinitions.push_back(Var);
4225 // If there were any unused file scoped decls, deserialize them and add to
4226 // Sema's list of unused file scoped decls.
4227 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4228 DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4229 SemaObj->UnusedFileScopedDecls.push_back(D);
4232 // If there were any delegating constructors, add them to Sema's list
4233 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
4234 CXXConstructorDecl *D
4235 = cast<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
4236 SemaObj->DelegatingCtorDecls.push_back(D);
4239 // If there were any locally-scoped external declarations,
4240 // deserialize them and add them to Sema's table of locally-scoped
4241 // external declarations.
4242 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4243 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4244 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
4247 // If there were any ext_vector type declarations, deserialize them
4248 // and add them to Sema's vector of such declarations.
4249 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
4250 SemaObj->ExtVectorDecls.push_back(
4251 cast<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])));
4253 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
4254 // Can we cut them down before writing them ?
4256 // If there were any dynamic classes declarations, deserialize them
4257 // and add them to Sema's vector of such declarations.
4258 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
4259 SemaObj->DynamicClasses.push_back(
4260 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
4262 // Load the offsets of the declarations that Sema references.
4263 // They will be lazily deserialized when needed.
4264 if (!SemaDeclRefs.empty()) {
4265 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4266 SemaObj->StdNamespace = SemaDeclRefs[0];
4267 SemaObj->StdBadAlloc = SemaDeclRefs[1];
4270 for (PerFileData *F = FirstInSource; F; F = F->NextInSource) {
4272 // If there are @selector references added them to its pool. This is for
4273 // implementation of -Wselector.
4274 if (!F->ReferencedSelectorsData.empty()) {
4275 unsigned int DataSize = F->ReferencedSelectorsData.size()-1;
4277 while (I < DataSize) {
4278 Selector Sel = DecodeSelector(F->ReferencedSelectorsData[I++]);
4279 SourceLocation SelLoc = ReadSourceLocation(
4280 *F, F->ReferencedSelectorsData, I);
4281 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
4286 // The special data sets below always come from the most recent PCH,
4287 // which is at the front of the chain.
4288 PerFileData &F = *Chain.front();
4290 // If there were any pending implicit instantiations, deserialize them
4291 // and add them to Sema's queue of such instantiations.
4292 assert(F.PendingInstantiations.size() % 2 == 0 &&
4293 "Expected pairs of entries");
4294 for (unsigned Idx = 0, N = F.PendingInstantiations.size(); Idx < N;) {
4295 ValueDecl *D=cast<ValueDecl>(GetDecl(F.PendingInstantiations[Idx++]));
4296 SourceLocation Loc = ReadSourceLocation(F, F.PendingInstantiations,Idx);
4297 SemaObj->PendingInstantiations.push_back(std::make_pair(D, Loc));
4300 // If there were any weak undeclared identifiers, deserialize them and add to
4301 // Sema's list of weak undeclared identifiers.
4302 if (!WeakUndeclaredIdentifiers.empty()) {
4304 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
4305 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4306 IdentifierInfo *AliasId= GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4307 SourceLocation Loc = ReadSourceLocation(F, WeakUndeclaredIdentifiers,Idx);
4308 bool Used = WeakUndeclaredIdentifiers[Idx++];
4309 Sema::WeakInfo WI(AliasId, Loc);
4311 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
4315 // If there were any VTable uses, deserialize the information and add it
4316 // to Sema's vector and map of VTable uses.
4317 if (!VTableUses.empty()) {
4319 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
4320 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4321 SourceLocation Loc = ReadSourceLocation(F, VTableUses, Idx);
4322 bool DefinitionRequired = VTableUses[Idx++];
4323 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
4324 SemaObj->VTablesUsed[Class] = DefinitionRequired;
4328 if (!FPPragmaOptions.empty()) {
4329 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4330 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4333 if (!OpenCLExtensions.empty()) {
4335 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4336 #include "clang/Basic/OpenCLExtensions.def"
4338 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4342 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4343 // Try to find this name within our on-disk hash tables. We start with the
4344 // most recent one, since that one contains the most up-to-date info.
4345 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4346 ASTIdentifierLookupTable *IdTable
4347 = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
4350 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
4351 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
4352 if (Pos == IdTable->end())
4355 // Dereferencing the iterator has the effect of building the
4356 // IdentifierInfo node and populating it with the various
4357 // declarations it needs.
4364 /// \brief An identifier-lookup iterator that enumerates all of the
4365 /// identifiers stored within a set of AST files.
4366 class ASTIdentifierIterator : public IdentifierIterator {
4367 /// \brief The AST reader whose identifiers are being enumerated.
4368 const ASTReader &Reader;
4370 /// \brief The current index into the chain of AST files stored in
4374 /// \brief The current position within the identifier lookup table
4375 /// of the current AST file.
4376 ASTIdentifierLookupTable::key_iterator Current;
4378 /// \brief The end position within the identifier lookup table of
4379 /// the current AST file.
4380 ASTIdentifierLookupTable::key_iterator End;
4383 explicit ASTIdentifierIterator(const ASTReader &Reader);
4385 virtual llvm::StringRef Next();
4389 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4390 : Reader(Reader), Index(Reader.Chain.size() - 1) {
4391 ASTIdentifierLookupTable *IdTable
4392 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4393 Current = IdTable->key_begin();
4394 End = IdTable->key_end();
4397 llvm::StringRef ASTIdentifierIterator::Next() {
4398 while (Current == End) {
4399 // If we have exhausted all of our AST files, we're done.
4401 return llvm::StringRef();
4404 ASTIdentifierLookupTable *IdTable
4405 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4406 Current = IdTable->key_begin();
4407 End = IdTable->key_end();
4410 // We have any identifiers remaining in the current AST file; return
4412 std::pair<const char*, unsigned> Key = *Current;
4414 return llvm::StringRef(Key.first, Key.second);
4417 IdentifierIterator *ASTReader::getIdentifiers() const {
4418 return new ASTIdentifierIterator(*this);
4421 std::pair<ObjCMethodList, ObjCMethodList>
4422 ASTReader::ReadMethodPool(Selector Sel) {
4423 // Find this selector in a hash table. We want to find the most recent entry.
4424 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4425 PerFileData &F = *Chain[I];
4426 if (!F.SelectorLookupTable)
4429 ASTSelectorLookupTable *PoolTable
4430 = (ASTSelectorLookupTable*)F.SelectorLookupTable;
4431 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
4432 if (Pos != PoolTable->end()) {
4434 // FIXME: Not quite happy with the statistics here. We probably should
4435 // disable this tracking when called via LoadSelector.
4436 // Also, should entries without methods count as misses?
4437 ++NumMethodPoolEntriesRead;
4438 ASTSelectorLookupTrait::data_type Data = *Pos;
4439 if (DeserializationListener)
4440 DeserializationListener->SelectorRead(Data.ID, Sel);
4441 return std::make_pair(Data.Instance, Data.Factory);
4445 ++NumMethodPoolMisses;
4446 return std::pair<ObjCMethodList, ObjCMethodList>();
4449 void ASTReader::LoadSelector(Selector Sel) {
4450 // It would be complicated to avoid reading the methods anyway. So don't.
4451 ReadMethodPool(Sel);
4454 void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
4455 assert(ID && "Non-zero identifier ID required");
4456 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4457 IdentifiersLoaded[ID - 1] = II;
4458 if (DeserializationListener)
4459 DeserializationListener->IdentifierRead(ID, II);
4462 /// \brief Set the globally-visible declarations associated with the given
4465 /// If the AST reader is currently in a state where the given declaration IDs
4466 /// cannot safely be resolved, they are queued until it is safe to resolve
4469 /// \param II an IdentifierInfo that refers to one or more globally-visible
4472 /// \param DeclIDs the set of declaration IDs with the name @p II that are
4473 /// visible at global scope.
4475 /// \param Nonrecursive should be true to indicate that the caller knows that
4476 /// this call is non-recursive, and therefore the globally-visible declarations
4477 /// will not be placed onto the pending queue.
4479 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4480 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
4481 bool Nonrecursive) {
4482 if (NumCurrentElementsDeserializing && !Nonrecursive) {
4483 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4484 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4486 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4490 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4491 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4493 if (SemaObj->TUScope) {
4494 // Introduce this declaration into the translation-unit scope
4495 // and add it to the declaration chain for this identifier, so
4496 // that (unqualified) name lookup will find it.
4497 SemaObj->TUScope->AddDecl(D);
4499 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
4501 // Queue this declaration so that it will be added to the
4502 // translation unit scope and identifier's declaration chain
4503 // once a Sema object is known.
4504 PreloadedDecls.push_back(D);
4509 IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) {
4513 if (IdentifiersLoaded.empty()) {
4514 Error("no identifier table in AST file");
4518 assert(PP && "Forgot to set Preprocessor ?");
4520 if (!IdentifiersLoaded[ID]) {
4521 unsigned Index = ID;
4522 const char *Str = 0;
4523 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4524 PerFileData *F = Chain[N - I - 1];
4525 if (Index < F->LocalNumIdentifiers) {
4526 uint32_t Offset = F->IdentifierOffsets[Index];
4527 Str = F->IdentifierTableData + Offset;
4530 Index -= F->LocalNumIdentifiers;
4532 assert(Str && "Broken Chain");
4534 // All of the strings in the AST file are preceded by a 16-bit length.
4535 // Extract that 16-bit length to avoid having to execute strlen().
4536 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4537 // unsigned integers. This is important to avoid integer overflow when
4538 // we cast them to 'unsigned'.
4539 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4540 unsigned StrLen = (((unsigned) StrLenPtr[0])
4541 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4542 IdentifiersLoaded[ID]
4543 = &PP->getIdentifierTable().get(Str, StrLen);
4544 if (DeserializationListener)
4545 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4548 return IdentifiersLoaded[ID];
4551 bool ASTReader::ReadSLocEntry(unsigned ID) {
4552 return ReadSLocEntryRecord(ID) != Success;
4555 Selector ASTReader::DecodeSelector(unsigned ID) {
4559 if (ID > SelectorsLoaded.size()) {
4560 Error("selector ID out of range in AST file");
4564 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4565 // Load this selector from the selector table.
4566 unsigned Idx = ID - 1;
4567 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4568 PerFileData &F = *Chain[N - I - 1];
4569 if (Idx < F.LocalNumSelectors) {
4570 ASTSelectorLookupTrait Trait(*this);
4571 SelectorsLoaded[ID - 1] =
4572 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
4573 if (DeserializationListener)
4574 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
4577 Idx -= F.LocalNumSelectors;
4581 return SelectorsLoaded[ID - 1];
4584 Selector ASTReader::GetExternalSelector(uint32_t ID) {
4585 return DecodeSelector(ID);
4588 uint32_t ASTReader::GetNumExternalSelectors() {
4589 // ID 0 (the null selector) is considered an external selector.
4590 return getTotalNumSelectors() + 1;
4594 ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
4595 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
4597 case DeclarationName::Identifier:
4598 return DeclarationName(GetIdentifierInfo(Record, Idx));
4600 case DeclarationName::ObjCZeroArgSelector:
4601 case DeclarationName::ObjCOneArgSelector:
4602 case DeclarationName::ObjCMultiArgSelector:
4603 return DeclarationName(GetSelector(Record, Idx));
4605 case DeclarationName::CXXConstructorName:
4606 return Context->DeclarationNames.getCXXConstructorName(
4607 Context->getCanonicalType(GetType(Record[Idx++])));
4609 case DeclarationName::CXXDestructorName:
4610 return Context->DeclarationNames.getCXXDestructorName(
4611 Context->getCanonicalType(GetType(Record[Idx++])));
4613 case DeclarationName::CXXConversionFunctionName:
4614 return Context->DeclarationNames.getCXXConversionFunctionName(
4615 Context->getCanonicalType(GetType(Record[Idx++])));
4617 case DeclarationName::CXXOperatorName:
4618 return Context->DeclarationNames.getCXXOperatorName(
4619 (OverloadedOperatorKind)Record[Idx++]);
4621 case DeclarationName::CXXLiteralOperatorName:
4622 return Context->DeclarationNames.getCXXLiteralOperatorName(
4623 GetIdentifierInfo(Record, Idx));
4625 case DeclarationName::CXXUsingDirective:
4626 return DeclarationName::getUsingDirectiveName();
4629 // Required to silence GCC warning
4630 return DeclarationName();
4633 void ASTReader::ReadDeclarationNameLoc(PerFileData &F,
4634 DeclarationNameLoc &DNLoc,
4635 DeclarationName Name,
4636 const RecordData &Record, unsigned &Idx) {
4637 switch (Name.getNameKind()) {
4638 case DeclarationName::CXXConstructorName:
4639 case DeclarationName::CXXDestructorName:
4640 case DeclarationName::CXXConversionFunctionName:
4641 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
4644 case DeclarationName::CXXOperatorName:
4645 DNLoc.CXXOperatorName.BeginOpNameLoc
4646 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4647 DNLoc.CXXOperatorName.EndOpNameLoc
4648 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4651 case DeclarationName::CXXLiteralOperatorName:
4652 DNLoc.CXXLiteralOperatorName.OpNameLoc
4653 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4656 case DeclarationName::Identifier:
4657 case DeclarationName::ObjCZeroArgSelector:
4658 case DeclarationName::ObjCOneArgSelector:
4659 case DeclarationName::ObjCMultiArgSelector:
4660 case DeclarationName::CXXUsingDirective:
4665 void ASTReader::ReadDeclarationNameInfo(PerFileData &F,
4666 DeclarationNameInfo &NameInfo,
4667 const RecordData &Record, unsigned &Idx) {
4668 NameInfo.setName(ReadDeclarationName(Record, Idx));
4669 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
4670 DeclarationNameLoc DNLoc;
4671 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
4672 NameInfo.setInfo(DNLoc);
4675 void ASTReader::ReadQualifierInfo(PerFileData &F, QualifierInfo &Info,
4676 const RecordData &Record, unsigned &Idx) {
4677 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
4678 unsigned NumTPLists = Record[Idx++];
4679 Info.NumTemplParamLists = NumTPLists;
4681 Info.TemplParamLists = new (*Context) TemplateParameterList*[NumTPLists];
4682 for (unsigned i=0; i != NumTPLists; ++i)
4683 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
4688 ASTReader::ReadTemplateName(PerFileData &F, const RecordData &Record,
4690 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
4692 case TemplateName::Template:
4693 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
4695 case TemplateName::OverloadedTemplate: {
4696 unsigned size = Record[Idx++];
4697 UnresolvedSet<8> Decls;
4699 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
4701 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
4704 case TemplateName::QualifiedTemplate: {
4705 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4706 bool hasTemplKeyword = Record[Idx++];
4707 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
4708 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
4711 case TemplateName::DependentTemplate: {
4712 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4713 if (Record[Idx++]) // isIdentifier
4714 return Context->getDependentTemplateName(NNS,
4715 GetIdentifierInfo(Record, Idx));
4716 return Context->getDependentTemplateName(NNS,
4717 (OverloadedOperatorKind)Record[Idx++]);
4720 case TemplateName::SubstTemplateTemplateParmPack: {
4721 TemplateTemplateParmDecl *Param
4722 = cast_or_null<TemplateTemplateParmDecl>(GetDecl(Record[Idx++]));
4724 return TemplateName();
4726 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
4727 if (ArgPack.getKind() != TemplateArgument::Pack)
4728 return TemplateName();
4730 return Context->getSubstTemplateTemplateParmPack(Param, ArgPack);
4734 assert(0 && "Unhandled template name kind!");
4735 return TemplateName();
4739 ASTReader::ReadTemplateArgument(PerFileData &F,
4740 const RecordData &Record, unsigned &Idx) {
4741 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
4743 case TemplateArgument::Null:
4744 return TemplateArgument();
4745 case TemplateArgument::Type:
4746 return TemplateArgument(GetType(Record[Idx++]));
4747 case TemplateArgument::Declaration:
4748 return TemplateArgument(GetDecl(Record[Idx++]));
4749 case TemplateArgument::Integral: {
4750 llvm::APSInt Value = ReadAPSInt(Record, Idx);
4751 QualType T = GetType(Record[Idx++]);
4752 return TemplateArgument(Value, T);
4754 case TemplateArgument::Template:
4755 return TemplateArgument(ReadTemplateName(F, Record, Idx));
4756 case TemplateArgument::TemplateExpansion: {
4757 TemplateName Name = ReadTemplateName(F, Record, Idx);
4758 llvm::Optional<unsigned> NumTemplateExpansions;
4759 if (unsigned NumExpansions = Record[Idx++])
4760 NumTemplateExpansions = NumExpansions - 1;
4761 return TemplateArgument(Name, NumTemplateExpansions);
4763 case TemplateArgument::Expression:
4764 return TemplateArgument(ReadExpr(F));
4765 case TemplateArgument::Pack: {
4766 unsigned NumArgs = Record[Idx++];
4767 TemplateArgument *Args = new (*Context) TemplateArgument[NumArgs];
4768 for (unsigned I = 0; I != NumArgs; ++I)
4769 Args[I] = ReadTemplateArgument(F, Record, Idx);
4770 return TemplateArgument(Args, NumArgs);
4774 assert(0 && "Unhandled template argument kind!");
4775 return TemplateArgument();
4778 TemplateParameterList *
4779 ASTReader::ReadTemplateParameterList(PerFileData &F,
4780 const RecordData &Record, unsigned &Idx) {
4781 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
4782 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
4783 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
4785 unsigned NumParams = Record[Idx++];
4786 llvm::SmallVector<NamedDecl *, 16> Params;
4787 Params.reserve(NumParams);
4789 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
4791 TemplateParameterList* TemplateParams =
4792 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
4793 Params.data(), Params.size(), RAngleLoc);
4794 return TemplateParams;
4799 ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
4800 PerFileData &F, const RecordData &Record,
4802 unsigned NumTemplateArgs = Record[Idx++];
4803 TemplArgs.reserve(NumTemplateArgs);
4804 while (NumTemplateArgs--)
4805 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
4808 /// \brief Read a UnresolvedSet structure.
4809 void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
4810 const RecordData &Record, unsigned &Idx) {
4811 unsigned NumDecls = Record[Idx++];
4812 while (NumDecls--) {
4813 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
4814 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
4820 ASTReader::ReadCXXBaseSpecifier(PerFileData &F,
4821 const RecordData &Record, unsigned &Idx) {
4822 bool isVirtual = static_cast<bool>(Record[Idx++]);
4823 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
4824 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
4825 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
4826 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
4827 SourceRange Range = ReadSourceRange(F, Record, Idx);
4828 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
4829 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
4831 Result.setInheritConstructors(inheritConstructors);
4835 std::pair<CXXCtorInitializer **, unsigned>
4836 ASTReader::ReadCXXCtorInitializers(PerFileData &F, const RecordData &Record,
4838 CXXCtorInitializer **CtorInitializers = 0;
4839 unsigned NumInitializers = Record[Idx++];
4840 if (NumInitializers) {
4841 ASTContext &C = *getContext();
4844 = new (C) CXXCtorInitializer*[NumInitializers];
4845 for (unsigned i=0; i != NumInitializers; ++i) {
4846 TypeSourceInfo *BaseClassInfo = 0;
4847 bool IsBaseVirtual = false;
4848 FieldDecl *Member = 0;
4849 IndirectFieldDecl *IndirectMember = 0;
4850 CXXConstructorDecl *Target = 0;
4852 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
4854 case CTOR_INITIALIZER_BASE:
4855 BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
4856 IsBaseVirtual = Record[Idx++];
4859 case CTOR_INITIALIZER_DELEGATING:
4860 Target = cast<CXXConstructorDecl>(GetDecl(Record[Idx++]));
4863 case CTOR_INITIALIZER_MEMBER:
4864 Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
4867 case CTOR_INITIALIZER_INDIRECT_MEMBER:
4868 IndirectMember = cast<IndirectFieldDecl>(GetDecl(Record[Idx++]));
4872 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
4873 Expr *Init = ReadExpr(F);
4874 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
4875 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
4876 bool IsWritten = Record[Idx++];
4877 unsigned SourceOrderOrNumArrayIndices;
4878 llvm::SmallVector<VarDecl *, 8> Indices;
4880 SourceOrderOrNumArrayIndices = Record[Idx++];
4882 SourceOrderOrNumArrayIndices = Record[Idx++];
4883 Indices.reserve(SourceOrderOrNumArrayIndices);
4884 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
4885 Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
4888 CXXCtorInitializer *BOMInit;
4889 if (Type == CTOR_INITIALIZER_BASE) {
4890 BOMInit = new (C) CXXCtorInitializer(C, BaseClassInfo, IsBaseVirtual,
4891 LParenLoc, Init, RParenLoc,
4892 MemberOrEllipsisLoc);
4893 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
4894 BOMInit = new (C) CXXCtorInitializer(C, MemberOrEllipsisLoc, LParenLoc,
4895 Target, Init, RParenLoc);
4896 } else if (IsWritten) {
4898 BOMInit = new (C) CXXCtorInitializer(C, Member, MemberOrEllipsisLoc,
4899 LParenLoc, Init, RParenLoc);
4901 BOMInit = new (C) CXXCtorInitializer(C, IndirectMember,
4902 MemberOrEllipsisLoc, LParenLoc,
4905 BOMInit = CXXCtorInitializer::Create(C, Member, MemberOrEllipsisLoc,
4906 LParenLoc, Init, RParenLoc,
4907 Indices.data(), Indices.size());
4911 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
4912 CtorInitializers[i] = BOMInit;
4916 return std::make_pair(CtorInitializers, NumInitializers);
4919 NestedNameSpecifier *
4920 ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
4921 unsigned N = Record[Idx++];
4922 NestedNameSpecifier *NNS = 0, *Prev = 0;
4923 for (unsigned I = 0; I != N; ++I) {
4924 NestedNameSpecifier::SpecifierKind Kind
4925 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
4927 case NestedNameSpecifier::Identifier: {
4928 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
4929 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
4933 case NestedNameSpecifier::Namespace: {
4934 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
4935 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
4939 case NestedNameSpecifier::NamespaceAlias: {
4940 NamespaceAliasDecl *Alias
4941 = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++]));
4942 NNS = NestedNameSpecifier::Create(*Context, Prev, Alias);
4946 case NestedNameSpecifier::TypeSpec:
4947 case NestedNameSpecifier::TypeSpecWithTemplate: {
4948 const Type *T = GetType(Record[Idx++]).getTypePtrOrNull();
4952 bool Template = Record[Idx++];
4953 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
4957 case NestedNameSpecifier::Global: {
4958 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
4959 // No associated value, and there can't be a prefix.
4968 NestedNameSpecifierLoc
4969 ASTReader::ReadNestedNameSpecifierLoc(PerFileData &F, const RecordData &Record,
4971 unsigned N = Record[Idx++];
4972 NestedNameSpecifierLocBuilder Builder;
4973 for (unsigned I = 0; I != N; ++I) {
4974 NestedNameSpecifier::SpecifierKind Kind
4975 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
4977 case NestedNameSpecifier::Identifier: {
4978 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
4979 SourceRange Range = ReadSourceRange(F, Record, Idx);
4980 Builder.Extend(*Context, II, Range.getBegin(), Range.getEnd());
4984 case NestedNameSpecifier::Namespace: {
4985 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
4986 SourceRange Range = ReadSourceRange(F, Record, Idx);
4987 Builder.Extend(*Context, NS, Range.getBegin(), Range.getEnd());
4991 case NestedNameSpecifier::NamespaceAlias: {
4992 NamespaceAliasDecl *Alias
4993 = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++]));
4994 SourceRange Range = ReadSourceRange(F, Record, Idx);
4995 Builder.Extend(*Context, Alias, Range.getBegin(), Range.getEnd());
4999 case NestedNameSpecifier::TypeSpec:
5000 case NestedNameSpecifier::TypeSpecWithTemplate: {
5001 bool Template = Record[Idx++];
5002 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
5004 return NestedNameSpecifierLoc();
5005 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5007 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
5008 Builder.Extend(*Context,
5009 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
5010 T->getTypeLoc(), ColonColonLoc);
5014 case NestedNameSpecifier::Global: {
5015 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5016 Builder.MakeGlobal(*Context, ColonColonLoc);
5022 return Builder.getWithLocInContext(*Context);
5026 ASTReader::ReadSourceRange(PerFileData &F, const RecordData &Record,
5028 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
5029 SourceLocation end = ReadSourceLocation(F, Record, Idx);
5030 return SourceRange(beg, end);
5033 /// \brief Read an integral value
5034 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
5035 unsigned BitWidth = Record[Idx++];
5036 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
5037 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
5042 /// \brief Read a signed integral value
5043 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
5044 bool isUnsigned = Record[Idx++];
5045 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
5048 /// \brief Read a floating-point value
5049 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
5050 return llvm::APFloat(ReadAPInt(Record, Idx));
5053 // \brief Read a string
5054 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
5055 unsigned Len = Record[Idx++];
5056 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
5061 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
5063 unsigned Major = Record[Idx++];
5064 unsigned Minor = Record[Idx++];
5065 unsigned Subminor = Record[Idx++];
5067 return VersionTuple(Major);
5069 return VersionTuple(Major, Minor - 1);
5070 return VersionTuple(Major, Minor - 1, Subminor - 1);
5073 CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record,
5075 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
5076 return CXXTemporary::Create(*Context, Decl);
5079 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
5080 return Diag(SourceLocation(), DiagID);
5083 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
5084 return Diags.Report(Loc, DiagID);
5087 /// \brief Retrieve the identifier table associated with the
5089 IdentifierTable &ASTReader::getIdentifierTable() {
5090 assert(PP && "Forgot to set Preprocessor ?");
5091 return PP->getIdentifierTable();
5094 /// \brief Record that the given ID maps to the given switch-case
5096 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
5097 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
5098 SwitchCaseStmts[ID] = SC;
5101 /// \brief Retrieve the switch-case statement with the given ID.
5102 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
5103 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
5104 return SwitchCaseStmts[ID];
5107 void ASTReader::ClearSwitchCaseIDs() {
5108 SwitchCaseStmts.clear();
5111 void ASTReader::FinishedDeserializing() {
5112 assert(NumCurrentElementsDeserializing &&
5113 "FinishedDeserializing not paired with StartedDeserializing");
5114 if (NumCurrentElementsDeserializing == 1) {
5115 // If any identifiers with corresponding top-level declarations have
5116 // been loaded, load those declarations now.
5117 while (!PendingIdentifierInfos.empty()) {
5118 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
5119 PendingIdentifierInfos.front().DeclIDs, true);
5120 PendingIdentifierInfos.pop_front();
5123 // Ready to load previous declarations of Decls that were delayed.
5124 while (!PendingPreviousDecls.empty()) {
5125 loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
5126 PendingPreviousDecls.front().second);
5127 PendingPreviousDecls.pop_front();
5130 // We are not in recursive loading, so it's safe to pass the "interesting"
5131 // decls to the consumer.
5133 PassInterestingDeclsToConsumer();
5135 assert(PendingForwardRefs.size() == 0 &&
5136 "Some forward refs did not get linked to the definition!");
5138 --NumCurrentElementsDeserializing;
5141 ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
5142 const char *isysroot, bool DisableValidation,
5143 bool DisableStatCache)
5144 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
5145 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
5146 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
5147 Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
5148 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
5149 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NextSLocOffset(0),
5150 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
5151 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
5152 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
5153 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
5154 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
5155 NumCurrentElementsDeserializing(0)
5157 RelocatablePCH = false;
5160 ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
5161 Diagnostic &Diags, const char *isysroot,
5162 bool DisableValidation, bool DisableStatCache)
5163 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
5164 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
5165 isysroot(isysroot), DisableValidation(DisableValidation),
5166 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
5167 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
5168 NextSLocOffset(0), NumStatementsRead(0), TotalNumStatements(0),
5169 NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
5170 NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
5171 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
5172 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
5173 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
5174 RelocatablePCH = false;
5177 ASTReader::~ASTReader() {
5178 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
5179 delete Chain[e - i - 1];
5180 // Delete all visible decl lookup tables
5181 for (DeclContextOffsetsMap::iterator I = DeclContextOffsets.begin(),
5182 E = DeclContextOffsets.end();
5184 for (DeclContextInfos::iterator J = I->second.begin(), F = I->second.end();
5186 if (J->NameLookupTableData)
5187 delete static_cast<ASTDeclContextNameLookupTable*>(
5188 J->NameLookupTableData);
5191 for (DeclContextVisibleUpdatesPending::iterator
5192 I = PendingVisibleUpdates.begin(),
5193 E = PendingVisibleUpdates.end();
5195 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
5196 F = I->second.end();
5198 delete static_cast<ASTDeclContextNameLookupTable*>(*J);
5202 ASTReader::PerFileData::PerFileData(ASTFileType Ty)
5203 : Type(Ty), SizeInBits(0), LocalNumSLocEntries(0), SLocOffsets(0),
5204 SLocFileOffsets(0), LocalSLocSize(0),
5205 LocalNumIdentifiers(0), IdentifierOffsets(0), IdentifierTableData(0),
5206 IdentifierLookupTable(0), LocalNumMacroDefinitions(0),
5207 MacroDefinitionOffsets(0),
5208 LocalNumHeaderFileInfos(0), HeaderFileInfoTableData(0),
5209 HeaderFileInfoTable(0),
5210 LocalNumSelectors(0), SelectorOffsets(0),
5211 SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
5212 DeclOffsets(0), LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0),
5213 LocalNumTypes(0), TypeOffsets(0), StatCache(0),
5214 NumPreallocatedPreprocessingEntities(0), NextInSource(0)
5217 ASTReader::PerFileData::~PerFileData() {
5218 delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable);
5219 delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable);
5220 delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable);