[Heikki Kultala] This patch contains the ABI changes for the TCE target.
[clang.git] / lib / Serialization / ASTReader.cpp
blob83f8a84d6644c4124d88ac91656a6d27bc4b5148
1 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTReader class, which reads AST files.
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/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/PreprocessingRecord.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Basic/OnDiskHashTable.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/SourceManagerInternals.h"
35 #include "clang/Basic/FileManager.h"
36 #include "clang/Basic/FileSystemStatCache.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/Version.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Bitcode/BitstreamReader.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/system_error.h"
46 #include <algorithm>
47 #include <iterator>
48 #include <cstdio>
49 #include <sys/stat.h>
51 using namespace clang;
52 using namespace clang::serialization;
54 //===----------------------------------------------------------------------===//
55 // PCH validator implementation
56 //===----------------------------------------------------------------------===//
58 ASTReaderListener::~ASTReaderListener() {}
60 bool
61 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
62 const LangOptions &PPLangOpts = PP.getLangOptions();
63 #define PARSE_LANGOPT_BENIGN(Option)
64 #define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
65 if (PPLangOpts.Option != LangOpts.Option) { \
66 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
67 return true; \
70 PARSE_LANGOPT_BENIGN(Trigraphs);
71 PARSE_LANGOPT_BENIGN(BCPLComment);
72 PARSE_LANGOPT_BENIGN(DollarIdents);
73 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
74 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
75 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
76 PARSE_LANGOPT_BENIGN(ImplicitInt);
77 PARSE_LANGOPT_BENIGN(Digraphs);
78 PARSE_LANGOPT_BENIGN(HexFloats);
79 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
80 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
81 PARSE_LANGOPT_BENIGN(MSCVersion);
82 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
83 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
84 PARSE_LANGOPT_BENIGN(CXXOperatorName);
85 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
86 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
87 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
88 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
89 PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext);
90 PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties,
91 diag::warn_pch_objc_auto_properties);
92 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
93 diag::warn_pch_no_constant_cfstrings);
94 PARSE_LANGOPT_BENIGN(PascalStrings);
95 PARSE_LANGOPT_BENIGN(WritableStrings);
96 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
97 diag::warn_pch_lax_vector_conversions);
98 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
99 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
100 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
101 PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields);
102 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
103 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
104 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
105 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
106 diag::warn_pch_thread_safe_statics);
107 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
108 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
109 PARSE_LANGOPT_BENIGN(EmitAllDecls);
110 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
111 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
112 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
113 diag::warn_pch_heinous_extensions);
114 // FIXME: Most of the options below are benign if the macro wasn't
115 // used. Unfortunately, this means that a PCH compiled without
116 // optimization can't be used with optimization turned on, even
117 // though the only thing that changes is whether __OPTIMIZE__ was
118 // defined... but if __OPTIMIZE__ never showed up in the header, it
119 // doesn't matter. We could consider making this some special kind
120 // of check.
121 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
122 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
123 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
124 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
125 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
126 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
127 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
128 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
129 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
130 PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums);
131 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
132 Reader.Diag(diag::warn_pch_gc_mode)
133 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
134 return true;
136 PARSE_LANGOPT_BENIGN(getVisibilityMode());
137 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
138 diag::warn_pch_stack_protector);
139 PARSE_LANGOPT_BENIGN(InstantiationDepth);
140 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
141 PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda);
142 PARSE_LANGOPT_BENIGN(CatchUndefined);
143 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
144 PARSE_LANGOPT_BENIGN(SpellChecking);
145 PARSE_LANGOPT_BENIGN(DefaultFPContract);
146 #undef PARSE_LANGOPT_IMPORTANT
147 #undef PARSE_LANGOPT_BENIGN
149 return false;
152 bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
153 if (Triple == PP.getTargetInfo().getTriple().str())
154 return false;
156 Reader.Diag(diag::warn_pch_target_triple)
157 << Triple << PP.getTargetInfo().getTriple().str();
158 return true;
161 namespace {
162 struct EmptyStringRef {
163 bool operator ()(llvm::StringRef r) const { return r.empty(); }
165 struct EmptyBlock {
166 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
170 static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
171 PCHPredefinesBlocks R) {
172 // First, sum up the lengths.
173 unsigned LL = 0, RL = 0;
174 for (unsigned I = 0, N = L.size(); I != N; ++I) {
175 LL += L[I].size();
177 for (unsigned I = 0, N = R.size(); I != N; ++I) {
178 RL += R[I].Data.size();
180 if (LL != RL)
181 return false;
182 if (LL == 0 && RL == 0)
183 return true;
185 // Kick out empty parts, they confuse the algorithm below.
186 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
187 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
189 // Do it the hard way. At this point, both vectors must be non-empty.
190 llvm::StringRef LR = L[0], RR = R[0].Data;
191 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
192 (void) RN;
193 for (;;) {
194 // Compare the current pieces.
195 if (LR.size() == RR.size()) {
196 // If they're the same length, it's pretty easy.
197 if (LR != RR)
198 return false;
199 // Both pieces are done, advance.
200 ++LI;
201 ++RI;
202 // If either string is done, they're both done, since they're the same
203 // length.
204 if (LI == LN) {
205 assert(RI == RN && "Strings not the same length after all?");
206 return true;
208 LR = L[LI];
209 RR = R[RI].Data;
210 } else if (LR.size() < RR.size()) {
211 // Right piece is longer.
212 if (!RR.startswith(LR))
213 return false;
214 ++LI;
215 assert(LI != LN && "Strings not the same length after all?");
216 RR = RR.substr(LR.size());
217 LR = L[LI];
218 } else {
219 // Left piece is longer.
220 if (!LR.startswith(RR))
221 return false;
222 ++RI;
223 assert(RI != RN && "Strings not the same length after all?");
224 LR = LR.substr(RR.size());
225 RR = R[RI].Data;
230 static std::pair<FileID, llvm::StringRef::size_type>
231 FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
232 std::pair<FileID, llvm::StringRef::size_type> Res;
233 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
234 Res.second = Buffers[I].Data.find(MacroDef);
235 if (Res.second != llvm::StringRef::npos) {
236 Res.first = Buffers[I].BufferID;
237 break;
240 return Res;
243 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
244 llvm::StringRef OriginalFileName,
245 std::string &SuggestedPredefines) {
246 // We are in the context of an implicit include, so the predefines buffer will
247 // have a #include entry for the PCH file itself (as normalized by the
248 // preprocessor initialization). Find it and skip over it in the checking
249 // below.
250 llvm::SmallString<256> PCHInclude;
251 PCHInclude += "#include \"";
252 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
253 PCHInclude += "\"\n";
254 std::pair<llvm::StringRef,llvm::StringRef> Split =
255 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
256 llvm::StringRef Left = Split.first, Right = Split.second;
257 if (Left == PP.getPredefines()) {
258 Error("Missing PCH include entry!");
259 return true;
262 // If the concatenation of all the PCH buffers is equal to the adjusted
263 // command line, we're done.
264 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
265 CommandLine.push_back(Left);
266 CommandLine.push_back(Right);
267 if (EqualConcatenations(CommandLine, Buffers))
268 return false;
270 SourceManager &SourceMgr = PP.getSourceManager();
272 // The predefines buffers are different. Determine what the differences are,
273 // and whether they require us to reject the PCH file.
274 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
275 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
276 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
278 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
279 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
281 // Pick out implicit #includes after the PCH and don't consider them for
282 // validation; we will insert them into SuggestedPredefines so that the
283 // preprocessor includes them.
284 std::string IncludesAfterPCH;
285 llvm::SmallVector<llvm::StringRef, 8> AfterPCHLines;
286 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
287 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
288 if (AfterPCHLines[i].startswith("#include ")) {
289 IncludesAfterPCH += AfterPCHLines[i];
290 IncludesAfterPCH += '\n';
291 } else {
292 CmdLineLines.push_back(AfterPCHLines[i]);
296 // Make sure we add the includes last into SuggestedPredefines before we
297 // exit this function.
298 struct AddIncludesRAII {
299 std::string &SuggestedPredefines;
300 std::string &IncludesAfterPCH;
302 AddIncludesRAII(std::string &SuggestedPredefines,
303 std::string &IncludesAfterPCH)
304 : SuggestedPredefines(SuggestedPredefines),
305 IncludesAfterPCH(IncludesAfterPCH) { }
306 ~AddIncludesRAII() {
307 SuggestedPredefines += IncludesAfterPCH;
309 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
311 // Sort both sets of predefined buffer lines, since we allow some extra
312 // definitions and they may appear at any point in the output.
313 std::sort(CmdLineLines.begin(), CmdLineLines.end());
314 std::sort(PCHLines.begin(), PCHLines.end());
316 // Determine which predefines that were used to build the PCH file are missing
317 // from the command line.
318 std::vector<llvm::StringRef> MissingPredefines;
319 std::set_difference(PCHLines.begin(), PCHLines.end(),
320 CmdLineLines.begin(), CmdLineLines.end(),
321 std::back_inserter(MissingPredefines));
323 bool MissingDefines = false;
324 bool ConflictingDefines = false;
325 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
326 llvm::StringRef Missing = MissingPredefines[I];
327 if (Missing.startswith("#include ")) {
328 // An -include was specified when generating the PCH; it is included in
329 // the PCH, just ignore it.
330 continue;
332 if (!Missing.startswith("#define ")) {
333 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
334 return true;
337 // This is a macro definition. Determine the name of the macro we're
338 // defining.
339 std::string::size_type StartOfMacroName = strlen("#define ");
340 std::string::size_type EndOfMacroName
341 = Missing.find_first_of("( \n\r", StartOfMacroName);
342 assert(EndOfMacroName != std::string::npos &&
343 "Couldn't find the end of the macro name");
344 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
346 // Determine whether this macro was given a different definition on the
347 // command line.
348 std::string MacroDefStart = "#define " + MacroName.str();
349 std::string::size_type MacroDefLen = MacroDefStart.size();
350 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
351 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
352 MacroDefStart);
353 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
354 if (!ConflictPos->startswith(MacroDefStart)) {
355 // Different macro; we're done.
356 ConflictPos = CmdLineLines.end();
357 break;
360 assert(ConflictPos->size() > MacroDefLen &&
361 "Invalid #define in predefines buffer?");
362 if ((*ConflictPos)[MacroDefLen] != ' ' &&
363 (*ConflictPos)[MacroDefLen] != '(')
364 continue; // Longer macro name; keep trying.
366 // We found a conflicting macro definition.
367 break;
370 if (ConflictPos != CmdLineLines.end()) {
371 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
372 << MacroName;
374 // Show the definition of this macro within the PCH file.
375 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
376 FindMacro(Buffers, Missing);
377 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
378 SourceLocation PCHMissingLoc =
379 SourceMgr.getLocForStartOfFile(MacroLoc.first)
380 .getFileLocWithOffset(MacroLoc.second);
381 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
383 ConflictingDefines = true;
384 continue;
387 // If the macro doesn't conflict, then we'll just pick up the macro
388 // definition from the PCH file. Warn the user that they made a mistake.
389 if (ConflictingDefines)
390 continue; // Don't complain if there are already conflicting defs
392 if (!MissingDefines) {
393 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
394 MissingDefines = true;
397 // Show the definition of this macro within the PCH file.
398 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
399 FindMacro(Buffers, Missing);
400 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
401 SourceLocation PCHMissingLoc =
402 SourceMgr.getLocForStartOfFile(MacroLoc.first)
403 .getFileLocWithOffset(MacroLoc.second);
404 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
407 if (ConflictingDefines)
408 return true;
410 // Determine what predefines were introduced based on command-line
411 // parameters that were not present when building the PCH
412 // file. Extra #defines are okay, so long as the identifiers being
413 // defined were not used within the precompiled header.
414 std::vector<llvm::StringRef> ExtraPredefines;
415 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
416 PCHLines.begin(), PCHLines.end(),
417 std::back_inserter(ExtraPredefines));
418 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
419 llvm::StringRef &Extra = ExtraPredefines[I];
420 if (!Extra.startswith("#define ")) {
421 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
422 return true;
425 // This is an extra macro definition. Determine the name of the
426 // macro we're defining.
427 std::string::size_type StartOfMacroName = strlen("#define ");
428 std::string::size_type EndOfMacroName
429 = Extra.find_first_of("( \n\r", StartOfMacroName);
430 assert(EndOfMacroName != std::string::npos &&
431 "Couldn't find the end of the macro name");
432 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
434 // Check whether this name was used somewhere in the PCH file. If
435 // so, defining it as a macro could change behavior, so we reject
436 // the PCH file.
437 if (IdentifierInfo *II = Reader.get(MacroName)) {
438 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
439 return true;
442 // Add this definition to the suggested predefines buffer.
443 SuggestedPredefines += Extra;
444 SuggestedPredefines += '\n';
447 // If we get here, it's because the predefines buffer had compatible
448 // contents. Accept the PCH file.
449 return false;
452 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
453 unsigned ID) {
454 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
455 ++NumHeaderInfos;
458 void PCHValidator::ReadCounter(unsigned Value) {
459 PP.setCounterValue(Value);
462 //===----------------------------------------------------------------------===//
463 // AST reader implementation
464 //===----------------------------------------------------------------------===//
466 void
467 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
468 DeserializationListener = Listener;
472 namespace {
473 class ASTSelectorLookupTrait {
474 ASTReader &Reader;
476 public:
477 struct data_type {
478 SelectorID ID;
479 ObjCMethodList Instance, Factory;
482 typedef Selector external_key_type;
483 typedef external_key_type internal_key_type;
485 explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { }
487 static bool EqualKey(const internal_key_type& a,
488 const internal_key_type& b) {
489 return a == b;
492 static unsigned ComputeHash(Selector Sel) {
493 return serialization::ComputeHash(Sel);
496 // This hopefully will just get inlined and removed by the optimizer.
497 static const internal_key_type&
498 GetInternalKey(const external_key_type& x) { return x; }
500 static std::pair<unsigned, unsigned>
501 ReadKeyDataLength(const unsigned char*& d) {
502 using namespace clang::io;
503 unsigned KeyLen = ReadUnalignedLE16(d);
504 unsigned DataLen = ReadUnalignedLE16(d);
505 return std::make_pair(KeyLen, DataLen);
508 internal_key_type ReadKey(const unsigned char* d, unsigned) {
509 using namespace clang::io;
510 SelectorTable &SelTable = Reader.getContext()->Selectors;
511 unsigned N = ReadUnalignedLE16(d);
512 IdentifierInfo *FirstII
513 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
514 if (N == 0)
515 return SelTable.getNullarySelector(FirstII);
516 else if (N == 1)
517 return SelTable.getUnarySelector(FirstII);
519 llvm::SmallVector<IdentifierInfo *, 16> Args;
520 Args.push_back(FirstII);
521 for (unsigned I = 1; I != N; ++I)
522 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
524 return SelTable.getSelector(N, Args.data());
527 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
528 using namespace clang::io;
530 data_type Result;
532 Result.ID = ReadUnalignedLE32(d);
533 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
534 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
536 // Load instance methods
537 ObjCMethodList *Prev = 0;
538 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
539 ObjCMethodDecl *Method
540 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
541 if (!Result.Instance.Method) {
542 // This is the first method, which is the easy case.
543 Result.Instance.Method = Method;
544 Prev = &Result.Instance;
545 continue;
548 ObjCMethodList *Mem =
549 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
550 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
551 Prev = Prev->Next;
554 // Load factory methods
555 Prev = 0;
556 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
557 ObjCMethodDecl *Method
558 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
559 if (!Result.Factory.Method) {
560 // This is the first method, which is the easy case.
561 Result.Factory.Method = Method;
562 Prev = &Result.Factory;
563 continue;
566 ObjCMethodList *Mem =
567 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
568 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
569 Prev = Prev->Next;
572 return Result;
576 } // end anonymous namespace
578 /// \brief The on-disk hash table used for the global method pool.
579 typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
580 ASTSelectorLookupTable;
582 namespace clang {
583 class ASTIdentifierLookupTrait {
584 ASTReader &Reader;
585 ASTReader::PerFileData &F;
587 // If we know the IdentifierInfo in advance, it is here and we will
588 // not build a new one. Used when deserializing information about an
589 // identifier that was constructed before the AST file was read.
590 IdentifierInfo *KnownII;
592 public:
593 typedef IdentifierInfo * data_type;
595 typedef const std::pair<const char*, unsigned> external_key_type;
597 typedef external_key_type internal_key_type;
599 ASTIdentifierLookupTrait(ASTReader &Reader, ASTReader::PerFileData &F,
600 IdentifierInfo *II = 0)
601 : Reader(Reader), F(F), KnownII(II) { }
603 static bool EqualKey(const internal_key_type& a,
604 const internal_key_type& b) {
605 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
606 : false;
609 static unsigned ComputeHash(const internal_key_type& a) {
610 return llvm::HashString(llvm::StringRef(a.first, a.second));
613 // This hopefully will just get inlined and removed by the optimizer.
614 static const internal_key_type&
615 GetInternalKey(const external_key_type& x) { return x; }
617 // This hopefully will just get inlined and removed by the optimizer.
618 static const external_key_type&
619 GetExternalKey(const internal_key_type& x) { return x; }
621 static std::pair<unsigned, unsigned>
622 ReadKeyDataLength(const unsigned char*& d) {
623 using namespace clang::io;
624 unsigned DataLen = ReadUnalignedLE16(d);
625 unsigned KeyLen = ReadUnalignedLE16(d);
626 return std::make_pair(KeyLen, DataLen);
629 static std::pair<const char*, unsigned>
630 ReadKey(const unsigned char* d, unsigned n) {
631 assert(n >= 2 && d[n-1] == '\0');
632 return std::make_pair((const char*) d, n-1);
635 IdentifierInfo *ReadData(const internal_key_type& k,
636 const unsigned char* d,
637 unsigned DataLen) {
638 using namespace clang::io;
639 IdentID ID = ReadUnalignedLE32(d);
640 bool IsInteresting = ID & 0x01;
642 // Wipe out the "is interesting" bit.
643 ID = ID >> 1;
645 if (!IsInteresting) {
646 // For uninteresting identifiers, just build the IdentifierInfo
647 // and associate it with the persistent ID.
648 IdentifierInfo *II = KnownII;
649 if (!II)
650 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
651 Reader.SetIdentifierInfo(ID, II);
652 II->setIsFromAST();
653 return II;
656 unsigned Bits = ReadUnalignedLE16(d);
657 bool CPlusPlusOperatorKeyword = Bits & 0x01;
658 Bits >>= 1;
659 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
660 Bits >>= 1;
661 bool Poisoned = Bits & 0x01;
662 Bits >>= 1;
663 bool ExtensionToken = Bits & 0x01;
664 Bits >>= 1;
665 bool hasMacroDefinition = Bits & 0x01;
666 Bits >>= 1;
667 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
668 Bits >>= 10;
670 assert(Bits == 0 && "Extra bits in the identifier?");
671 DataLen -= 6;
673 // Build the IdentifierInfo itself and link the identifier ID with
674 // the new IdentifierInfo.
675 IdentifierInfo *II = KnownII;
676 if (!II)
677 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
678 Reader.SetIdentifierInfo(ID, II);
680 // Set or check the various bits in the IdentifierInfo structure.
681 // Token IDs are read-only.
682 if (HasRevertedTokenIDToIdentifier)
683 II->RevertTokenIDToIdentifier();
684 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
685 assert(II->isExtensionToken() == ExtensionToken &&
686 "Incorrect extension token flag");
687 (void)ExtensionToken;
688 II->setIsPoisoned(Poisoned);
689 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
690 "Incorrect C++ operator keyword flag");
691 (void)CPlusPlusOperatorKeyword;
693 // If this identifier is a macro, deserialize the macro
694 // definition.
695 if (hasMacroDefinition) {
696 uint32_t Offset = ReadUnalignedLE32(d);
697 Reader.SetIdentifierIsMacro(II, F, Offset);
698 DataLen -= 4;
701 // Read all of the declarations visible at global scope with this
702 // name.
703 if (Reader.getContext() == 0) return II;
704 if (DataLen > 0) {
705 llvm::SmallVector<uint32_t, 4> DeclIDs;
706 for (; DataLen > 0; DataLen -= 4)
707 DeclIDs.push_back(ReadUnalignedLE32(d));
708 Reader.SetGloballyVisibleDecls(II, DeclIDs);
711 II->setIsFromAST();
712 return II;
716 } // end anonymous namespace
718 /// \brief The on-disk hash table used to contain information about
719 /// all of the identifiers in the program.
720 typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
721 ASTIdentifierLookupTable;
723 namespace {
724 class ASTDeclContextNameLookupTrait {
725 ASTReader &Reader;
727 public:
728 /// \brief Pair of begin/end iterators for DeclIDs.
729 typedef std::pair<DeclID *, DeclID *> data_type;
731 /// \brief Special internal key for declaration names.
732 /// The hash table creates keys for comparison; we do not create
733 /// a DeclarationName for the internal key to avoid deserializing types.
734 struct DeclNameKey {
735 DeclarationName::NameKind Kind;
736 uint64_t Data;
737 DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { }
740 typedef DeclarationName external_key_type;
741 typedef DeclNameKey internal_key_type;
743 explicit ASTDeclContextNameLookupTrait(ASTReader &Reader) : Reader(Reader) { }
745 static bool EqualKey(const internal_key_type& a,
746 const internal_key_type& b) {
747 return a.Kind == b.Kind && a.Data == b.Data;
750 unsigned ComputeHash(const DeclNameKey &Key) const {
751 llvm::FoldingSetNodeID ID;
752 ID.AddInteger(Key.Kind);
754 switch (Key.Kind) {
755 case DeclarationName::Identifier:
756 case DeclarationName::CXXLiteralOperatorName:
757 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
758 break;
759 case DeclarationName::ObjCZeroArgSelector:
760 case DeclarationName::ObjCOneArgSelector:
761 case DeclarationName::ObjCMultiArgSelector:
762 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
763 break;
764 case DeclarationName::CXXConstructorName:
765 case DeclarationName::CXXDestructorName:
766 case DeclarationName::CXXConversionFunctionName:
767 ID.AddInteger((TypeID)Key.Data);
768 break;
769 case DeclarationName::CXXOperatorName:
770 ID.AddInteger((OverloadedOperatorKind)Key.Data);
771 break;
772 case DeclarationName::CXXUsingDirective:
773 break;
776 return ID.ComputeHash();
779 internal_key_type GetInternalKey(const external_key_type& Name) const {
780 DeclNameKey Key;
781 Key.Kind = Name.getNameKind();
782 switch (Name.getNameKind()) {
783 case DeclarationName::Identifier:
784 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
785 break;
786 case DeclarationName::ObjCZeroArgSelector:
787 case DeclarationName::ObjCOneArgSelector:
788 case DeclarationName::ObjCMultiArgSelector:
789 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
790 break;
791 case DeclarationName::CXXConstructorName:
792 case DeclarationName::CXXDestructorName:
793 case DeclarationName::CXXConversionFunctionName:
794 Key.Data = Reader.GetTypeID(Name.getCXXNameType());
795 break;
796 case DeclarationName::CXXOperatorName:
797 Key.Data = Name.getCXXOverloadedOperator();
798 break;
799 case DeclarationName::CXXLiteralOperatorName:
800 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
801 break;
802 case DeclarationName::CXXUsingDirective:
803 break;
806 return Key;
809 external_key_type GetExternalKey(const internal_key_type& Key) const {
810 ASTContext *Context = Reader.getContext();
811 switch (Key.Kind) {
812 case DeclarationName::Identifier:
813 return DeclarationName((IdentifierInfo*)Key.Data);
815 case DeclarationName::ObjCZeroArgSelector:
816 case DeclarationName::ObjCOneArgSelector:
817 case DeclarationName::ObjCMultiArgSelector:
818 return DeclarationName(Selector(Key.Data));
820 case DeclarationName::CXXConstructorName:
821 return Context->DeclarationNames.getCXXConstructorName(
822 Context->getCanonicalType(Reader.GetType(Key.Data)));
824 case DeclarationName::CXXDestructorName:
825 return Context->DeclarationNames.getCXXDestructorName(
826 Context->getCanonicalType(Reader.GetType(Key.Data)));
828 case DeclarationName::CXXConversionFunctionName:
829 return Context->DeclarationNames.getCXXConversionFunctionName(
830 Context->getCanonicalType(Reader.GetType(Key.Data)));
832 case DeclarationName::CXXOperatorName:
833 return Context->DeclarationNames.getCXXOperatorName(
834 (OverloadedOperatorKind)Key.Data);
836 case DeclarationName::CXXLiteralOperatorName:
837 return Context->DeclarationNames.getCXXLiteralOperatorName(
838 (IdentifierInfo*)Key.Data);
840 case DeclarationName::CXXUsingDirective:
841 return DeclarationName::getUsingDirectiveName();
844 llvm_unreachable("Invalid Name Kind ?");
847 static std::pair<unsigned, unsigned>
848 ReadKeyDataLength(const unsigned char*& d) {
849 using namespace clang::io;
850 unsigned KeyLen = ReadUnalignedLE16(d);
851 unsigned DataLen = ReadUnalignedLE16(d);
852 return std::make_pair(KeyLen, DataLen);
855 internal_key_type ReadKey(const unsigned char* d, unsigned) {
856 using namespace clang::io;
858 DeclNameKey Key;
859 Key.Kind = (DeclarationName::NameKind)*d++;
860 switch (Key.Kind) {
861 case DeclarationName::Identifier:
862 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
863 break;
864 case DeclarationName::ObjCZeroArgSelector:
865 case DeclarationName::ObjCOneArgSelector:
866 case DeclarationName::ObjCMultiArgSelector:
867 Key.Data =
868 (uint64_t)Reader.DecodeSelector(ReadUnalignedLE32(d)).getAsOpaquePtr();
869 break;
870 case DeclarationName::CXXConstructorName:
871 case DeclarationName::CXXDestructorName:
872 case DeclarationName::CXXConversionFunctionName:
873 Key.Data = ReadUnalignedLE32(d); // TypeID
874 break;
875 case DeclarationName::CXXOperatorName:
876 Key.Data = *d++; // OverloadedOperatorKind
877 break;
878 case DeclarationName::CXXLiteralOperatorName:
879 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
880 break;
881 case DeclarationName::CXXUsingDirective:
882 break;
885 return Key;
888 data_type ReadData(internal_key_type, const unsigned char* d,
889 unsigned DataLen) {
890 using namespace clang::io;
891 unsigned NumDecls = ReadUnalignedLE16(d);
892 DeclID *Start = (DeclID *)d;
893 return std::make_pair(Start, Start + NumDecls);
897 } // end anonymous namespace
899 /// \brief The on-disk hash table used for the DeclContext's Name lookup table.
900 typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
901 ASTDeclContextNameLookupTable;
903 bool ASTReader::ReadDeclContextStorage(llvm::BitstreamCursor &Cursor,
904 const std::pair<uint64_t, uint64_t> &Offsets,
905 DeclContextInfo &Info) {
906 SavedStreamPosition SavedPosition(Cursor);
907 // First the lexical decls.
908 if (Offsets.first != 0) {
909 Cursor.JumpToBit(Offsets.first);
911 RecordData Record;
912 const char *Blob;
913 unsigned BlobLen;
914 unsigned Code = Cursor.ReadCode();
915 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
916 if (RecCode != DECL_CONTEXT_LEXICAL) {
917 Error("Expected lexical block");
918 return true;
921 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
922 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
923 } else {
924 Info.LexicalDecls = 0;
925 Info.NumLexicalDecls = 0;
928 // Now the lookup table.
929 if (Offsets.second != 0) {
930 Cursor.JumpToBit(Offsets.second);
932 RecordData Record;
933 const char *Blob;
934 unsigned BlobLen;
935 unsigned Code = Cursor.ReadCode();
936 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
937 if (RecCode != DECL_CONTEXT_VISIBLE) {
938 Error("Expected visible lookup table block");
939 return true;
941 Info.NameLookupTableData
942 = ASTDeclContextNameLookupTable::Create(
943 (const unsigned char *)Blob + Record[0],
944 (const unsigned char *)Blob,
945 ASTDeclContextNameLookupTrait(*this));
946 } else {
947 Info.NameLookupTableData = 0;
950 return false;
953 void ASTReader::Error(const char *Msg) {
954 Diag(diag::err_fe_pch_malformed) << Msg;
957 /// \brief Tell the AST listener about the predefines buffers in the chain.
958 bool ASTReader::CheckPredefinesBuffers() {
959 if (Listener)
960 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
961 ActualOriginalFileName,
962 SuggestedPredefines);
963 return false;
966 //===----------------------------------------------------------------------===//
967 // Source Manager Deserialization
968 //===----------------------------------------------------------------------===//
970 /// \brief Read the line table in the source manager block.
971 /// \returns true if there was an error.
972 bool ASTReader::ParseLineTable(PerFileData &F,
973 llvm::SmallVectorImpl<uint64_t> &Record) {
974 unsigned Idx = 0;
975 LineTableInfo &LineTable = SourceMgr.getLineTable();
977 // Parse the file names
978 std::map<int, int> FileIDs;
979 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
980 // Extract the file name
981 unsigned FilenameLen = Record[Idx++];
982 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
983 Idx += FilenameLen;
984 MaybeAddSystemRootToFilename(Filename);
985 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
986 Filename.size());
989 // Parse the line entries
990 std::vector<LineEntry> Entries;
991 while (Idx < Record.size()) {
992 int FID = Record[Idx++];
994 // Extract the line entries
995 unsigned NumEntries = Record[Idx++];
996 assert(NumEntries && "Numentries is 00000");
997 Entries.clear();
998 Entries.reserve(NumEntries);
999 for (unsigned I = 0; I != NumEntries; ++I) {
1000 unsigned FileOffset = Record[Idx++];
1001 unsigned LineNo = Record[Idx++];
1002 int FilenameID = FileIDs[Record[Idx++]];
1003 SrcMgr::CharacteristicKind FileKind
1004 = (SrcMgr::CharacteristicKind)Record[Idx++];
1005 unsigned IncludeOffset = Record[Idx++];
1006 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1007 FileKind, IncludeOffset));
1009 LineTable.AddEntry(FID, Entries);
1012 return false;
1015 namespace {
1017 class ASTStatData {
1018 public:
1019 const ino_t ino;
1020 const dev_t dev;
1021 const mode_t mode;
1022 const time_t mtime;
1023 const off_t size;
1025 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
1026 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
1029 class ASTStatLookupTrait {
1030 public:
1031 typedef const char *external_key_type;
1032 typedef const char *internal_key_type;
1034 typedef ASTStatData data_type;
1036 static unsigned ComputeHash(const char *path) {
1037 return llvm::HashString(path);
1040 static internal_key_type GetInternalKey(const char *path) { return path; }
1042 static bool EqualKey(internal_key_type a, internal_key_type b) {
1043 return strcmp(a, b) == 0;
1046 static std::pair<unsigned, unsigned>
1047 ReadKeyDataLength(const unsigned char*& d) {
1048 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1049 unsigned DataLen = (unsigned) *d++;
1050 return std::make_pair(KeyLen + 1, DataLen);
1053 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1054 return (const char *)d;
1057 static data_type ReadData(const internal_key_type, const unsigned char *d,
1058 unsigned /*DataLen*/) {
1059 using namespace clang::io;
1061 ino_t ino = (ino_t) ReadUnalignedLE32(d);
1062 dev_t dev = (dev_t) ReadUnalignedLE32(d);
1063 mode_t mode = (mode_t) ReadUnalignedLE16(d);
1064 time_t mtime = (time_t) ReadUnalignedLE64(d);
1065 off_t size = (off_t) ReadUnalignedLE64(d);
1066 return data_type(ino, dev, mode, mtime, size);
1070 /// \brief stat() cache for precompiled headers.
1072 /// This cache is very similar to the stat cache used by pretokenized
1073 /// headers.
1074 class ASTStatCache : public FileSystemStatCache {
1075 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
1076 CacheTy *Cache;
1078 unsigned &NumStatHits, &NumStatMisses;
1079 public:
1080 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1081 unsigned &NumStatHits, unsigned &NumStatMisses)
1082 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1083 Cache = CacheTy::Create(Buckets, Base);
1086 ~ASTStatCache() { delete Cache; }
1088 LookupResult getStat(const char *Path, struct stat &StatBuf,
1089 int *FileDescriptor) {
1090 // Do the lookup for the file's data in the AST file.
1091 CacheTy::iterator I = Cache->find(Path);
1093 // If we don't get a hit in the AST file just forward to 'stat'.
1094 if (I == Cache->end()) {
1095 ++NumStatMisses;
1096 return statChained(Path, StatBuf, FileDescriptor);
1099 ++NumStatHits;
1100 ASTStatData Data = *I;
1102 StatBuf.st_ino = Data.ino;
1103 StatBuf.st_dev = Data.dev;
1104 StatBuf.st_mtime = Data.mtime;
1105 StatBuf.st_mode = Data.mode;
1106 StatBuf.st_size = Data.size;
1107 return CacheExists;
1110 } // end anonymous namespace
1113 /// \brief Read a source manager block
1114 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) {
1115 using namespace SrcMgr;
1117 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1119 // Set the source-location entry cursor to the current position in
1120 // the stream. This cursor will be used to read the contents of the
1121 // source manager block initially, and then lazily read
1122 // source-location entries as needed.
1123 SLocEntryCursor = F.Stream;
1125 // The stream itself is going to skip over the source manager block.
1126 if (F.Stream.SkipBlock()) {
1127 Error("malformed block record in AST file");
1128 return Failure;
1131 // Enter the source manager block.
1132 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1133 Error("malformed source manager block record in AST file");
1134 return Failure;
1137 RecordData Record;
1138 while (true) {
1139 unsigned Code = SLocEntryCursor.ReadCode();
1140 if (Code == llvm::bitc::END_BLOCK) {
1141 if (SLocEntryCursor.ReadBlockEnd()) {
1142 Error("error at end of Source Manager block in AST file");
1143 return Failure;
1145 return Success;
1148 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1149 // No known subblocks, always skip them.
1150 SLocEntryCursor.ReadSubBlockID();
1151 if (SLocEntryCursor.SkipBlock()) {
1152 Error("malformed block record in AST file");
1153 return Failure;
1155 continue;
1158 if (Code == llvm::bitc::DEFINE_ABBREV) {
1159 SLocEntryCursor.ReadAbbrevRecord();
1160 continue;
1163 // Read a record.
1164 const char *BlobStart;
1165 unsigned BlobLen;
1166 Record.clear();
1167 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1168 default: // Default behavior: ignore.
1169 break;
1171 case SM_LINE_TABLE:
1172 if (ParseLineTable(F, Record))
1173 return Failure;
1174 break;
1176 case SM_SLOC_FILE_ENTRY:
1177 case SM_SLOC_BUFFER_ENTRY:
1178 case SM_SLOC_INSTANTIATION_ENTRY:
1179 // Once we hit one of the source location entries, we're done.
1180 return Success;
1185 /// \brief If a header file is not found at the path that we expect it to be
1186 /// and the PCH file was moved from its original location, try to resolve the
1187 /// file by assuming that header+PCH were moved together and the header is in
1188 /// the same place relative to the PCH.
1189 static std::string
1190 resolveFileRelativeToOriginalDir(const std::string &Filename,
1191 const std::string &OriginalDir,
1192 const std::string &CurrDir) {
1193 assert(OriginalDir != CurrDir &&
1194 "No point trying to resolve the file if the PCH dir didn't change");
1195 using namespace llvm::sys;
1196 llvm::SmallString<128> filePath(Filename);
1197 fs::make_absolute(filePath);
1198 assert(path::is_absolute(OriginalDir));
1199 llvm::SmallString<128> currPCHPath(CurrDir);
1201 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1202 fileDirE = path::end(path::parent_path(filePath));
1203 path::const_iterator origDirI = path::begin(OriginalDir),
1204 origDirE = path::end(OriginalDir);
1205 // Skip the common path components from filePath and OriginalDir.
1206 while (fileDirI != fileDirE && origDirI != origDirE &&
1207 *fileDirI == *origDirI) {
1208 ++fileDirI;
1209 ++origDirI;
1211 for (; origDirI != origDirE; ++origDirI)
1212 path::append(currPCHPath, "..");
1213 path::append(currPCHPath, fileDirI, fileDirE);
1214 path::append(currPCHPath, path::filename(Filename));
1215 return currPCHPath.str();
1218 /// \brief Get a cursor that's correctly positioned for reading the source
1219 /// location entry with the given ID.
1220 ASTReader::PerFileData *ASTReader::SLocCursorForID(unsigned ID) {
1221 assert(ID != 0 && ID <= TotalNumSLocEntries &&
1222 "SLocCursorForID should only be called for real IDs.");
1224 ID -= 1;
1225 PerFileData *F = 0;
1226 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1227 F = Chain[N - I - 1];
1228 if (ID < F->LocalNumSLocEntries)
1229 break;
1230 ID -= F->LocalNumSLocEntries;
1232 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
1234 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
1235 return F;
1238 /// \brief Read in the source location entry with the given ID.
1239 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(unsigned ID) {
1240 if (ID == 0)
1241 return Success;
1243 if (ID > TotalNumSLocEntries) {
1244 Error("source location entry ID out-of-range for AST file");
1245 return Failure;
1248 PerFileData *F = SLocCursorForID(ID);
1249 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1251 ++NumSLocEntriesRead;
1252 unsigned Code = SLocEntryCursor.ReadCode();
1253 if (Code == llvm::bitc::END_BLOCK ||
1254 Code == llvm::bitc::ENTER_SUBBLOCK ||
1255 Code == llvm::bitc::DEFINE_ABBREV) {
1256 Error("incorrectly-formatted source location entry in AST file");
1257 return Failure;
1260 RecordData Record;
1261 const char *BlobStart;
1262 unsigned BlobLen;
1263 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1264 default:
1265 Error("incorrectly-formatted source location entry in AST file");
1266 return Failure;
1268 case SM_SLOC_FILE_ENTRY: {
1269 std::string Filename(BlobStart, BlobStart + BlobLen);
1270 MaybeAddSystemRootToFilename(Filename);
1271 const FileEntry *File = FileMgr.getFile(Filename);
1272 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1273 OriginalDir != CurrentDir) {
1274 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1275 OriginalDir,
1276 CurrentDir);
1277 if (!resolved.empty())
1278 File = FileMgr.getFile(resolved);
1280 if (File == 0)
1281 File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1282 (time_t)Record[5]);
1283 if (File == 0) {
1284 std::string ErrorStr = "could not find file '";
1285 ErrorStr += Filename;
1286 ErrorStr += "' referenced by AST file";
1287 Error(ErrorStr.c_str());
1288 return Failure;
1291 if (Record.size() < 6) {
1292 Error("source location entry is incorrect");
1293 return Failure;
1296 if (!DisableValidation &&
1297 ((off_t)Record[4] != File->getSize()
1298 #if !defined(LLVM_ON_WIN32)
1299 // In our regression testing, the Windows file system seems to
1300 // have inconsistent modification times that sometimes
1301 // erroneously trigger this error-handling path.
1302 || (time_t)Record[5] != File->getModificationTime()
1303 #endif
1304 )) {
1305 Diag(diag::err_fe_pch_file_modified)
1306 << Filename;
1307 return Failure;
1310 FileID FID = SourceMgr.createFileID(File, ReadSourceLocation(*F, Record[1]),
1311 (SrcMgr::CharacteristicKind)Record[2],
1312 ID, Record[0]);
1313 if (Record[3])
1314 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1315 .setHasLineDirectives();
1317 break;
1320 case SM_SLOC_BUFFER_ENTRY: {
1321 const char *Name = BlobStart;
1322 unsigned Offset = Record[0];
1323 unsigned Code = SLocEntryCursor.ReadCode();
1324 Record.clear();
1325 unsigned RecCode
1326 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1328 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1329 Error("AST record has invalid code");
1330 return Failure;
1333 llvm::MemoryBuffer *Buffer
1334 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1335 Name);
1336 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
1338 if (strcmp(Name, "<built-in>") == 0) {
1339 PCHPredefinesBlock Block = {
1340 BufferID,
1341 llvm::StringRef(BlobStart, BlobLen - 1)
1343 PCHPredefinesBuffers.push_back(Block);
1346 break;
1349 case SM_SLOC_INSTANTIATION_ENTRY: {
1350 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1351 SourceMgr.createInstantiationLoc(SpellingLoc,
1352 ReadSourceLocation(*F, Record[2]),
1353 ReadSourceLocation(*F, Record[3]),
1354 Record[4],
1356 Record[0]);
1357 break;
1361 return Success;
1364 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1365 /// specified cursor. Read the abbreviations that are at the top of the block
1366 /// and then leave the cursor pointing into the block.
1367 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1368 unsigned BlockID) {
1369 if (Cursor.EnterSubBlock(BlockID)) {
1370 Error("malformed block record in AST file");
1371 return Failure;
1374 while (true) {
1375 uint64_t Offset = Cursor.GetCurrentBitNo();
1376 unsigned Code = Cursor.ReadCode();
1378 // We expect all abbrevs to be at the start of the block.
1379 if (Code != llvm::bitc::DEFINE_ABBREV) {
1380 Cursor.JumpToBit(Offset);
1381 return false;
1383 Cursor.ReadAbbrevRecord();
1387 PreprocessedEntity *ASTReader::ReadMacroRecord(PerFileData &F, uint64_t Offset) {
1388 assert(PP && "Forgot to set Preprocessor ?");
1389 llvm::BitstreamCursor &Stream = F.MacroCursor;
1391 // Keep track of where we are in the stream, then jump back there
1392 // after reading this macro.
1393 SavedStreamPosition SavedPosition(Stream);
1395 Stream.JumpToBit(Offset);
1396 RecordData Record;
1397 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1398 MacroInfo *Macro = 0;
1400 while (true) {
1401 unsigned Code = Stream.ReadCode();
1402 switch (Code) {
1403 case llvm::bitc::END_BLOCK:
1404 return 0;
1406 case llvm::bitc::ENTER_SUBBLOCK:
1407 // No known subblocks, always skip them.
1408 Stream.ReadSubBlockID();
1409 if (Stream.SkipBlock()) {
1410 Error("malformed block record in AST file");
1411 return 0;
1413 continue;
1415 case llvm::bitc::DEFINE_ABBREV:
1416 Stream.ReadAbbrevRecord();
1417 continue;
1418 default: break;
1421 // Read a record.
1422 const char *BlobStart = 0;
1423 unsigned BlobLen = 0;
1424 Record.clear();
1425 PreprocessorRecordTypes RecType =
1426 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1427 BlobLen);
1428 switch (RecType) {
1429 case PP_MACRO_OBJECT_LIKE:
1430 case PP_MACRO_FUNCTION_LIKE: {
1431 // If we already have a macro, that means that we've hit the end
1432 // of the definition of the macro we were looking for. We're
1433 // done.
1434 if (Macro)
1435 return 0;
1437 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1438 if (II == 0) {
1439 Error("macro must have a name in AST file");
1440 return 0;
1442 SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1443 bool isUsed = Record[2];
1445 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1446 MI->setIsUsed(isUsed);
1447 MI->setIsFromAST();
1449 unsigned NextIndex = 3;
1450 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1451 // Decode function-like macro info.
1452 bool isC99VarArgs = Record[3];
1453 bool isGNUVarArgs = Record[4];
1454 MacroArgs.clear();
1455 unsigned NumArgs = Record[5];
1456 NextIndex = 6 + NumArgs;
1457 for (unsigned i = 0; i != NumArgs; ++i)
1458 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1460 // Install function-like macro info.
1461 MI->setIsFunctionLike();
1462 if (isC99VarArgs) MI->setIsC99Varargs();
1463 if (isGNUVarArgs) MI->setIsGNUVarargs();
1464 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1465 PP->getPreprocessorAllocator());
1468 // Finally, install the macro.
1469 PP->setMacroInfo(II, MI);
1471 // Remember that we saw this macro last so that we add the tokens that
1472 // form its body to it.
1473 Macro = MI;
1475 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1476 // We have a macro definition. Load it now.
1477 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1478 getMacroDefinition(Record[NextIndex]));
1481 ++NumMacrosRead;
1482 break;
1485 case PP_TOKEN: {
1486 // If we see a TOKEN before a PP_MACRO_*, then the file is
1487 // erroneous, just pretend we didn't see this.
1488 if (Macro == 0) break;
1490 Token Tok;
1491 Tok.startToken();
1492 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1493 Tok.setLength(Record[1]);
1494 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1495 Tok.setIdentifierInfo(II);
1496 Tok.setKind((tok::TokenKind)Record[3]);
1497 Tok.setFlag((Token::TokenFlags)Record[4]);
1498 Macro->AddTokenToBody(Tok);
1499 break;
1504 return 0;
1507 PreprocessedEntity *ASTReader::LoadPreprocessedEntity(PerFileData &F) {
1508 assert(PP && "Forgot to set Preprocessor ?");
1509 unsigned Code = F.PreprocessorDetailCursor.ReadCode();
1510 switch (Code) {
1511 case llvm::bitc::END_BLOCK:
1512 return 0;
1514 case llvm::bitc::ENTER_SUBBLOCK:
1515 Error("unexpected subblock record in preprocessor detail block");
1516 return 0;
1518 case llvm::bitc::DEFINE_ABBREV:
1519 Error("unexpected abbrevation record in preprocessor detail block");
1520 return 0;
1522 default:
1523 break;
1526 if (!PP->getPreprocessingRecord()) {
1527 Error("no preprocessing record");
1528 return 0;
1531 // Read the record.
1532 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1533 const char *BlobStart = 0;
1534 unsigned BlobLen = 0;
1535 RecordData Record;
1536 PreprocessorDetailRecordTypes RecType =
1537 (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord(
1538 Code, Record, BlobStart, BlobLen);
1539 switch (RecType) {
1540 case PPD_MACRO_INSTANTIATION: {
1541 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1542 return PE;
1544 MacroInstantiation *MI
1545 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1546 SourceRange(ReadSourceLocation(F, Record[1]),
1547 ReadSourceLocation(F, Record[2])),
1548 getMacroDefinition(Record[4]));
1549 PPRec.SetPreallocatedEntity(Record[0], MI);
1550 return MI;
1553 case PPD_MACRO_DEFINITION: {
1554 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1555 return PE;
1557 if (Record[1] > MacroDefinitionsLoaded.size()) {
1558 Error("out-of-bounds macro definition record");
1559 return 0;
1562 // Decode the identifier info and then check again; if the macro is
1563 // still defined and associated with the identifier,
1564 IdentifierInfo *II = DecodeIdentifierInfo(Record[4]);
1565 if (!MacroDefinitionsLoaded[Record[1] - 1]) {
1566 MacroDefinition *MD
1567 = new (PPRec) MacroDefinition(II,
1568 ReadSourceLocation(F, Record[5]),
1569 SourceRange(
1570 ReadSourceLocation(F, Record[2]),
1571 ReadSourceLocation(F, Record[3])));
1573 PPRec.SetPreallocatedEntity(Record[0], MD);
1574 MacroDefinitionsLoaded[Record[1] - 1] = MD;
1576 if (DeserializationListener)
1577 DeserializationListener->MacroDefinitionRead(Record[1], MD);
1580 return MacroDefinitionsLoaded[Record[1] - 1];
1583 case PPD_INCLUSION_DIRECTIVE: {
1584 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1585 return PE;
1587 const char *FullFileNameStart = BlobStart + Record[3];
1588 const FileEntry *File
1589 = PP->getFileManager().getFile(llvm::StringRef(FullFileNameStart,
1590 BlobLen - Record[3]));
1592 // FIXME: Stable encoding
1593 InclusionDirective::InclusionKind Kind
1594 = static_cast<InclusionDirective::InclusionKind>(Record[5]);
1595 InclusionDirective *ID
1596 = new (PPRec) InclusionDirective(PPRec, Kind,
1597 llvm::StringRef(BlobStart, Record[3]),
1598 Record[4],
1599 File,
1600 SourceRange(ReadSourceLocation(F, Record[1]),
1601 ReadSourceLocation(F, Record[2])));
1602 PPRec.SetPreallocatedEntity(Record[0], ID);
1603 return ID;
1607 Error("invalid offset in preprocessor detail block");
1608 return 0;
1611 namespace {
1612 /// \brief Trait class used to search the on-disk hash table containing all of
1613 /// the header search information.
1615 /// The on-disk hash table contains a mapping from each header path to
1616 /// information about that header (how many times it has been included, its
1617 /// controlling macro, etc.). Note that we actually hash based on the
1618 /// filename, and support "deep" comparisons of file names based on current
1619 /// inode numbers, so that the search can cope with non-normalized path names
1620 /// and symlinks.
1621 class HeaderFileInfoTrait {
1622 const char *SearchPath;
1623 struct stat SearchPathStatBuf;
1624 llvm::Optional<int> SearchPathStatResult;
1626 int StatSimpleCache(const char *Path, struct stat *StatBuf) {
1627 if (Path == SearchPath) {
1628 if (!SearchPathStatResult)
1629 SearchPathStatResult = stat(Path, &SearchPathStatBuf);
1631 *StatBuf = SearchPathStatBuf;
1632 return *SearchPathStatResult;
1635 return stat(Path, StatBuf);
1638 public:
1639 typedef const char *external_key_type;
1640 typedef const char *internal_key_type;
1642 typedef HeaderFileInfo data_type;
1644 HeaderFileInfoTrait(const char *SearchPath = 0) : SearchPath(SearchPath) { }
1646 static unsigned ComputeHash(const char *path) {
1647 return llvm::HashString(llvm::sys::path::filename(path));
1650 static internal_key_type GetInternalKey(const char *path) { return path; }
1652 bool EqualKey(internal_key_type a, internal_key_type b) {
1653 if (strcmp(a, b) == 0)
1654 return true;
1656 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1657 return false;
1659 // The file names match, but the path names don't. stat() the files to
1660 // see if they are the same.
1661 struct stat StatBufA, StatBufB;
1662 if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1663 return false;
1665 return StatBufA.st_ino == StatBufB.st_ino;
1668 static std::pair<unsigned, unsigned>
1669 ReadKeyDataLength(const unsigned char*& d) {
1670 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1671 unsigned DataLen = (unsigned) *d++;
1672 return std::make_pair(KeyLen + 1, DataLen);
1675 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1676 return (const char *)d;
1679 static data_type ReadData(const internal_key_type, const unsigned char *d,
1680 unsigned DataLen) {
1681 const unsigned char *End = d + DataLen;
1682 using namespace clang::io;
1683 HeaderFileInfo HFI;
1684 unsigned Flags = *d++;
1685 HFI.isImport = (Flags >> 3) & 0x01;
1686 HFI.DirInfo = (Flags >> 1) & 0x03;
1687 HFI.Resolved = Flags & 0x01;
1688 HFI.NumIncludes = ReadUnalignedLE16(d);
1689 HFI.ControllingMacroID = ReadUnalignedLE32(d);
1690 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1691 (void)End;
1693 // This HeaderFileInfo was externally loaded.
1694 HFI.External = true;
1695 return HFI;
1700 /// \brief The on-disk hash table used for the global method pool.
1701 typedef OnDiskChainedHashTable<HeaderFileInfoTrait>
1702 HeaderFileInfoLookupTable;
1704 void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, PerFileData &F,
1705 uint64_t Offset) {
1706 // Note that this identifier has a macro definition.
1707 II->setHasMacroDefinition(true);
1709 // Adjust the offset based on our position in the chain.
1710 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1711 if (Chain[I] == &F)
1712 break;
1714 Offset += Chain[I]->SizeInBits;
1717 UnreadMacroRecordOffsets[II] = Offset;
1720 void ASTReader::ReadDefinedMacros() {
1721 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1722 PerFileData &F = *Chain[N - I - 1];
1723 llvm::BitstreamCursor &MacroCursor = F.MacroCursor;
1725 // If there was no preprocessor block, skip this file.
1726 if (!MacroCursor.getBitStreamReader())
1727 continue;
1729 llvm::BitstreamCursor Cursor = MacroCursor;
1730 Cursor.JumpToBit(F.MacroStartOffset);
1732 RecordData Record;
1733 while (true) {
1734 unsigned Code = Cursor.ReadCode();
1735 if (Code == llvm::bitc::END_BLOCK)
1736 break;
1738 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1739 // No known subblocks, always skip them.
1740 Cursor.ReadSubBlockID();
1741 if (Cursor.SkipBlock()) {
1742 Error("malformed block record in AST file");
1743 return;
1745 continue;
1748 if (Code == llvm::bitc::DEFINE_ABBREV) {
1749 Cursor.ReadAbbrevRecord();
1750 continue;
1753 // Read a record.
1754 const char *BlobStart;
1755 unsigned BlobLen;
1756 Record.clear();
1757 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1758 default: // Default behavior: ignore.
1759 break;
1761 case PP_MACRO_OBJECT_LIKE:
1762 case PP_MACRO_FUNCTION_LIKE:
1763 DecodeIdentifierInfo(Record[0]);
1764 break;
1766 case PP_TOKEN:
1767 // Ignore tokens.
1768 break;
1773 // Drain the unread macro-record offsets map.
1774 while (!UnreadMacroRecordOffsets.empty())
1775 LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1778 void ASTReader::LoadMacroDefinition(
1779 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1780 assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1781 PerFileData *F = 0;
1782 uint64_t Offset = Pos->second;
1783 UnreadMacroRecordOffsets.erase(Pos);
1785 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1786 if (Offset < Chain[I]->SizeInBits) {
1787 F = Chain[I];
1788 break;
1791 Offset -= Chain[I]->SizeInBits;
1793 if (!F) {
1794 Error("Malformed macro record offset");
1795 return;
1798 ReadMacroRecord(*F, Offset);
1801 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1802 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1803 = UnreadMacroRecordOffsets.find(II);
1804 LoadMacroDefinition(Pos);
1807 MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
1808 if (ID == 0 || ID > MacroDefinitionsLoaded.size())
1809 return 0;
1811 if (!MacroDefinitionsLoaded[ID - 1]) {
1812 unsigned Index = ID - 1;
1813 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1814 PerFileData &F = *Chain[N - I - 1];
1815 if (Index < F.LocalNumMacroDefinitions) {
1816 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
1817 F.PreprocessorDetailCursor.JumpToBit(F.MacroDefinitionOffsets[Index]);
1818 LoadPreprocessedEntity(F);
1819 break;
1821 Index -= F.LocalNumMacroDefinitions;
1823 assert(MacroDefinitionsLoaded[ID - 1] && "Broken chain");
1826 return MacroDefinitionsLoaded[ID - 1];
1829 /// \brief If we are loading a relocatable PCH file, and the filename is
1830 /// not an absolute path, add the system root to the beginning of the file
1831 /// name.
1832 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1833 // If this is not a relocatable PCH file, there's nothing to do.
1834 if (!RelocatablePCH)
1835 return;
1837 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1838 return;
1840 if (isysroot == 0) {
1841 // If no system root was given, default to '/'
1842 Filename.insert(Filename.begin(), '/');
1843 return;
1846 unsigned Length = strlen(isysroot);
1847 if (isysroot[Length - 1] != '/')
1848 Filename.insert(Filename.begin(), '/');
1850 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1853 ASTReader::ASTReadResult
1854 ASTReader::ReadASTBlock(PerFileData &F) {
1855 llvm::BitstreamCursor &Stream = F.Stream;
1857 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1858 Error("malformed block record in AST file");
1859 return Failure;
1862 // Read all of the records and blocks for the ASt file.
1863 RecordData Record;
1864 bool First = true;
1865 while (!Stream.AtEndOfStream()) {
1866 unsigned Code = Stream.ReadCode();
1867 if (Code == llvm::bitc::END_BLOCK) {
1868 if (Stream.ReadBlockEnd()) {
1869 Error("error at end of module block in AST file");
1870 return Failure;
1873 return Success;
1876 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1877 switch (Stream.ReadSubBlockID()) {
1878 case DECLTYPES_BLOCK_ID:
1879 // We lazily load the decls block, but we want to set up the
1880 // DeclsCursor cursor to point into it. Clone our current bitcode
1881 // cursor to it, enter the block and read the abbrevs in that block.
1882 // With the main cursor, we just skip over it.
1883 F.DeclsCursor = Stream;
1884 if (Stream.SkipBlock() || // Skip with the main cursor.
1885 // Read the abbrevs.
1886 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1887 Error("malformed block record in AST file");
1888 return Failure;
1890 break;
1892 case DECL_UPDATES_BLOCK_ID:
1893 if (Stream.SkipBlock()) {
1894 Error("malformed block record in AST file");
1895 return Failure;
1897 break;
1899 case PREPROCESSOR_BLOCK_ID:
1900 F.MacroCursor = Stream;
1901 if (PP)
1902 PP->setExternalSource(this);
1904 if (Stream.SkipBlock() ||
1905 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1906 Error("malformed block record in AST file");
1907 return Failure;
1909 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1910 break;
1912 case PREPROCESSOR_DETAIL_BLOCK_ID:
1913 F.PreprocessorDetailCursor = Stream;
1914 if (Stream.SkipBlock() ||
1915 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1916 PREPROCESSOR_DETAIL_BLOCK_ID)) {
1917 Error("malformed preprocessor detail record in AST file");
1918 return Failure;
1920 F.PreprocessorDetailStartOffset
1921 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1922 break;
1924 case SOURCE_MANAGER_BLOCK_ID:
1925 switch (ReadSourceManagerBlock(F)) {
1926 case Success:
1927 break;
1929 case Failure:
1930 Error("malformed source manager block in AST file");
1931 return Failure;
1933 case IgnorePCH:
1934 return IgnorePCH;
1936 break;
1938 First = false;
1939 continue;
1942 if (Code == llvm::bitc::DEFINE_ABBREV) {
1943 Stream.ReadAbbrevRecord();
1944 continue;
1947 // Read and process a record.
1948 Record.clear();
1949 const char *BlobStart = 0;
1950 unsigned BlobLen = 0;
1951 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1952 &BlobStart, &BlobLen)) {
1953 default: // Default behavior: ignore.
1954 break;
1956 case METADATA: {
1957 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1958 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1959 : diag::warn_pch_version_too_new);
1960 return IgnorePCH;
1963 RelocatablePCH = Record[4];
1964 if (Listener) {
1965 std::string TargetTriple(BlobStart, BlobLen);
1966 if (Listener->ReadTargetTriple(TargetTriple))
1967 return IgnorePCH;
1969 break;
1972 case CHAINED_METADATA: {
1973 if (!First) {
1974 Error("CHAINED_METADATA is not first record in block");
1975 return Failure;
1977 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1978 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1979 : diag::warn_pch_version_too_new);
1980 return IgnorePCH;
1983 // Load the chained file, which is always a PCH file.
1984 switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen), PCH)) {
1985 case Failure: return Failure;
1986 // If we have to ignore the dependency, we'll have to ignore this too.
1987 case IgnorePCH: return IgnorePCH;
1988 case Success: break;
1990 break;
1993 case TYPE_OFFSET:
1994 if (F.LocalNumTypes != 0) {
1995 Error("duplicate TYPE_OFFSET record in AST file");
1996 return Failure;
1998 F.TypeOffsets = (const uint32_t *)BlobStart;
1999 F.LocalNumTypes = Record[0];
2000 break;
2002 case DECL_OFFSET:
2003 if (F.LocalNumDecls != 0) {
2004 Error("duplicate DECL_OFFSET record in AST file");
2005 return Failure;
2007 F.DeclOffsets = (const uint32_t *)BlobStart;
2008 F.LocalNumDecls = Record[0];
2009 break;
2011 case TU_UPDATE_LEXICAL: {
2012 DeclContextInfo Info = {
2013 /* No visible information */ 0,
2014 reinterpret_cast<const KindDeclIDPair *>(BlobStart),
2015 BlobLen / sizeof(KindDeclIDPair)
2017 DeclContextOffsets[Context ? Context->getTranslationUnitDecl() : 0]
2018 .push_back(Info);
2019 break;
2022 case UPDATE_VISIBLE: {
2023 serialization::DeclID ID = Record[0];
2024 void *Table = ASTDeclContextNameLookupTable::Create(
2025 (const unsigned char *)BlobStart + Record[1],
2026 (const unsigned char *)BlobStart,
2027 ASTDeclContextNameLookupTrait(*this));
2028 if (ID == 1 && Context) { // Is it the TU?
2029 DeclContextInfo Info = {
2030 Table, /* No lexical inforamtion */ 0, 0
2032 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
2033 } else
2034 PendingVisibleUpdates[ID].push_back(Table);
2035 break;
2038 case REDECLS_UPDATE_LATEST: {
2039 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
2040 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
2041 DeclID First = Record[i], Latest = Record[i+1];
2042 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
2043 Latest > FirstLatestDeclIDs[First]) &&
2044 "The new latest is supposed to come after the previous latest");
2045 FirstLatestDeclIDs[First] = Latest;
2047 break;
2050 case LANGUAGE_OPTIONS:
2051 if (ParseLanguageOptions(Record) && !DisableValidation)
2052 return IgnorePCH;
2053 break;
2055 case IDENTIFIER_TABLE:
2056 F.IdentifierTableData = BlobStart;
2057 if (Record[0]) {
2058 F.IdentifierLookupTable
2059 = ASTIdentifierLookupTable::Create(
2060 (const unsigned char *)F.IdentifierTableData + Record[0],
2061 (const unsigned char *)F.IdentifierTableData,
2062 ASTIdentifierLookupTrait(*this, F));
2063 if (PP)
2064 PP->getIdentifierTable().setExternalIdentifierLookup(this);
2066 break;
2068 case IDENTIFIER_OFFSET:
2069 if (F.LocalNumIdentifiers != 0) {
2070 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2071 return Failure;
2073 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2074 F.LocalNumIdentifiers = Record[0];
2075 break;
2077 case EXTERNAL_DEFINITIONS:
2078 // Optimization for the first block.
2079 if (ExternalDefinitions.empty())
2080 ExternalDefinitions.swap(Record);
2081 else
2082 ExternalDefinitions.insert(ExternalDefinitions.end(),
2083 Record.begin(), Record.end());
2084 break;
2086 case SPECIAL_TYPES:
2087 // Optimization for the first block
2088 if (SpecialTypes.empty())
2089 SpecialTypes.swap(Record);
2090 else
2091 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
2092 break;
2094 case STATISTICS:
2095 TotalNumStatements += Record[0];
2096 TotalNumMacros += Record[1];
2097 TotalLexicalDeclContexts += Record[2];
2098 TotalVisibleDeclContexts += Record[3];
2099 break;
2101 case TENTATIVE_DEFINITIONS:
2102 // Optimization for the first block.
2103 if (TentativeDefinitions.empty())
2104 TentativeDefinitions.swap(Record);
2105 else
2106 TentativeDefinitions.insert(TentativeDefinitions.end(),
2107 Record.begin(), Record.end());
2108 break;
2110 case UNUSED_FILESCOPED_DECLS:
2111 // Optimization for the first block.
2112 if (UnusedFileScopedDecls.empty())
2113 UnusedFileScopedDecls.swap(Record);
2114 else
2115 UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(),
2116 Record.begin(), Record.end());
2117 break;
2119 case WEAK_UNDECLARED_IDENTIFIERS:
2120 // Later blocks overwrite earlier ones.
2121 WeakUndeclaredIdentifiers.swap(Record);
2122 break;
2124 case LOCALLY_SCOPED_EXTERNAL_DECLS:
2125 // Optimization for the first block.
2126 if (LocallyScopedExternalDecls.empty())
2127 LocallyScopedExternalDecls.swap(Record);
2128 else
2129 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
2130 Record.begin(), Record.end());
2131 break;
2133 case SELECTOR_OFFSETS:
2134 F.SelectorOffsets = (const uint32_t *)BlobStart;
2135 F.LocalNumSelectors = Record[0];
2136 break;
2138 case METHOD_POOL:
2139 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2140 if (Record[0])
2141 F.SelectorLookupTable
2142 = ASTSelectorLookupTable::Create(
2143 F.SelectorLookupTableData + Record[0],
2144 F.SelectorLookupTableData,
2145 ASTSelectorLookupTrait(*this));
2146 TotalNumMethodPoolEntries += Record[1];
2147 break;
2149 case REFERENCED_SELECTOR_POOL:
2150 F.ReferencedSelectorsData.swap(Record);
2151 break;
2153 case PP_COUNTER_VALUE:
2154 if (!Record.empty() && Listener)
2155 Listener->ReadCounter(Record[0]);
2156 break;
2158 case SOURCE_LOCATION_OFFSETS:
2159 F.SLocOffsets = (const uint32_t *)BlobStart;
2160 F.LocalNumSLocEntries = Record[0];
2161 F.LocalSLocSize = Record[1];
2162 break;
2164 case SOURCE_LOCATION_PRELOADS:
2165 if (PreloadSLocEntries.empty())
2166 PreloadSLocEntries.swap(Record);
2167 else
2168 PreloadSLocEntries.insert(PreloadSLocEntries.end(),
2169 Record.begin(), Record.end());
2170 break;
2172 case STAT_CACHE: {
2173 if (!DisableStatCache) {
2174 ASTStatCache *MyStatCache =
2175 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2176 (const unsigned char *)BlobStart,
2177 NumStatHits, NumStatMisses);
2178 FileMgr.addStatCache(MyStatCache);
2179 F.StatCache = MyStatCache;
2181 break;
2184 case EXT_VECTOR_DECLS:
2185 // Optimization for the first block.
2186 if (ExtVectorDecls.empty())
2187 ExtVectorDecls.swap(Record);
2188 else
2189 ExtVectorDecls.insert(ExtVectorDecls.end(),
2190 Record.begin(), Record.end());
2191 break;
2193 case VTABLE_USES:
2194 // Later tables overwrite earlier ones.
2195 VTableUses.swap(Record);
2196 break;
2198 case DYNAMIC_CLASSES:
2199 // Optimization for the first block.
2200 if (DynamicClasses.empty())
2201 DynamicClasses.swap(Record);
2202 else
2203 DynamicClasses.insert(DynamicClasses.end(),
2204 Record.begin(), Record.end());
2205 break;
2207 case PENDING_IMPLICIT_INSTANTIATIONS:
2208 F.PendingInstantiations.swap(Record);
2209 break;
2211 case SEMA_DECL_REFS:
2212 // Later tables overwrite earlier ones.
2213 SemaDeclRefs.swap(Record);
2214 break;
2216 case ORIGINAL_FILE_NAME:
2217 // The primary AST will be the last to get here, so it will be the one
2218 // that's used.
2219 ActualOriginalFileName.assign(BlobStart, BlobLen);
2220 OriginalFileName = ActualOriginalFileName;
2221 MaybeAddSystemRootToFilename(OriginalFileName);
2222 break;
2224 case ORIGINAL_PCH_DIR:
2225 // The primary AST will be the last to get here, so it will be the one
2226 // that's used.
2227 OriginalDir.assign(BlobStart, BlobLen);
2228 break;
2230 case VERSION_CONTROL_BRANCH_REVISION: {
2231 const std::string &CurBranch = getClangFullRepositoryVersion();
2232 llvm::StringRef ASTBranch(BlobStart, BlobLen);
2233 if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2234 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2235 return IgnorePCH;
2237 break;
2240 case MACRO_DEFINITION_OFFSETS:
2241 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
2242 F.NumPreallocatedPreprocessingEntities = Record[0];
2243 F.LocalNumMacroDefinitions = Record[1];
2244 break;
2246 case DECL_UPDATE_OFFSETS: {
2247 if (Record.size() % 2 != 0) {
2248 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2249 return Failure;
2251 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2252 DeclUpdateOffsets[static_cast<DeclID>(Record[I])]
2253 .push_back(std::make_pair(&F, Record[I+1]));
2254 break;
2257 case DECL_REPLACEMENTS: {
2258 if (Record.size() % 2 != 0) {
2259 Error("invalid DECL_REPLACEMENTS block in AST file");
2260 return Failure;
2262 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2263 ReplacedDecls[static_cast<DeclID>(Record[I])] =
2264 std::make_pair(&F, Record[I+1]);
2265 break;
2268 case CXX_BASE_SPECIFIER_OFFSETS: {
2269 if (F.LocalNumCXXBaseSpecifiers != 0) {
2270 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2271 return Failure;
2274 F.LocalNumCXXBaseSpecifiers = Record[0];
2275 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2276 break;
2279 case DIAG_PRAGMA_MAPPINGS:
2280 if (Record.size() % 2 != 0) {
2281 Error("invalid DIAG_USER_MAPPINGS block in AST file");
2282 return Failure;
2284 if (PragmaDiagMappings.empty())
2285 PragmaDiagMappings.swap(Record);
2286 else
2287 PragmaDiagMappings.insert(PragmaDiagMappings.end(),
2288 Record.begin(), Record.end());
2289 break;
2291 case CUDA_SPECIAL_DECL_REFS:
2292 // Later tables overwrite earlier ones.
2293 CUDASpecialDeclRefs.swap(Record);
2294 break;
2296 case HEADER_SEARCH_TABLE:
2297 F.HeaderFileInfoTableData = BlobStart;
2298 F.LocalNumHeaderFileInfos = Record[1];
2299 if (Record[0]) {
2300 F.HeaderFileInfoTable
2301 = HeaderFileInfoLookupTable::Create(
2302 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2303 (const unsigned char *)F.HeaderFileInfoTableData);
2304 if (PP)
2305 PP->getHeaderSearchInfo().SetExternalSource(this);
2307 break;
2309 case FP_PRAGMA_OPTIONS:
2310 // Later tables overwrite earlier ones.
2311 FPPragmaOptions.swap(Record);
2312 break;
2314 case OPENCL_EXTENSIONS:
2315 // Later tables overwrite earlier ones.
2316 OpenCLExtensions.swap(Record);
2317 break;
2319 First = false;
2321 Error("premature end of bitstream in AST file");
2322 return Failure;
2325 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2326 ASTFileType Type) {
2327 switch(ReadASTCore(FileName, Type)) {
2328 case Failure: return Failure;
2329 case IgnorePCH: return IgnorePCH;
2330 case Success: break;
2333 // Here comes stuff that we only do once the entire chain is loaded.
2335 // Allocate space for loaded slocentries, identifiers, decls and types.
2336 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
2337 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
2338 TotalNumSelectors = 0;
2339 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2340 TotalNumSLocEntries += Chain[I]->LocalNumSLocEntries;
2341 NextSLocOffset += Chain[I]->LocalSLocSize;
2342 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
2343 TotalNumTypes += Chain[I]->LocalNumTypes;
2344 TotalNumDecls += Chain[I]->LocalNumDecls;
2345 TotalNumPreallocatedPreprocessingEntities +=
2346 Chain[I]->NumPreallocatedPreprocessingEntities;
2347 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
2348 TotalNumSelectors += Chain[I]->LocalNumSelectors;
2350 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, NextSLocOffset);
2351 IdentifiersLoaded.resize(TotalNumIdentifiers);
2352 TypesLoaded.resize(TotalNumTypes);
2353 DeclsLoaded.resize(TotalNumDecls);
2354 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
2355 if (PP) {
2356 if (TotalNumIdentifiers > 0)
2357 PP->getHeaderSearchInfo().SetExternalLookup(this);
2358 if (TotalNumPreallocatedPreprocessingEntities > 0) {
2359 if (!PP->getPreprocessingRecord())
2360 PP->createPreprocessingRecord();
2361 PP->getPreprocessingRecord()->SetExternalSource(*this,
2362 TotalNumPreallocatedPreprocessingEntities);
2365 SelectorsLoaded.resize(TotalNumSelectors);
2366 // Preload SLocEntries.
2367 for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) {
2368 ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]);
2369 if (Result != Success)
2370 return Result;
2373 // Check the predefines buffers.
2374 if (!DisableValidation && CheckPredefinesBuffers())
2375 return IgnorePCH;
2377 if (PP) {
2378 // Initialization of keywords and pragmas occurs before the
2379 // AST file is read, so there may be some identifiers that were
2380 // loaded into the IdentifierTable before we intercepted the
2381 // creation of identifiers. Iterate through the list of known
2382 // identifiers and determine whether we have to establish
2383 // preprocessor definitions or top-level identifier declaration
2384 // chains for those identifiers.
2386 // We copy the IdentifierInfo pointers to a small vector first,
2387 // since de-serializing declarations or macro definitions can add
2388 // new entries into the identifier table, invalidating the
2389 // iterators.
2390 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
2391 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
2392 IdEnd = PP->getIdentifierTable().end();
2393 Id != IdEnd; ++Id)
2394 Identifiers.push_back(Id->second);
2395 // We need to search the tables in all files.
2396 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
2397 ASTIdentifierLookupTable *IdTable
2398 = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
2399 // Not all AST files necessarily have identifier tables, only the useful
2400 // ones.
2401 if (!IdTable)
2402 continue;
2403 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2404 IdentifierInfo *II = Identifiers[I];
2405 // Look in the on-disk hash tables for an entry for this identifier
2406 ASTIdentifierLookupTrait Info(*this, *Chain[J], II);
2407 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
2408 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
2409 if (Pos == IdTable->end())
2410 continue;
2412 // Dereferencing the iterator has the effect of populating the
2413 // IdentifierInfo node with the various declarations it needs.
2414 (void)*Pos;
2419 if (Context)
2420 InitializeContext(*Context);
2422 if (DeserializationListener)
2423 DeserializationListener->ReaderInitialized(this);
2425 // If this AST file is a precompiled preamble, then set the main file ID of
2426 // the source manager to the file source file from which the preamble was
2427 // built. This is the only valid way to use a precompiled preamble.
2428 if (Type == Preamble) {
2429 SourceLocation Loc
2430 = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1);
2431 if (Loc.isValid()) {
2432 std::pair<FileID, unsigned> Decomposed = SourceMgr.getDecomposedLoc(Loc);
2433 SourceMgr.SetPreambleFileID(Decomposed.first);
2437 return Success;
2440 ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName,
2441 ASTFileType Type) {
2442 PerFileData *Prev = Chain.empty() ? 0 : Chain.back();
2443 Chain.push_back(new PerFileData(Type));
2444 PerFileData &F = *Chain.back();
2445 if (Prev)
2446 Prev->NextInSource = &F;
2447 else
2448 FirstInSource = &F;
2449 F.Loaders.push_back(Prev);
2451 // Set the AST file name.
2452 F.FileName = FileName;
2454 if (FileName != "-") {
2455 CurrentDir = llvm::sys::path::parent_path(FileName);
2456 if (CurrentDir.empty()) CurrentDir = ".";
2459 // Open the AST file.
2461 // FIXME: This shouldn't be here, we should just take a raw_ostream.
2462 std::string ErrStr;
2463 llvm::error_code ec;
2464 if (FileName == "-") {
2465 ec = llvm::MemoryBuffer::getSTDIN(F.Buffer);
2466 if (ec)
2467 ErrStr = ec.message();
2468 } else
2469 F.Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrStr));
2470 if (!F.Buffer) {
2471 Error(ErrStr.c_str());
2472 return IgnorePCH;
2475 // Initialize the stream
2476 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
2477 (const unsigned char *)F.Buffer->getBufferEnd());
2478 llvm::BitstreamCursor &Stream = F.Stream;
2479 Stream.init(F.StreamFile);
2480 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2482 // Sniff for the signature.
2483 if (Stream.Read(8) != 'C' ||
2484 Stream.Read(8) != 'P' ||
2485 Stream.Read(8) != 'C' ||
2486 Stream.Read(8) != 'H') {
2487 Diag(diag::err_not_a_pch_file) << FileName;
2488 return Failure;
2491 while (!Stream.AtEndOfStream()) {
2492 unsigned Code = Stream.ReadCode();
2494 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2495 Error("invalid record at top-level of AST file");
2496 return Failure;
2499 unsigned BlockID = Stream.ReadSubBlockID();
2501 // We only know the AST subblock ID.
2502 switch (BlockID) {
2503 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2504 if (Stream.ReadBlockInfoBlock()) {
2505 Error("malformed BlockInfoBlock in AST file");
2506 return Failure;
2508 break;
2509 case AST_BLOCK_ID:
2510 switch (ReadASTBlock(F)) {
2511 case Success:
2512 break;
2514 case Failure:
2515 return Failure;
2517 case IgnorePCH:
2518 // FIXME: We could consider reading through to the end of this
2519 // AST block, skipping subblocks, to see if there are other
2520 // AST blocks elsewhere.
2522 // Clear out any preallocated source location entries, so that
2523 // the source manager does not try to resolve them later.
2524 SourceMgr.ClearPreallocatedSLocEntries();
2526 // Remove the stat cache.
2527 if (F.StatCache)
2528 FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2530 return IgnorePCH;
2532 break;
2533 default:
2534 if (Stream.SkipBlock()) {
2535 Error("malformed block record in AST file");
2536 return Failure;
2538 break;
2542 return Success;
2545 void ASTReader::setPreprocessor(Preprocessor &pp) {
2546 PP = &pp;
2548 unsigned TotalNum = 0;
2549 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
2550 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
2551 if (TotalNum) {
2552 if (!PP->getPreprocessingRecord())
2553 PP->createPreprocessingRecord();
2554 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
2558 void ASTReader::InitializeContext(ASTContext &Ctx) {
2559 Context = &Ctx;
2560 assert(Context && "Passed null context!");
2562 assert(PP && "Forgot to set Preprocessor ?");
2563 PP->getIdentifierTable().setExternalIdentifierLookup(this);
2564 PP->getHeaderSearchInfo().SetExternalLookup(this);
2565 PP->setExternalSource(this);
2566 PP->getHeaderSearchInfo().SetExternalSource(this);
2568 // If we have an update block for the TU waiting, we have to add it before
2569 // deserializing the decl.
2570 DeclContextOffsetsMap::iterator DCU = DeclContextOffsets.find(0);
2571 if (DCU != DeclContextOffsets.end()) {
2572 // Insertion could invalidate map, so grab vector.
2573 DeclContextInfos T;
2574 T.swap(DCU->second);
2575 DeclContextOffsets.erase(DCU);
2576 DeclContextOffsets[Ctx.getTranslationUnitDecl()].swap(T);
2579 // Load the translation unit declaration
2580 GetTranslationUnitDecl();
2582 // Load the special types.
2583 Context->setBuiltinVaListType(
2584 GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2585 if (unsigned Id = SpecialTypes[SPECIAL_TYPE_OBJC_ID])
2586 Context->setObjCIdType(GetType(Id));
2587 if (unsigned Sel = SpecialTypes[SPECIAL_TYPE_OBJC_SELECTOR])
2588 Context->setObjCSelType(GetType(Sel));
2589 if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL])
2590 Context->setObjCProtoType(GetType(Proto));
2591 if (unsigned Class = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS])
2592 Context->setObjCClassType(GetType(Class));
2594 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING])
2595 Context->setCFConstantStringType(GetType(String));
2596 if (unsigned FastEnum
2597 = SpecialTypes[SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2598 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
2599 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2600 QualType FileType = GetType(File);
2601 if (FileType.isNull()) {
2602 Error("FILE type is NULL");
2603 return;
2605 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2606 Context->setFILEDecl(Typedef->getDecl());
2607 else {
2608 const TagType *Tag = FileType->getAs<TagType>();
2609 if (!Tag) {
2610 Error("Invalid FILE type in AST file");
2611 return;
2613 Context->setFILEDecl(Tag->getDecl());
2616 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2617 QualType Jmp_bufType = GetType(Jmp_buf);
2618 if (Jmp_bufType.isNull()) {
2619 Error("jmp_bug type is NULL");
2620 return;
2622 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2623 Context->setjmp_bufDecl(Typedef->getDecl());
2624 else {
2625 const TagType *Tag = Jmp_bufType->getAs<TagType>();
2626 if (!Tag) {
2627 Error("Invalid jmp_buf type in AST file");
2628 return;
2630 Context->setjmp_bufDecl(Tag->getDecl());
2633 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2634 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2635 if (Sigjmp_bufType.isNull()) {
2636 Error("sigjmp_buf type is NULL");
2637 return;
2639 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2640 Context->setsigjmp_bufDecl(Typedef->getDecl());
2641 else {
2642 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2643 assert(Tag && "Invalid sigjmp_buf type in AST file");
2644 Context->setsigjmp_bufDecl(Tag->getDecl());
2647 if (unsigned ObjCIdRedef
2648 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2649 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2650 if (unsigned ObjCClassRedef
2651 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2652 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2653 if (unsigned String = SpecialTypes[SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2654 Context->setBlockDescriptorType(GetType(String));
2655 if (unsigned String
2656 = SpecialTypes[SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2657 Context->setBlockDescriptorExtendedType(GetType(String));
2658 if (unsigned ObjCSelRedef
2659 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2660 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2661 if (unsigned String = SpecialTypes[SPECIAL_TYPE_NS_CONSTANT_STRING])
2662 Context->setNSConstantStringType(GetType(String));
2664 if (SpecialTypes[SPECIAL_TYPE_INT128_INSTALLED])
2665 Context->setInt128Installed();
2667 ReadPragmaDiagnosticMappings(Context->getDiagnostics());
2669 // If there were any CUDA special declarations, deserialize them.
2670 if (!CUDASpecialDeclRefs.empty()) {
2671 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2672 Context->setcudaConfigureCallDecl(
2673 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2677 /// \brief Retrieve the name of the original source file name
2678 /// directly from the AST file, without actually loading the AST
2679 /// file.
2680 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2681 FileManager &FileMgr,
2682 Diagnostic &Diags) {
2683 // Open the AST file.
2684 std::string ErrStr;
2685 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2686 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2687 if (!Buffer) {
2688 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2689 return std::string();
2692 // Initialize the stream
2693 llvm::BitstreamReader StreamFile;
2694 llvm::BitstreamCursor Stream;
2695 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2696 (const unsigned char *)Buffer->getBufferEnd());
2697 Stream.init(StreamFile);
2699 // Sniff for the signature.
2700 if (Stream.Read(8) != 'C' ||
2701 Stream.Read(8) != 'P' ||
2702 Stream.Read(8) != 'C' ||
2703 Stream.Read(8) != 'H') {
2704 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2705 return std::string();
2708 RecordData Record;
2709 while (!Stream.AtEndOfStream()) {
2710 unsigned Code = Stream.ReadCode();
2712 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2713 unsigned BlockID = Stream.ReadSubBlockID();
2715 // We only know the AST subblock ID.
2716 switch (BlockID) {
2717 case AST_BLOCK_ID:
2718 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2719 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2720 return std::string();
2722 break;
2724 default:
2725 if (Stream.SkipBlock()) {
2726 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2727 return std::string();
2729 break;
2731 continue;
2734 if (Code == llvm::bitc::END_BLOCK) {
2735 if (Stream.ReadBlockEnd()) {
2736 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2737 return std::string();
2739 continue;
2742 if (Code == llvm::bitc::DEFINE_ABBREV) {
2743 Stream.ReadAbbrevRecord();
2744 continue;
2747 Record.clear();
2748 const char *BlobStart = 0;
2749 unsigned BlobLen = 0;
2750 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2751 == ORIGINAL_FILE_NAME)
2752 return std::string(BlobStart, BlobLen);
2755 return std::string();
2758 /// \brief Parse the record that corresponds to a LangOptions data
2759 /// structure.
2761 /// This routine parses the language options from the AST file and then gives
2762 /// them to the AST listener if one is set.
2764 /// \returns true if the listener deems the file unacceptable, false otherwise.
2765 bool ASTReader::ParseLanguageOptions(
2766 const llvm::SmallVectorImpl<uint64_t> &Record) {
2767 if (Listener) {
2768 LangOptions LangOpts;
2770 #define PARSE_LANGOPT(Option) \
2771 LangOpts.Option = Record[Idx]; \
2772 ++Idx
2774 unsigned Idx = 0;
2775 PARSE_LANGOPT(Trigraphs);
2776 PARSE_LANGOPT(BCPLComment);
2777 PARSE_LANGOPT(DollarIdents);
2778 PARSE_LANGOPT(AsmPreprocessor);
2779 PARSE_LANGOPT(GNUMode);
2780 PARSE_LANGOPT(GNUKeywords);
2781 PARSE_LANGOPT(ImplicitInt);
2782 PARSE_LANGOPT(Digraphs);
2783 PARSE_LANGOPT(HexFloats);
2784 PARSE_LANGOPT(C99);
2785 PARSE_LANGOPT(Microsoft);
2786 PARSE_LANGOPT(CPlusPlus);
2787 PARSE_LANGOPT(CPlusPlus0x);
2788 PARSE_LANGOPT(CXXOperatorNames);
2789 PARSE_LANGOPT(ObjC1);
2790 PARSE_LANGOPT(ObjC2);
2791 PARSE_LANGOPT(ObjCNonFragileABI);
2792 PARSE_LANGOPT(ObjCNonFragileABI2);
2793 PARSE_LANGOPT(AppleKext);
2794 PARSE_LANGOPT(ObjCDefaultSynthProperties);
2795 PARSE_LANGOPT(NoConstantCFStrings);
2796 PARSE_LANGOPT(PascalStrings);
2797 PARSE_LANGOPT(WritableStrings);
2798 PARSE_LANGOPT(LaxVectorConversions);
2799 PARSE_LANGOPT(AltiVec);
2800 PARSE_LANGOPT(Exceptions);
2801 PARSE_LANGOPT(SjLjExceptions);
2802 PARSE_LANGOPT(MSBitfields);
2803 PARSE_LANGOPT(NeXTRuntime);
2804 PARSE_LANGOPT(Freestanding);
2805 PARSE_LANGOPT(NoBuiltin);
2806 PARSE_LANGOPT(ThreadsafeStatics);
2807 PARSE_LANGOPT(POSIXThreads);
2808 PARSE_LANGOPT(Blocks);
2809 PARSE_LANGOPT(EmitAllDecls);
2810 PARSE_LANGOPT(MathErrno);
2811 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2812 Record[Idx++]);
2813 PARSE_LANGOPT(HeinousExtensions);
2814 PARSE_LANGOPT(Optimize);
2815 PARSE_LANGOPT(OptimizeSize);
2816 PARSE_LANGOPT(Static);
2817 PARSE_LANGOPT(PICLevel);
2818 PARSE_LANGOPT(GNUInline);
2819 PARSE_LANGOPT(NoInline);
2820 PARSE_LANGOPT(AccessControl);
2821 PARSE_LANGOPT(CharIsSigned);
2822 PARSE_LANGOPT(ShortWChar);
2823 PARSE_LANGOPT(ShortEnums);
2824 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2825 LangOpts.setVisibilityMode((Visibility)Record[Idx++]);
2826 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
2827 Record[Idx++]);
2828 PARSE_LANGOPT(InstantiationDepth);
2829 PARSE_LANGOPT(OpenCL);
2830 PARSE_LANGOPT(CUDA);
2831 PARSE_LANGOPT(CatchUndefined);
2832 PARSE_LANGOPT(DefaultFPContract);
2833 // FIXME: Missing ElideConstructors?!
2834 #undef PARSE_LANGOPT
2836 return Listener->ReadLanguageOptions(LangOpts);
2839 return false;
2842 void ASTReader::ReadPreprocessedEntities() {
2843 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2844 PerFileData &F = *Chain[I];
2845 if (!F.PreprocessorDetailCursor.getBitStreamReader())
2846 continue;
2848 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
2849 F.PreprocessorDetailCursor.JumpToBit(F.PreprocessorDetailStartOffset);
2850 while (LoadPreprocessedEntity(F)) { }
2854 PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) {
2855 PerFileData *F = 0;
2856 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2857 if (Offset < Chain[I]->SizeInBits) {
2858 F = Chain[I];
2859 break;
2862 Offset -= Chain[I]->SizeInBits;
2865 if (!F) {
2866 Error("Malformed preprocessed entity offset");
2867 return 0;
2870 // Keep track of where we are in the stream, then jump back there
2871 // after reading this entity.
2872 SavedStreamPosition SavedPosition(F->PreprocessorDetailCursor);
2873 F->PreprocessorDetailCursor.JumpToBit(Offset);
2874 return LoadPreprocessedEntity(*F);
2877 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
2878 HeaderFileInfoTrait Trait(FE->getName());
2879 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2880 PerFileData &F = *Chain[I];
2881 HeaderFileInfoLookupTable *Table
2882 = static_cast<HeaderFileInfoLookupTable *>(F.HeaderFileInfoTable);
2883 if (!Table)
2884 continue;
2886 // Look in the on-disk hash table for an entry for this file name.
2887 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE->getName(),
2888 &Trait);
2889 if (Pos == Table->end())
2890 continue;
2892 HeaderFileInfo HFI = *Pos;
2893 if (Listener)
2894 Listener->ReadHeaderFileInfo(HFI, FE->getUID());
2896 return HFI;
2899 return HeaderFileInfo();
2902 void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) {
2903 unsigned Idx = 0;
2904 while (Idx < PragmaDiagMappings.size()) {
2905 SourceLocation
2906 Loc = SourceLocation::getFromRawEncoding(PragmaDiagMappings[Idx++]);
2907 while (1) {
2908 assert(Idx < PragmaDiagMappings.size() &&
2909 "Invalid data, didn't find '-1' marking end of diag/map pairs");
2910 if (Idx >= PragmaDiagMappings.size())
2911 break; // Something is messed up but at least avoid infinite loop in
2912 // release build.
2913 unsigned DiagID = PragmaDiagMappings[Idx++];
2914 if (DiagID == (unsigned)-1)
2915 break; // no more diag/map pairs for this location.
2916 diag::Mapping Map = (diag::Mapping)PragmaDiagMappings[Idx++];
2917 Diag.setDiagnosticMapping(DiagID, Map, Loc);
2922 /// \brief Get the correct cursor and offset for loading a type.
2923 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
2924 PerFileData *F = 0;
2925 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2926 F = Chain[N - I - 1];
2927 if (Index < F->LocalNumTypes)
2928 break;
2929 Index -= F->LocalNumTypes;
2931 assert(F && F->LocalNumTypes > Index && "Broken chain");
2932 return RecordLocation(F, F->TypeOffsets[Index]);
2935 /// \brief Read and return the type with the given index..
2937 /// The index is the type ID, shifted and minus the number of predefs. This
2938 /// routine actually reads the record corresponding to the type at the given
2939 /// location. It is a helper routine for GetType, which deals with reading type
2940 /// IDs.
2941 QualType ASTReader::ReadTypeRecord(unsigned Index) {
2942 RecordLocation Loc = TypeCursorForIndex(Index);
2943 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2945 // Keep track of where we are in the stream, then jump back there
2946 // after reading this type.
2947 SavedStreamPosition SavedPosition(DeclsCursor);
2949 ReadingKindTracker ReadingKind(Read_Type, *this);
2951 // Note that we are loading a type record.
2952 Deserializing AType(this);
2954 DeclsCursor.JumpToBit(Loc.Offset);
2955 RecordData Record;
2956 unsigned Code = DeclsCursor.ReadCode();
2957 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
2958 case TYPE_EXT_QUAL: {
2959 if (Record.size() != 2) {
2960 Error("Incorrect encoding of extended qualifier type");
2961 return QualType();
2963 QualType Base = GetType(Record[0]);
2964 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2965 return Context->getQualifiedType(Base, Quals);
2968 case TYPE_COMPLEX: {
2969 if (Record.size() != 1) {
2970 Error("Incorrect encoding of complex type");
2971 return QualType();
2973 QualType ElemType = GetType(Record[0]);
2974 return Context->getComplexType(ElemType);
2977 case TYPE_POINTER: {
2978 if (Record.size() != 1) {
2979 Error("Incorrect encoding of pointer type");
2980 return QualType();
2982 QualType PointeeType = GetType(Record[0]);
2983 return Context->getPointerType(PointeeType);
2986 case TYPE_BLOCK_POINTER: {
2987 if (Record.size() != 1) {
2988 Error("Incorrect encoding of block pointer type");
2989 return QualType();
2991 QualType PointeeType = GetType(Record[0]);
2992 return Context->getBlockPointerType(PointeeType);
2995 case TYPE_LVALUE_REFERENCE: {
2996 if (Record.size() != 1) {
2997 Error("Incorrect encoding of lvalue reference type");
2998 return QualType();
3000 QualType PointeeType = GetType(Record[0]);
3001 return Context->getLValueReferenceType(PointeeType);
3004 case TYPE_RVALUE_REFERENCE: {
3005 if (Record.size() != 1) {
3006 Error("Incorrect encoding of rvalue reference type");
3007 return QualType();
3009 QualType PointeeType = GetType(Record[0]);
3010 return Context->getRValueReferenceType(PointeeType);
3013 case TYPE_MEMBER_POINTER: {
3014 if (Record.size() != 2) {
3015 Error("Incorrect encoding of member pointer type");
3016 return QualType();
3018 QualType PointeeType = GetType(Record[0]);
3019 QualType ClassType = GetType(Record[1]);
3020 if (PointeeType.isNull() || ClassType.isNull())
3021 return QualType();
3023 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
3026 case TYPE_CONSTANT_ARRAY: {
3027 QualType ElementType = GetType(Record[0]);
3028 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3029 unsigned IndexTypeQuals = Record[2];
3030 unsigned Idx = 3;
3031 llvm::APInt Size = ReadAPInt(Record, Idx);
3032 return Context->getConstantArrayType(ElementType, Size,
3033 ASM, IndexTypeQuals);
3036 case TYPE_INCOMPLETE_ARRAY: {
3037 QualType ElementType = GetType(Record[0]);
3038 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3039 unsigned IndexTypeQuals = Record[2];
3040 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3043 case TYPE_VARIABLE_ARRAY: {
3044 QualType ElementType = GetType(Record[0]);
3045 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3046 unsigned IndexTypeQuals = Record[2];
3047 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3048 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3049 return Context->getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3050 ASM, IndexTypeQuals,
3051 SourceRange(LBLoc, RBLoc));
3054 case TYPE_VECTOR: {
3055 if (Record.size() != 3) {
3056 Error("incorrect encoding of vector type in AST file");
3057 return QualType();
3060 QualType ElementType = GetType(Record[0]);
3061 unsigned NumElements = Record[1];
3062 unsigned VecKind = Record[2];
3063 return Context->getVectorType(ElementType, NumElements,
3064 (VectorType::VectorKind)VecKind);
3067 case TYPE_EXT_VECTOR: {
3068 if (Record.size() != 3) {
3069 Error("incorrect encoding of extended vector type in AST file");
3070 return QualType();
3073 QualType ElementType = GetType(Record[0]);
3074 unsigned NumElements = Record[1];
3075 return Context->getExtVectorType(ElementType, NumElements);
3078 case TYPE_FUNCTION_NO_PROTO: {
3079 if (Record.size() != 4) {
3080 Error("incorrect encoding of no-proto function type");
3081 return QualType();
3083 QualType ResultType = GetType(Record[0]);
3084 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
3085 return Context->getFunctionNoProtoType(ResultType, Info);
3088 case TYPE_FUNCTION_PROTO: {
3089 QualType ResultType = GetType(Record[0]);
3091 FunctionProtoType::ExtProtoInfo EPI;
3092 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3093 /*regparm*/ Record[2],
3094 static_cast<CallingConv>(Record[3]));
3096 unsigned Idx = 4;
3097 unsigned NumParams = Record[Idx++];
3098 llvm::SmallVector<QualType, 16> ParamTypes;
3099 for (unsigned I = 0; I != NumParams; ++I)
3100 ParamTypes.push_back(GetType(Record[Idx++]));
3102 EPI.Variadic = Record[Idx++];
3103 EPI.TypeQuals = Record[Idx++];
3104 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3105 EPI.HasExceptionSpec = Record[Idx++];
3106 EPI.HasAnyExceptionSpec = Record[Idx++];
3107 EPI.NumExceptions = Record[Idx++];
3108 llvm::SmallVector<QualType, 2> Exceptions;
3109 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3110 Exceptions.push_back(GetType(Record[Idx++]));
3111 EPI.Exceptions = Exceptions.data();
3112 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
3113 EPI);
3116 case TYPE_UNRESOLVED_USING:
3117 return Context->getTypeDeclType(
3118 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
3120 case TYPE_TYPEDEF: {
3121 if (Record.size() != 2) {
3122 Error("incorrect encoding of typedef type");
3123 return QualType();
3125 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
3126 QualType Canonical = GetType(Record[1]);
3127 if (!Canonical.isNull())
3128 Canonical = Context->getCanonicalType(Canonical);
3129 return Context->getTypedefType(Decl, Canonical);
3132 case TYPE_TYPEOF_EXPR:
3133 return Context->getTypeOfExprType(ReadExpr(*Loc.F));
3135 case TYPE_TYPEOF: {
3136 if (Record.size() != 1) {
3137 Error("incorrect encoding of typeof(type) in AST file");
3138 return QualType();
3140 QualType UnderlyingType = GetType(Record[0]);
3141 return Context->getTypeOfType(UnderlyingType);
3144 case TYPE_DECLTYPE:
3145 return Context->getDecltypeType(ReadExpr(*Loc.F));
3147 case TYPE_RECORD: {
3148 if (Record.size() != 2) {
3149 Error("incorrect encoding of record type");
3150 return QualType();
3152 bool IsDependent = Record[0];
3153 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
3154 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3155 return T;
3158 case TYPE_ENUM: {
3159 if (Record.size() != 2) {
3160 Error("incorrect encoding of enum type");
3161 return QualType();
3163 bool IsDependent = Record[0];
3164 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
3165 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3166 return T;
3169 case TYPE_ATTRIBUTED: {
3170 if (Record.size() != 3) {
3171 Error("incorrect encoding of attributed type");
3172 return QualType();
3174 QualType modifiedType = GetType(Record[0]);
3175 QualType equivalentType = GetType(Record[1]);
3176 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3177 return Context->getAttributedType(kind, modifiedType, equivalentType);
3180 case TYPE_PAREN: {
3181 if (Record.size() != 1) {
3182 Error("incorrect encoding of paren type");
3183 return QualType();
3185 QualType InnerType = GetType(Record[0]);
3186 return Context->getParenType(InnerType);
3189 case TYPE_PACK_EXPANSION: {
3190 if (Record.size() != 2) {
3191 Error("incorrect encoding of pack expansion type");
3192 return QualType();
3194 QualType Pattern = GetType(Record[0]);
3195 if (Pattern.isNull())
3196 return QualType();
3197 llvm::Optional<unsigned> NumExpansions;
3198 if (Record[1])
3199 NumExpansions = Record[1] - 1;
3200 return Context->getPackExpansionType(Pattern, NumExpansions);
3203 case TYPE_ELABORATED: {
3204 unsigned Idx = 0;
3205 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3206 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3207 QualType NamedType = GetType(Record[Idx++]);
3208 return Context->getElaboratedType(Keyword, NNS, NamedType);
3211 case TYPE_OBJC_INTERFACE: {
3212 unsigned Idx = 0;
3213 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
3214 return Context->getObjCInterfaceType(ItfD);
3217 case TYPE_OBJC_OBJECT: {
3218 unsigned Idx = 0;
3219 QualType Base = GetType(Record[Idx++]);
3220 unsigned NumProtos = Record[Idx++];
3221 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
3222 for (unsigned I = 0; I != NumProtos; ++I)
3223 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
3224 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
3227 case TYPE_OBJC_OBJECT_POINTER: {
3228 unsigned Idx = 0;
3229 QualType Pointee = GetType(Record[Idx++]);
3230 return Context->getObjCObjectPointerType(Pointee);
3233 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3234 unsigned Idx = 0;
3235 QualType Parm = GetType(Record[Idx++]);
3236 QualType Replacement = GetType(Record[Idx++]);
3237 return
3238 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3239 Replacement);
3242 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3243 unsigned Idx = 0;
3244 QualType Parm = GetType(Record[Idx++]);
3245 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3246 return Context->getSubstTemplateTypeParmPackType(
3247 cast<TemplateTypeParmType>(Parm),
3248 ArgPack);
3251 case TYPE_INJECTED_CLASS_NAME: {
3252 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
3253 QualType TST = GetType(Record[1]); // probably derivable
3254 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3255 // for AST reading, too much interdependencies.
3256 return
3257 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3260 case TYPE_TEMPLATE_TYPE_PARM: {
3261 unsigned Idx = 0;
3262 unsigned Depth = Record[Idx++];
3263 unsigned Index = Record[Idx++];
3264 bool Pack = Record[Idx++];
3265 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
3266 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
3269 case TYPE_DEPENDENT_NAME: {
3270 unsigned Idx = 0;
3271 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3272 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3273 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3274 QualType Canon = GetType(Record[Idx++]);
3275 if (!Canon.isNull())
3276 Canon = Context->getCanonicalType(Canon);
3277 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
3280 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3281 unsigned Idx = 0;
3282 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3283 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3284 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3285 unsigned NumArgs = Record[Idx++];
3286 llvm::SmallVector<TemplateArgument, 8> Args;
3287 Args.reserve(NumArgs);
3288 while (NumArgs--)
3289 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3290 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
3291 Args.size(), Args.data());
3294 case TYPE_DEPENDENT_SIZED_ARRAY: {
3295 unsigned Idx = 0;
3297 // ArrayType
3298 QualType ElementType = GetType(Record[Idx++]);
3299 ArrayType::ArraySizeModifier ASM
3300 = (ArrayType::ArraySizeModifier)Record[Idx++];
3301 unsigned IndexTypeQuals = Record[Idx++];
3303 // DependentSizedArrayType
3304 Expr *NumElts = ReadExpr(*Loc.F);
3305 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3307 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
3308 IndexTypeQuals, Brackets);
3311 case TYPE_TEMPLATE_SPECIALIZATION: {
3312 unsigned Idx = 0;
3313 bool IsDependent = Record[Idx++];
3314 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3315 llvm::SmallVector<TemplateArgument, 8> Args;
3316 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3317 QualType Canon = GetType(Record[Idx++]);
3318 QualType T;
3319 if (Canon.isNull())
3320 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
3321 Args.size());
3322 else
3323 T = Context->getTemplateSpecializationType(Name, Args.data(),
3324 Args.size(), Canon);
3325 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3326 return T;
3329 // Suppress a GCC warning
3330 return QualType();
3333 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3334 ASTReader &Reader;
3335 ASTReader::PerFileData &F;
3336 llvm::BitstreamCursor &DeclsCursor;
3337 const ASTReader::RecordData &Record;
3338 unsigned &Idx;
3340 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3341 unsigned &I) {
3342 return Reader.ReadSourceLocation(F, R, I);
3345 public:
3346 TypeLocReader(ASTReader &Reader, ASTReader::PerFileData &F,
3347 const ASTReader::RecordData &Record, unsigned &Idx)
3348 : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3351 // We want compile-time assurance that we've enumerated all of
3352 // these, so unfortunately we have to declare them first, then
3353 // define them out-of-line.
3354 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3355 #define TYPELOC(CLASS, PARENT) \
3356 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3357 #include "clang/AST/TypeLocNodes.def"
3359 void VisitFunctionTypeLoc(FunctionTypeLoc);
3360 void VisitArrayTypeLoc(ArrayTypeLoc);
3363 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3364 // nothing to do
3366 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3367 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3368 if (TL.needsExtraLocalData()) {
3369 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3370 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3371 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3372 TL.setModeAttr(Record[Idx++]);
3375 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3376 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3378 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3379 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3381 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3382 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3384 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3385 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3387 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3388 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3390 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3391 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3393 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3394 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3395 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3396 if (Record[Idx++])
3397 TL.setSizeExpr(Reader.ReadExpr(F));
3398 else
3399 TL.setSizeExpr(0);
3401 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3402 VisitArrayTypeLoc(TL);
3404 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3405 VisitArrayTypeLoc(TL);
3407 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3408 VisitArrayTypeLoc(TL);
3410 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3411 DependentSizedArrayTypeLoc TL) {
3412 VisitArrayTypeLoc(TL);
3414 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3415 DependentSizedExtVectorTypeLoc TL) {
3416 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3418 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3419 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3421 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3422 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3424 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3425 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3426 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3427 TL.setTrailingReturn(Record[Idx++]);
3428 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3429 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
3432 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3433 VisitFunctionTypeLoc(TL);
3435 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3436 VisitFunctionTypeLoc(TL);
3438 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3439 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3441 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3442 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3444 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3445 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3446 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3447 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3449 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3450 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3451 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3452 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3453 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3455 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3456 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3458 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3459 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3461 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3462 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3464 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3465 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3466 if (TL.hasAttrOperand()) {
3467 SourceRange range;
3468 range.setBegin(ReadSourceLocation(Record, Idx));
3469 range.setEnd(ReadSourceLocation(Record, Idx));
3470 TL.setAttrOperandParensRange(range);
3472 if (TL.hasAttrExprOperand()) {
3473 if (Record[Idx++])
3474 TL.setAttrExprOperand(Reader.ReadExpr(F));
3475 else
3476 TL.setAttrExprOperand(0);
3477 } else if (TL.hasAttrEnumOperand())
3478 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3480 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3481 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3483 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3484 SubstTemplateTypeParmTypeLoc TL) {
3485 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3487 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3488 SubstTemplateTypeParmPackTypeLoc TL) {
3489 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3491 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3492 TemplateSpecializationTypeLoc TL) {
3493 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3494 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3495 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3496 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3497 TL.setArgLocInfo(i,
3498 Reader.GetTemplateArgumentLocInfo(F,
3499 TL.getTypePtr()->getArg(i).getKind(),
3500 Record, Idx));
3502 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3503 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3504 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3506 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3507 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3508 TL.setQualifierRange(Reader.ReadSourceRange(F, Record, Idx));
3510 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3511 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3513 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3514 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3515 TL.setQualifierRange(Reader.ReadSourceRange(F, Record, Idx));
3516 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3518 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3519 DependentTemplateSpecializationTypeLoc TL) {
3520 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3521 TL.setQualifierRange(Reader.ReadSourceRange(F, Record, Idx));
3522 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3523 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3524 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3525 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3526 TL.setArgLocInfo(I,
3527 Reader.GetTemplateArgumentLocInfo(F,
3528 TL.getTypePtr()->getArg(I).getKind(),
3529 Record, Idx));
3531 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3532 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3534 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3535 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3537 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3538 TL.setHasBaseTypeAsWritten(Record[Idx++]);
3539 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3540 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3541 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3542 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3544 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3545 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3548 TypeSourceInfo *ASTReader::GetTypeSourceInfo(PerFileData &F,
3549 const RecordData &Record,
3550 unsigned &Idx) {
3551 QualType InfoTy = GetType(Record[Idx++]);
3552 if (InfoTy.isNull())
3553 return 0;
3555 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
3556 TypeLocReader TLR(*this, F, Record, Idx);
3557 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3558 TLR.Visit(TL);
3559 return TInfo;
3562 QualType ASTReader::GetType(TypeID ID) {
3563 unsigned FastQuals = ID & Qualifiers::FastMask;
3564 unsigned Index = ID >> Qualifiers::FastWidth;
3566 if (Index < NUM_PREDEF_TYPE_IDS) {
3567 QualType T;
3568 switch ((PredefinedTypeIDs)Index) {
3569 case PREDEF_TYPE_NULL_ID: return QualType();
3570 case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
3571 case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
3573 case PREDEF_TYPE_CHAR_U_ID:
3574 case PREDEF_TYPE_CHAR_S_ID:
3575 // FIXME: Check that the signedness of CharTy is correct!
3576 T = Context->CharTy;
3577 break;
3579 case PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
3580 case PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
3581 case PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
3582 case PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
3583 case PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
3584 case PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
3585 case PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
3586 case PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
3587 case PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
3588 case PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
3589 case PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
3590 case PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
3591 case PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
3592 case PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
3593 case PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
3594 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
3595 case PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
3596 case PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
3597 case PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
3598 case PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
3599 case PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
3600 case PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
3601 case PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
3602 case PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
3605 assert(!T.isNull() && "Unknown predefined type");
3606 return T.withFastQualifiers(FastQuals);
3609 Index -= NUM_PREDEF_TYPE_IDS;
3610 assert(Index < TypesLoaded.size() && "Type index out-of-range");
3611 if (TypesLoaded[Index].isNull()) {
3612 TypesLoaded[Index] = ReadTypeRecord(Index);
3613 if (TypesLoaded[Index].isNull())
3614 return QualType();
3616 TypesLoaded[Index]->setFromAST();
3617 TypeIdxs[TypesLoaded[Index]] = TypeIdx::fromTypeID(ID);
3618 if (DeserializationListener)
3619 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3620 TypesLoaded[Index]);
3623 return TypesLoaded[Index].withFastQualifiers(FastQuals);
3626 TypeID ASTReader::GetTypeID(QualType T) const {
3627 return MakeTypeID(T,
3628 std::bind1st(std::mem_fun(&ASTReader::GetTypeIdx), this));
3631 TypeIdx ASTReader::GetTypeIdx(QualType T) const {
3632 if (T.isNull())
3633 return TypeIdx();
3634 assert(!T.getLocalFastQualifiers());
3636 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3637 // GetTypeIdx is mostly used for computing the hash of DeclarationNames and
3638 // comparing keys of ASTDeclContextNameLookupTable.
3639 // If the type didn't come from the AST file use a specially marked index
3640 // so that any hash/key comparison fail since no such index is stored
3641 // in a AST file.
3642 if (I == TypeIdxs.end())
3643 return TypeIdx(-1);
3644 return I->second;
3647 unsigned ASTReader::getTotalNumCXXBaseSpecifiers() const {
3648 unsigned Result = 0;
3649 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
3650 Result += Chain[I]->LocalNumCXXBaseSpecifiers;
3652 return Result;
3655 TemplateArgumentLocInfo
3656 ASTReader::GetTemplateArgumentLocInfo(PerFileData &F,
3657 TemplateArgument::ArgKind Kind,
3658 const RecordData &Record,
3659 unsigned &Index) {
3660 switch (Kind) {
3661 case TemplateArgument::Expression:
3662 return ReadExpr(F);
3663 case TemplateArgument::Type:
3664 return GetTypeSourceInfo(F, Record, Index);
3665 case TemplateArgument::Template: {
3666 SourceRange QualifierRange = ReadSourceRange(F, Record, Index);
3667 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3668 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc,
3669 SourceLocation());
3671 case TemplateArgument::TemplateExpansion: {
3672 SourceRange QualifierRange = ReadSourceRange(F, Record, Index);
3673 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3674 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3675 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc,
3676 EllipsisLoc);
3678 case TemplateArgument::Null:
3679 case TemplateArgument::Integral:
3680 case TemplateArgument::Declaration:
3681 case TemplateArgument::Pack:
3682 return TemplateArgumentLocInfo();
3684 llvm_unreachable("unexpected template argument loc");
3685 return TemplateArgumentLocInfo();
3688 TemplateArgumentLoc
3689 ASTReader::ReadTemplateArgumentLoc(PerFileData &F,
3690 const RecordData &Record, unsigned &Index) {
3691 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
3693 if (Arg.getKind() == TemplateArgument::Expression) {
3694 if (Record[Index++]) // bool InfoHasSameExpr.
3695 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
3697 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
3698 Record, Index));
3701 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
3702 return GetDecl(ID);
3705 uint64_t
3706 ASTReader::GetCXXBaseSpecifiersOffset(serialization::CXXBaseSpecifiersID ID) {
3707 if (ID == 0)
3708 return 0;
3710 --ID;
3711 uint64_t Offset = 0;
3712 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3713 if (ID < Chain[I]->LocalNumCXXBaseSpecifiers)
3714 return Offset + Chain[I]->CXXBaseSpecifiersOffsets[ID];
3716 ID -= Chain[I]->LocalNumCXXBaseSpecifiers;
3717 Offset += Chain[I]->SizeInBits;
3720 assert(false && "CXXBaseSpecifiers not found");
3721 return 0;
3724 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
3725 // Figure out which AST file contains this offset.
3726 PerFileData *F = 0;
3727 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3728 if (Offset < Chain[I]->SizeInBits) {
3729 F = Chain[I];
3730 break;
3733 Offset -= Chain[I]->SizeInBits;
3736 if (!F) {
3737 Error("Malformed AST file: C++ base specifiers at impossible offset");
3738 return 0;
3741 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3742 SavedStreamPosition SavedPosition(Cursor);
3743 Cursor.JumpToBit(Offset);
3744 ReadingKindTracker ReadingKind(Read_Decl, *this);
3745 RecordData Record;
3746 unsigned Code = Cursor.ReadCode();
3747 unsigned RecCode = Cursor.ReadRecord(Code, Record);
3748 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
3749 Error("Malformed AST file: missing C++ base specifiers");
3750 return 0;
3753 unsigned Idx = 0;
3754 unsigned NumBases = Record[Idx++];
3755 void *Mem = Context->Allocate(sizeof(CXXBaseSpecifier) * NumBases);
3756 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
3757 for (unsigned I = 0; I != NumBases; ++I)
3758 Bases[I] = ReadCXXBaseSpecifier(*F, Record, Idx);
3759 return Bases;
3762 TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() {
3763 if (!DeclsLoaded[0]) {
3764 ReadDeclRecord(0, 1);
3765 if (DeserializationListener)
3766 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
3769 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
3772 Decl *ASTReader::GetDecl(DeclID ID) {
3773 if (ID == 0)
3774 return 0;
3776 if (ID > DeclsLoaded.size()) {
3777 Error("declaration ID out-of-range for AST file");
3778 return 0;
3781 unsigned Index = ID - 1;
3782 if (!DeclsLoaded[Index]) {
3783 ReadDeclRecord(Index, ID);
3784 if (DeserializationListener)
3785 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
3788 return DeclsLoaded[Index];
3791 /// \brief Resolve the offset of a statement into a statement.
3793 /// This operation will read a new statement from the external
3794 /// source each time it is called, and is meant to be used via a
3795 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
3796 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
3797 // Switch case IDs are per Decl.
3798 ClearSwitchCaseIDs();
3800 // Offset here is a global offset across the entire chain.
3801 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3802 PerFileData &F = *Chain[N - I - 1];
3803 if (Offset < F.SizeInBits) {
3804 // Since we know that this statement is part of a decl, make sure to use
3805 // the decl cursor to read it.
3806 F.DeclsCursor.JumpToBit(Offset);
3807 return ReadStmtFromStream(F);
3809 Offset -= F.SizeInBits;
3811 llvm_unreachable("Broken chain");
3814 bool ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
3815 bool (*isKindWeWant)(Decl::Kind),
3816 llvm::SmallVectorImpl<Decl*> &Decls) {
3817 assert(DC->hasExternalLexicalStorage() &&
3818 "DeclContext has no lexical decls in storage");
3820 // There might be lexical decls in multiple parts of the chain, for the TU
3821 // at least.
3822 // DeclContextOffsets might reallocate as we load additional decls below,
3823 // so make a copy of the vector.
3824 DeclContextInfos Infos = DeclContextOffsets[DC];
3825 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3826 I != E; ++I) {
3827 // IDs can be 0 if this context doesn't contain declarations.
3828 if (!I->LexicalDecls)
3829 continue;
3831 // Load all of the declaration IDs
3832 for (const KindDeclIDPair *ID = I->LexicalDecls,
3833 *IDE = ID + I->NumLexicalDecls; ID != IDE; ++ID) {
3834 if (isKindWeWant && !isKindWeWant((Decl::Kind)ID->first))
3835 continue;
3837 Decl *D = GetDecl(ID->second);
3838 assert(D && "Null decl in lexical decls");
3839 Decls.push_back(D);
3843 ++NumLexicalDeclContextsRead;
3844 return false;
3847 DeclContext::lookup_result
3848 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
3849 DeclarationName Name) {
3850 assert(DC->hasExternalVisibleStorage() &&
3851 "DeclContext has no visible decls in storage");
3852 if (!Name)
3853 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
3854 DeclContext::lookup_iterator(0));
3856 llvm::SmallVector<NamedDecl *, 64> Decls;
3857 // There might be visible decls in multiple parts of the chain, for the TU
3858 // and namespaces. For any given name, the last available results replace
3859 // all earlier ones. For this reason, we walk in reverse.
3860 DeclContextInfos &Infos = DeclContextOffsets[DC];
3861 for (DeclContextInfos::reverse_iterator I = Infos.rbegin(), E = Infos.rend();
3862 I != E; ++I) {
3863 if (!I->NameLookupTableData)
3864 continue;
3866 ASTDeclContextNameLookupTable *LookupTable =
3867 (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3868 ASTDeclContextNameLookupTable::iterator Pos = LookupTable->find(Name);
3869 if (Pos == LookupTable->end())
3870 continue;
3872 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
3873 for (; Data.first != Data.second; ++Data.first)
3874 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3875 break;
3878 ++NumVisibleDeclContextsRead;
3880 SetExternalVisibleDeclsForName(DC, Name, Decls);
3881 return const_cast<DeclContext*>(DC)->lookup(Name);
3884 void ASTReader::MaterializeVisibleDecls(const DeclContext *DC) {
3885 assert(DC->hasExternalVisibleStorage() &&
3886 "DeclContext has no visible decls in storage");
3888 llvm::SmallVector<NamedDecl *, 64> Decls;
3889 // There might be visible decls in multiple parts of the chain, for the TU
3890 // and namespaces.
3891 DeclContextInfos &Infos = DeclContextOffsets[DC];
3892 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3893 I != E; ++I) {
3894 if (!I->NameLookupTableData)
3895 continue;
3897 ASTDeclContextNameLookupTable *LookupTable =
3898 (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3899 for (ASTDeclContextNameLookupTable::item_iterator
3900 ItemI = LookupTable->item_begin(),
3901 ItemEnd = LookupTable->item_end() ; ItemI != ItemEnd; ++ItemI) {
3902 ASTDeclContextNameLookupTable::item_iterator::value_type Val
3903 = *ItemI;
3904 ASTDeclContextNameLookupTrait::data_type Data = Val.second;
3905 Decls.clear();
3906 for (; Data.first != Data.second; ++Data.first)
3907 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3908 MaterializeVisibleDeclsForName(DC, Val.first, Decls);
3913 void ASTReader::PassInterestingDeclsToConsumer() {
3914 assert(Consumer);
3915 while (!InterestingDecls.empty()) {
3916 DeclGroupRef DG(InterestingDecls.front());
3917 InterestingDecls.pop_front();
3918 Consumer->HandleInterestingDecl(DG);
3922 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
3923 this->Consumer = Consumer;
3925 if (!Consumer)
3926 return;
3928 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
3929 // Force deserialization of this decl, which will cause it to be queued for
3930 // passing to the consumer.
3931 GetDecl(ExternalDefinitions[I]);
3934 PassInterestingDeclsToConsumer();
3937 void ASTReader::PrintStats() {
3938 std::fprintf(stderr, "*** AST File Statistics:\n");
3940 unsigned NumTypesLoaded
3941 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
3942 QualType());
3943 unsigned NumDeclsLoaded
3944 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3945 (Decl *)0);
3946 unsigned NumIdentifiersLoaded
3947 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3948 IdentifiersLoaded.end(),
3949 (IdentifierInfo *)0);
3950 unsigned NumSelectorsLoaded
3951 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3952 SelectorsLoaded.end(),
3953 Selector());
3955 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3956 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
3957 if (TotalNumSLocEntries)
3958 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3959 NumSLocEntriesRead, TotalNumSLocEntries,
3960 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
3961 if (!TypesLoaded.empty())
3962 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
3963 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3964 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3965 if (!DeclsLoaded.empty())
3966 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
3967 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3968 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
3969 if (!IdentifiersLoaded.empty())
3970 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
3971 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3972 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
3973 if (!SelectorsLoaded.empty())
3974 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3975 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3976 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
3977 if (TotalNumStatements)
3978 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3979 NumStatementsRead, TotalNumStatements,
3980 ((float)NumStatementsRead/TotalNumStatements * 100));
3981 if (TotalNumMacros)
3982 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3983 NumMacrosRead, TotalNumMacros,
3984 ((float)NumMacrosRead/TotalNumMacros * 100));
3985 if (TotalLexicalDeclContexts)
3986 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3987 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3988 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3989 * 100));
3990 if (TotalVisibleDeclContexts)
3991 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3992 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3993 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3994 * 100));
3995 if (TotalNumMethodPoolEntries) {
3996 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3997 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3998 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
3999 * 100));
4000 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
4002 std::fprintf(stderr, "\n");
4005 void ASTReader::InitializeSema(Sema &S) {
4006 SemaObj = &S;
4007 S.ExternalSource = this;
4009 // Makes sure any declarations that were deserialized "too early"
4010 // still get added to the identifier's declaration chains.
4011 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4012 if (SemaObj->TUScope)
4013 SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
4015 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
4017 PreloadedDecls.clear();
4019 // If there were any tentative definitions, deserialize them and add
4020 // them to Sema's list of tentative definitions.
4021 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4022 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
4023 SemaObj->TentativeDefinitions.push_back(Var);
4026 // If there were any unused file scoped decls, deserialize them and add to
4027 // Sema's list of unused file scoped decls.
4028 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4029 DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4030 SemaObj->UnusedFileScopedDecls.push_back(D);
4033 // If there were any locally-scoped external declarations,
4034 // deserialize them and add them to Sema's table of locally-scoped
4035 // external declarations.
4036 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4037 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4038 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
4041 // If there were any ext_vector type declarations, deserialize them
4042 // and add them to Sema's vector of such declarations.
4043 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
4044 SemaObj->ExtVectorDecls.push_back(
4045 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
4047 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
4048 // Can we cut them down before writing them ?
4050 // If there were any dynamic classes declarations, deserialize them
4051 // and add them to Sema's vector of such declarations.
4052 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
4053 SemaObj->DynamicClasses.push_back(
4054 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
4056 // Load the offsets of the declarations that Sema references.
4057 // They will be lazily deserialized when needed.
4058 if (!SemaDeclRefs.empty()) {
4059 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4060 SemaObj->StdNamespace = SemaDeclRefs[0];
4061 SemaObj->StdBadAlloc = SemaDeclRefs[1];
4064 for (PerFileData *F = FirstInSource; F; F = F->NextInSource) {
4066 // If there are @selector references added them to its pool. This is for
4067 // implementation of -Wselector.
4068 if (!F->ReferencedSelectorsData.empty()) {
4069 unsigned int DataSize = F->ReferencedSelectorsData.size()-1;
4070 unsigned I = 0;
4071 while (I < DataSize) {
4072 Selector Sel = DecodeSelector(F->ReferencedSelectorsData[I++]);
4073 SourceLocation SelLoc = ReadSourceLocation(
4074 *F, F->ReferencedSelectorsData, I);
4075 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
4079 // If there were any pending implicit instantiations, deserialize them
4080 // and add them to Sema's queue of such instantiations.
4081 assert(F->PendingInstantiations.size() % 2 == 0 &&
4082 "Expected pairs of entries");
4083 for (unsigned Idx = 0, N = F->PendingInstantiations.size(); Idx < N;) {
4084 ValueDecl *D=cast<ValueDecl>(GetDecl(F->PendingInstantiations[Idx++]));
4085 SourceLocation Loc = ReadSourceLocation(*F, F->PendingInstantiations,Idx);
4086 SemaObj->PendingInstantiations.push_back(std::make_pair(D, Loc));
4090 // The two special data sets below always come from the most recent PCH,
4091 // which is at the front of the chain.
4092 PerFileData &F = *Chain.front();
4094 // If there were any weak undeclared identifiers, deserialize them and add to
4095 // Sema's list of weak undeclared identifiers.
4096 if (!WeakUndeclaredIdentifiers.empty()) {
4097 unsigned Idx = 0;
4098 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
4099 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4100 IdentifierInfo *AliasId= GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4101 SourceLocation Loc = ReadSourceLocation(F, WeakUndeclaredIdentifiers,Idx);
4102 bool Used = WeakUndeclaredIdentifiers[Idx++];
4103 Sema::WeakInfo WI(AliasId, Loc);
4104 WI.setUsed(Used);
4105 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
4109 // If there were any VTable uses, deserialize the information and add it
4110 // to Sema's vector and map of VTable uses.
4111 if (!VTableUses.empty()) {
4112 unsigned Idx = 0;
4113 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
4114 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4115 SourceLocation Loc = ReadSourceLocation(F, VTableUses, Idx);
4116 bool DefinitionRequired = VTableUses[Idx++];
4117 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
4118 SemaObj->VTablesUsed[Class] = DefinitionRequired;
4122 if (!FPPragmaOptions.empty()) {
4123 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4124 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4127 if (!OpenCLExtensions.empty()) {
4128 unsigned I = 0;
4129 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4130 #include "clang/Basic/OpenCLExtensions.def"
4132 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4136 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4137 // Try to find this name within our on-disk hash tables. We start with the
4138 // most recent one, since that one contains the most up-to-date info.
4139 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4140 ASTIdentifierLookupTable *IdTable
4141 = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
4142 if (!IdTable)
4143 continue;
4144 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
4145 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
4146 if (Pos == IdTable->end())
4147 continue;
4149 // Dereferencing the iterator has the effect of building the
4150 // IdentifierInfo node and populating it with the various
4151 // declarations it needs.
4152 return *Pos;
4154 return 0;
4157 namespace clang {
4158 /// \brief An identifier-lookup iterator that enumerates all of the
4159 /// identifiers stored within a set of AST files.
4160 class ASTIdentifierIterator : public IdentifierIterator {
4161 /// \brief The AST reader whose identifiers are being enumerated.
4162 const ASTReader &Reader;
4164 /// \brief The current index into the chain of AST files stored in
4165 /// the AST reader.
4166 unsigned Index;
4168 /// \brief The current position within the identifier lookup table
4169 /// of the current AST file.
4170 ASTIdentifierLookupTable::key_iterator Current;
4172 /// \brief The end position within the identifier lookup table of
4173 /// the current AST file.
4174 ASTIdentifierLookupTable::key_iterator End;
4176 public:
4177 explicit ASTIdentifierIterator(const ASTReader &Reader);
4179 virtual llvm::StringRef Next();
4183 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4184 : Reader(Reader), Index(Reader.Chain.size() - 1) {
4185 ASTIdentifierLookupTable *IdTable
4186 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4187 Current = IdTable->key_begin();
4188 End = IdTable->key_end();
4191 llvm::StringRef ASTIdentifierIterator::Next() {
4192 while (Current == End) {
4193 // If we have exhausted all of our AST files, we're done.
4194 if (Index == 0)
4195 return llvm::StringRef();
4197 --Index;
4198 ASTIdentifierLookupTable *IdTable
4199 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4200 Current = IdTable->key_begin();
4201 End = IdTable->key_end();
4204 // We have any identifiers remaining in the current AST file; return
4205 // the next one.
4206 std::pair<const char*, unsigned> Key = *Current;
4207 ++Current;
4208 return llvm::StringRef(Key.first, Key.second);
4211 IdentifierIterator *ASTReader::getIdentifiers() const {
4212 return new ASTIdentifierIterator(*this);
4215 std::pair<ObjCMethodList, ObjCMethodList>
4216 ASTReader::ReadMethodPool(Selector Sel) {
4217 // Find this selector in a hash table. We want to find the most recent entry.
4218 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4219 PerFileData &F = *Chain[I];
4220 if (!F.SelectorLookupTable)
4221 continue;
4223 ASTSelectorLookupTable *PoolTable
4224 = (ASTSelectorLookupTable*)F.SelectorLookupTable;
4225 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
4226 if (Pos != PoolTable->end()) {
4227 ++NumSelectorsRead;
4228 // FIXME: Not quite happy with the statistics here. We probably should
4229 // disable this tracking when called via LoadSelector.
4230 // Also, should entries without methods count as misses?
4231 ++NumMethodPoolEntriesRead;
4232 ASTSelectorLookupTrait::data_type Data = *Pos;
4233 if (DeserializationListener)
4234 DeserializationListener->SelectorRead(Data.ID, Sel);
4235 return std::make_pair(Data.Instance, Data.Factory);
4239 ++NumMethodPoolMisses;
4240 return std::pair<ObjCMethodList, ObjCMethodList>();
4243 void ASTReader::LoadSelector(Selector Sel) {
4244 // It would be complicated to avoid reading the methods anyway. So don't.
4245 ReadMethodPool(Sel);
4248 void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
4249 assert(ID && "Non-zero identifier ID required");
4250 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4251 IdentifiersLoaded[ID - 1] = II;
4252 if (DeserializationListener)
4253 DeserializationListener->IdentifierRead(ID, II);
4256 /// \brief Set the globally-visible declarations associated with the given
4257 /// identifier.
4259 /// If the AST reader is currently in a state where the given declaration IDs
4260 /// cannot safely be resolved, they are queued until it is safe to resolve
4261 /// them.
4263 /// \param II an IdentifierInfo that refers to one or more globally-visible
4264 /// declarations.
4266 /// \param DeclIDs the set of declaration IDs with the name @p II that are
4267 /// visible at global scope.
4269 /// \param Nonrecursive should be true to indicate that the caller knows that
4270 /// this call is non-recursive, and therefore the globally-visible declarations
4271 /// will not be placed onto the pending queue.
4272 void
4273 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4274 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
4275 bool Nonrecursive) {
4276 if (NumCurrentElementsDeserializing && !Nonrecursive) {
4277 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4278 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4279 PII.II = II;
4280 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4281 return;
4284 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4285 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4286 if (SemaObj) {
4287 if (SemaObj->TUScope) {
4288 // Introduce this declaration into the translation-unit scope
4289 // and add it to the declaration chain for this identifier, so
4290 // that (unqualified) name lookup will find it.
4291 SemaObj->TUScope->AddDecl(D);
4293 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
4294 } else {
4295 // Queue this declaration so that it will be added to the
4296 // translation unit scope and identifier's declaration chain
4297 // once a Sema object is known.
4298 PreloadedDecls.push_back(D);
4303 IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) {
4304 if (ID == 0)
4305 return 0;
4307 if (IdentifiersLoaded.empty()) {
4308 Error("no identifier table in AST file");
4309 return 0;
4312 assert(PP && "Forgot to set Preprocessor ?");
4313 ID -= 1;
4314 if (!IdentifiersLoaded[ID]) {
4315 unsigned Index = ID;
4316 const char *Str = 0;
4317 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4318 PerFileData *F = Chain[N - I - 1];
4319 if (Index < F->LocalNumIdentifiers) {
4320 uint32_t Offset = F->IdentifierOffsets[Index];
4321 Str = F->IdentifierTableData + Offset;
4322 break;
4324 Index -= F->LocalNumIdentifiers;
4326 assert(Str && "Broken Chain");
4328 // All of the strings in the AST file are preceded by a 16-bit length.
4329 // Extract that 16-bit length to avoid having to execute strlen().
4330 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4331 // unsigned integers. This is important to avoid integer overflow when
4332 // we cast them to 'unsigned'.
4333 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4334 unsigned StrLen = (((unsigned) StrLenPtr[0])
4335 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4336 IdentifiersLoaded[ID]
4337 = &PP->getIdentifierTable().get(Str, StrLen);
4338 if (DeserializationListener)
4339 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4342 return IdentifiersLoaded[ID];
4345 void ASTReader::ReadSLocEntry(unsigned ID) {
4346 ReadSLocEntryRecord(ID);
4349 Selector ASTReader::DecodeSelector(unsigned ID) {
4350 if (ID == 0)
4351 return Selector();
4353 if (ID > SelectorsLoaded.size()) {
4354 Error("selector ID out of range in AST file");
4355 return Selector();
4358 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4359 // Load this selector from the selector table.
4360 unsigned Idx = ID - 1;
4361 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4362 PerFileData &F = *Chain[N - I - 1];
4363 if (Idx < F.LocalNumSelectors) {
4364 ASTSelectorLookupTrait Trait(*this);
4365 SelectorsLoaded[ID - 1] =
4366 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
4367 if (DeserializationListener)
4368 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
4369 break;
4371 Idx -= F.LocalNumSelectors;
4375 return SelectorsLoaded[ID - 1];
4378 Selector ASTReader::GetExternalSelector(uint32_t ID) {
4379 return DecodeSelector(ID);
4382 uint32_t ASTReader::GetNumExternalSelectors() {
4383 // ID 0 (the null selector) is considered an external selector.
4384 return getTotalNumSelectors() + 1;
4387 DeclarationName
4388 ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
4389 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
4390 switch (Kind) {
4391 case DeclarationName::Identifier:
4392 return DeclarationName(GetIdentifierInfo(Record, Idx));
4394 case DeclarationName::ObjCZeroArgSelector:
4395 case DeclarationName::ObjCOneArgSelector:
4396 case DeclarationName::ObjCMultiArgSelector:
4397 return DeclarationName(GetSelector(Record, Idx));
4399 case DeclarationName::CXXConstructorName:
4400 return Context->DeclarationNames.getCXXConstructorName(
4401 Context->getCanonicalType(GetType(Record[Idx++])));
4403 case DeclarationName::CXXDestructorName:
4404 return Context->DeclarationNames.getCXXDestructorName(
4405 Context->getCanonicalType(GetType(Record[Idx++])));
4407 case DeclarationName::CXXConversionFunctionName:
4408 return Context->DeclarationNames.getCXXConversionFunctionName(
4409 Context->getCanonicalType(GetType(Record[Idx++])));
4411 case DeclarationName::CXXOperatorName:
4412 return Context->DeclarationNames.getCXXOperatorName(
4413 (OverloadedOperatorKind)Record[Idx++]);
4415 case DeclarationName::CXXLiteralOperatorName:
4416 return Context->DeclarationNames.getCXXLiteralOperatorName(
4417 GetIdentifierInfo(Record, Idx));
4419 case DeclarationName::CXXUsingDirective:
4420 return DeclarationName::getUsingDirectiveName();
4423 // Required to silence GCC warning
4424 return DeclarationName();
4427 void ASTReader::ReadDeclarationNameLoc(PerFileData &F,
4428 DeclarationNameLoc &DNLoc,
4429 DeclarationName Name,
4430 const RecordData &Record, unsigned &Idx) {
4431 switch (Name.getNameKind()) {
4432 case DeclarationName::CXXConstructorName:
4433 case DeclarationName::CXXDestructorName:
4434 case DeclarationName::CXXConversionFunctionName:
4435 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
4436 break;
4438 case DeclarationName::CXXOperatorName:
4439 DNLoc.CXXOperatorName.BeginOpNameLoc
4440 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4441 DNLoc.CXXOperatorName.EndOpNameLoc
4442 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4443 break;
4445 case DeclarationName::CXXLiteralOperatorName:
4446 DNLoc.CXXLiteralOperatorName.OpNameLoc
4447 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4448 break;
4450 case DeclarationName::Identifier:
4451 case DeclarationName::ObjCZeroArgSelector:
4452 case DeclarationName::ObjCOneArgSelector:
4453 case DeclarationName::ObjCMultiArgSelector:
4454 case DeclarationName::CXXUsingDirective:
4455 break;
4459 void ASTReader::ReadDeclarationNameInfo(PerFileData &F,
4460 DeclarationNameInfo &NameInfo,
4461 const RecordData &Record, unsigned &Idx) {
4462 NameInfo.setName(ReadDeclarationName(Record, Idx));
4463 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
4464 DeclarationNameLoc DNLoc;
4465 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
4466 NameInfo.setInfo(DNLoc);
4469 void ASTReader::ReadQualifierInfo(PerFileData &F, QualifierInfo &Info,
4470 const RecordData &Record, unsigned &Idx) {
4471 Info.NNS = ReadNestedNameSpecifier(Record, Idx);
4472 Info.NNSRange = ReadSourceRange(F, Record, Idx);
4473 unsigned NumTPLists = Record[Idx++];
4474 Info.NumTemplParamLists = NumTPLists;
4475 if (NumTPLists) {
4476 Info.TemplParamLists = new (*Context) TemplateParameterList*[NumTPLists];
4477 for (unsigned i=0; i != NumTPLists; ++i)
4478 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
4482 TemplateName
4483 ASTReader::ReadTemplateName(PerFileData &F, const RecordData &Record,
4484 unsigned &Idx) {
4485 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
4486 switch (Kind) {
4487 case TemplateName::Template:
4488 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
4490 case TemplateName::OverloadedTemplate: {
4491 unsigned size = Record[Idx++];
4492 UnresolvedSet<8> Decls;
4493 while (size--)
4494 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
4496 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
4499 case TemplateName::QualifiedTemplate: {
4500 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4501 bool hasTemplKeyword = Record[Idx++];
4502 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
4503 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
4506 case TemplateName::DependentTemplate: {
4507 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4508 if (Record[Idx++]) // isIdentifier
4509 return Context->getDependentTemplateName(NNS,
4510 GetIdentifierInfo(Record, Idx));
4511 return Context->getDependentTemplateName(NNS,
4512 (OverloadedOperatorKind)Record[Idx++]);
4515 case TemplateName::SubstTemplateTemplateParmPack: {
4516 TemplateTemplateParmDecl *Param
4517 = cast_or_null<TemplateTemplateParmDecl>(GetDecl(Record[Idx++]));
4518 if (!Param)
4519 return TemplateName();
4521 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
4522 if (ArgPack.getKind() != TemplateArgument::Pack)
4523 return TemplateName();
4525 return Context->getSubstTemplateTemplateParmPack(Param, ArgPack);
4529 assert(0 && "Unhandled template name kind!");
4530 return TemplateName();
4533 TemplateArgument
4534 ASTReader::ReadTemplateArgument(PerFileData &F,
4535 const RecordData &Record, unsigned &Idx) {
4536 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
4537 switch (Kind) {
4538 case TemplateArgument::Null:
4539 return TemplateArgument();
4540 case TemplateArgument::Type:
4541 return TemplateArgument(GetType(Record[Idx++]));
4542 case TemplateArgument::Declaration:
4543 return TemplateArgument(GetDecl(Record[Idx++]));
4544 case TemplateArgument::Integral: {
4545 llvm::APSInt Value = ReadAPSInt(Record, Idx);
4546 QualType T = GetType(Record[Idx++]);
4547 return TemplateArgument(Value, T);
4549 case TemplateArgument::Template:
4550 return TemplateArgument(ReadTemplateName(F, Record, Idx));
4551 case TemplateArgument::TemplateExpansion: {
4552 TemplateName Name = ReadTemplateName(F, Record, Idx);
4553 llvm::Optional<unsigned> NumTemplateExpansions;
4554 if (unsigned NumExpansions = Record[Idx++])
4555 NumTemplateExpansions = NumExpansions - 1;
4556 return TemplateArgument(Name, NumTemplateExpansions);
4558 case TemplateArgument::Expression:
4559 return TemplateArgument(ReadExpr(F));
4560 case TemplateArgument::Pack: {
4561 unsigned NumArgs = Record[Idx++];
4562 TemplateArgument *Args = new (*Context) TemplateArgument[NumArgs];
4563 for (unsigned I = 0; I != NumArgs; ++I)
4564 Args[I] = ReadTemplateArgument(F, Record, Idx);
4565 return TemplateArgument(Args, NumArgs);
4569 assert(0 && "Unhandled template argument kind!");
4570 return TemplateArgument();
4573 TemplateParameterList *
4574 ASTReader::ReadTemplateParameterList(PerFileData &F,
4575 const RecordData &Record, unsigned &Idx) {
4576 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
4577 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
4578 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
4580 unsigned NumParams = Record[Idx++];
4581 llvm::SmallVector<NamedDecl *, 16> Params;
4582 Params.reserve(NumParams);
4583 while (NumParams--)
4584 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
4586 TemplateParameterList* TemplateParams =
4587 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
4588 Params.data(), Params.size(), RAngleLoc);
4589 return TemplateParams;
4592 void
4593 ASTReader::
4594 ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
4595 PerFileData &F, const RecordData &Record,
4596 unsigned &Idx) {
4597 unsigned NumTemplateArgs = Record[Idx++];
4598 TemplArgs.reserve(NumTemplateArgs);
4599 while (NumTemplateArgs--)
4600 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
4603 /// \brief Read a UnresolvedSet structure.
4604 void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
4605 const RecordData &Record, unsigned &Idx) {
4606 unsigned NumDecls = Record[Idx++];
4607 while (NumDecls--) {
4608 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
4609 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
4610 Set.addDecl(D, AS);
4614 CXXBaseSpecifier
4615 ASTReader::ReadCXXBaseSpecifier(PerFileData &F,
4616 const RecordData &Record, unsigned &Idx) {
4617 bool isVirtual = static_cast<bool>(Record[Idx++]);
4618 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
4619 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
4620 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
4621 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
4622 SourceRange Range = ReadSourceRange(F, Record, Idx);
4623 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
4624 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
4625 EllipsisLoc);
4626 Result.setInheritConstructors(inheritConstructors);
4627 return Result;
4630 std::pair<CXXCtorInitializer **, unsigned>
4631 ASTReader::ReadCXXCtorInitializers(PerFileData &F, const RecordData &Record,
4632 unsigned &Idx) {
4633 CXXCtorInitializer **CtorInitializers = 0;
4634 unsigned NumInitializers = Record[Idx++];
4635 if (NumInitializers) {
4636 ASTContext &C = *getContext();
4638 CtorInitializers
4639 = new (C) CXXCtorInitializer*[NumInitializers];
4640 for (unsigned i=0; i != NumInitializers; ++i) {
4641 TypeSourceInfo *BaseClassInfo = 0;
4642 bool IsBaseVirtual = false;
4643 FieldDecl *Member = 0;
4644 IndirectFieldDecl *IndirectMember = 0;
4646 bool IsBaseInitializer = Record[Idx++];
4647 if (IsBaseInitializer) {
4648 BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
4649 IsBaseVirtual = Record[Idx++];
4650 } else {
4651 bool IsIndirectMemberInitializer = Record[Idx++];
4652 if (IsIndirectMemberInitializer)
4653 IndirectMember = cast<IndirectFieldDecl>(GetDecl(Record[Idx++]));
4654 else
4655 Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
4657 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
4658 Expr *Init = ReadExpr(F);
4659 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
4660 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
4661 bool IsWritten = Record[Idx++];
4662 unsigned SourceOrderOrNumArrayIndices;
4663 llvm::SmallVector<VarDecl *, 8> Indices;
4664 if (IsWritten) {
4665 SourceOrderOrNumArrayIndices = Record[Idx++];
4666 } else {
4667 SourceOrderOrNumArrayIndices = Record[Idx++];
4668 Indices.reserve(SourceOrderOrNumArrayIndices);
4669 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
4670 Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
4673 CXXCtorInitializer *BOMInit;
4674 if (IsBaseInitializer) {
4675 BOMInit = new (C) CXXCtorInitializer(C, BaseClassInfo, IsBaseVirtual,
4676 LParenLoc, Init, RParenLoc,
4677 MemberOrEllipsisLoc);
4678 } else if (IsWritten) {
4679 if (Member)
4680 BOMInit = new (C) CXXCtorInitializer(C, Member, MemberOrEllipsisLoc,
4681 LParenLoc, Init, RParenLoc);
4682 else
4683 BOMInit = new (C) CXXCtorInitializer(C, IndirectMember,
4684 MemberOrEllipsisLoc, LParenLoc,
4685 Init, RParenLoc);
4686 } else {
4687 BOMInit = CXXCtorInitializer::Create(C, Member, MemberOrEllipsisLoc,
4688 LParenLoc, Init, RParenLoc,
4689 Indices.data(), Indices.size());
4692 if (IsWritten)
4693 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
4694 CtorInitializers[i] = BOMInit;
4698 return std::make_pair(CtorInitializers, NumInitializers);
4701 NestedNameSpecifier *
4702 ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
4703 unsigned N = Record[Idx++];
4704 NestedNameSpecifier *NNS = 0, *Prev = 0;
4705 for (unsigned I = 0; I != N; ++I) {
4706 NestedNameSpecifier::SpecifierKind Kind
4707 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
4708 switch (Kind) {
4709 case NestedNameSpecifier::Identifier: {
4710 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
4711 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
4712 break;
4715 case NestedNameSpecifier::Namespace: {
4716 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
4717 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
4718 break;
4721 case NestedNameSpecifier::TypeSpec:
4722 case NestedNameSpecifier::TypeSpecWithTemplate: {
4723 const Type *T = GetType(Record[Idx++]).getTypePtrOrNull();
4724 if (!T)
4725 return 0;
4727 bool Template = Record[Idx++];
4728 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
4729 break;
4732 case NestedNameSpecifier::Global: {
4733 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
4734 // No associated value, and there can't be a prefix.
4735 break;
4738 Prev = NNS;
4740 return NNS;
4743 SourceRange
4744 ASTReader::ReadSourceRange(PerFileData &F, const RecordData &Record,
4745 unsigned &Idx) {
4746 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
4747 SourceLocation end = ReadSourceLocation(F, Record, Idx);
4748 return SourceRange(beg, end);
4751 /// \brief Read an integral value
4752 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
4753 unsigned BitWidth = Record[Idx++];
4754 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
4755 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
4756 Idx += NumWords;
4757 return Result;
4760 /// \brief Read a signed integral value
4761 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
4762 bool isUnsigned = Record[Idx++];
4763 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
4766 /// \brief Read a floating-point value
4767 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
4768 return llvm::APFloat(ReadAPInt(Record, Idx));
4771 // \brief Read a string
4772 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
4773 unsigned Len = Record[Idx++];
4774 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
4775 Idx += Len;
4776 return Result;
4779 CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record,
4780 unsigned &Idx) {
4781 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
4782 return CXXTemporary::Create(*Context, Decl);
4785 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
4786 return Diag(SourceLocation(), DiagID);
4789 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
4790 return Diags.Report(Loc, DiagID);
4793 /// \brief Retrieve the identifier table associated with the
4794 /// preprocessor.
4795 IdentifierTable &ASTReader::getIdentifierTable() {
4796 assert(PP && "Forgot to set Preprocessor ?");
4797 return PP->getIdentifierTable();
4800 /// \brief Record that the given ID maps to the given switch-case
4801 /// statement.
4802 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
4803 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
4804 SwitchCaseStmts[ID] = SC;
4807 /// \brief Retrieve the switch-case statement with the given ID.
4808 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
4809 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
4810 return SwitchCaseStmts[ID];
4813 void ASTReader::ClearSwitchCaseIDs() {
4814 SwitchCaseStmts.clear();
4817 void ASTReader::FinishedDeserializing() {
4818 assert(NumCurrentElementsDeserializing &&
4819 "FinishedDeserializing not paired with StartedDeserializing");
4820 if (NumCurrentElementsDeserializing == 1) {
4821 // If any identifiers with corresponding top-level declarations have
4822 // been loaded, load those declarations now.
4823 while (!PendingIdentifierInfos.empty()) {
4824 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
4825 PendingIdentifierInfos.front().DeclIDs, true);
4826 PendingIdentifierInfos.pop_front();
4829 // Ready to load previous declarations of Decls that were delayed.
4830 while (!PendingPreviousDecls.empty()) {
4831 loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
4832 PendingPreviousDecls.front().second);
4833 PendingPreviousDecls.pop_front();
4836 // We are not in recursive loading, so it's safe to pass the "interesting"
4837 // decls to the consumer.
4838 if (Consumer)
4839 PassInterestingDeclsToConsumer();
4841 assert(PendingForwardRefs.size() == 0 &&
4842 "Some forward refs did not get linked to the definition!");
4844 --NumCurrentElementsDeserializing;
4847 ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
4848 const char *isysroot, bool DisableValidation,
4849 bool DisableStatCache)
4850 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
4851 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
4852 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
4853 Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
4854 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
4855 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NextSLocOffset(0),
4856 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
4857 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
4858 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
4859 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
4860 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
4861 NumCurrentElementsDeserializing(0)
4863 RelocatablePCH = false;
4866 ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
4867 Diagnostic &Diags, const char *isysroot,
4868 bool DisableValidation, bool DisableStatCache)
4869 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
4870 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
4871 isysroot(isysroot), DisableValidation(DisableValidation),
4872 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
4873 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
4874 NextSLocOffset(0), NumStatementsRead(0), TotalNumStatements(0),
4875 NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
4876 NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
4877 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
4878 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
4879 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
4880 RelocatablePCH = false;
4883 ASTReader::~ASTReader() {
4884 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
4885 delete Chain[e - i - 1];
4886 // Delete all visible decl lookup tables
4887 for (DeclContextOffsetsMap::iterator I = DeclContextOffsets.begin(),
4888 E = DeclContextOffsets.end();
4889 I != E; ++I) {
4890 for (DeclContextInfos::iterator J = I->second.begin(), F = I->second.end();
4891 J != F; ++J) {
4892 if (J->NameLookupTableData)
4893 delete static_cast<ASTDeclContextNameLookupTable*>(
4894 J->NameLookupTableData);
4897 for (DeclContextVisibleUpdatesPending::iterator
4898 I = PendingVisibleUpdates.begin(),
4899 E = PendingVisibleUpdates.end();
4900 I != E; ++I) {
4901 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
4902 F = I->second.end();
4903 J != F; ++J)
4904 delete static_cast<ASTDeclContextNameLookupTable*>(*J);
4908 ASTReader::PerFileData::PerFileData(ASTFileType Ty)
4909 : Type(Ty), SizeInBits(0), LocalNumSLocEntries(0), SLocOffsets(0), LocalSLocSize(0),
4910 LocalNumIdentifiers(0), IdentifierOffsets(0), IdentifierTableData(0),
4911 IdentifierLookupTable(0), LocalNumMacroDefinitions(0),
4912 MacroDefinitionOffsets(0),
4913 LocalNumHeaderFileInfos(0), HeaderFileInfoTableData(0),
4914 HeaderFileInfoTable(0),
4915 LocalNumSelectors(0), SelectorOffsets(0),
4916 SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
4917 DeclOffsets(0), LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0),
4918 LocalNumTypes(0), TypeOffsets(0), StatCache(0),
4919 NumPreallocatedPreprocessingEntities(0), NextInSource(0)
4922 ASTReader::PerFileData::~PerFileData() {
4923 delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable);
4924 delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable);
4925 delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable);