blob: 9ab3b7a0a2610463805032f1c6cd5bdfbaa1f206 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- PCHReader.cpp - Precompiled Headers 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 PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHReader.h"
15#include "clang/Frontend/FrontendDiagnostic.h"
16#include "clang/Frontend/Utils.h"
17#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeLocVisitor.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Lex/HeaderSearch.h"
26#include "clang/Basic/OnDiskHashTable.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/FileManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/Version.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Bitcode/BitstreamReader.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/System/Path.h"
37#include <algorithm>
38#include <iterator>
39#include <cstdio>
40#include <sys/stat.h>
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
75 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
76 PARSE_LANGOPT_BENIGN(PascalStrings);
77 PARSE_LANGOPT_BENIGN(WritableStrings);
78 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
79 diag::warn_pch_lax_vector_conversions);
80 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
81 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
82 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
83 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
84 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
85 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
86 diag::warn_pch_thread_safe_statics);
87 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
88 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
89 PARSE_LANGOPT_BENIGN(EmitAllDecls);
90 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
91 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
92 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
93 diag::warn_pch_heinous_extensions);
94 // FIXME: Most of the options below are benign if the macro wasn't
95 // used. Unfortunately, this means that a PCH compiled without
96 // optimization can't be used with optimization turned on, even
97 // though the only thing that changes is whether __OPTIMIZE__ was
98 // defined... but if __OPTIMIZE__ never showed up in the header, it
99 // doesn't matter. We could consider making this some special kind
100 // of check.
101 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
102 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
103 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
104 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
105 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
106 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
107 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
108 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
109 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
110 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
111 Reader.Diag(diag::warn_pch_gc_mode)
112 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
113 return true;
114 }
115 PARSE_LANGOPT_BENIGN(getVisibilityMode());
116 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
117 diag::warn_pch_stack_protector);
118 PARSE_LANGOPT_BENIGN(InstantiationDepth);
119 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
120 PARSE_LANGOPT_BENIGN(CatchUndefined);
121 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
122#undef PARSE_LANGOPT_IRRELEVANT
123#undef PARSE_LANGOPT_BENIGN
124
125 return false;
126}
127
128bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
129 if (Triple == PP.getTargetInfo().getTriple().str())
130 return false;
131
132 Reader.Diag(diag::warn_pch_target_triple)
133 << Triple << PP.getTargetInfo().getTriple().str();
134 return true;
135}
136
137bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
138 FileID PCHBufferID,
139 llvm::StringRef OriginalFileName,
140 std::string &SuggestedPredefines) {
141 // We are in the context of an implicit include, so the predefines buffer will
142 // have a #include entry for the PCH file itself (as normalized by the
143 // preprocessor initialization). Find it and skip over it in the checking
144 // below.
145 llvm::SmallString<256> PCHInclude;
146 PCHInclude += "#include \"";
147 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
148 PCHInclude += "\"\n";
149 std::pair<llvm::StringRef,llvm::StringRef> Split =
150 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
151 llvm::StringRef Left = Split.first, Right = Split.second;
152 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
153
154 // If the predefines is equal to the joined left and right halves, we're done!
155 if (Left.size() + Right.size() == PCHPredef.size() &&
156 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
157 return false;
158
159 SourceManager &SourceMgr = PP.getSourceManager();
160
161 // The predefines buffers are different. Determine what the differences are,
162 // and whether they require us to reject the PCH file.
163 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
164 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
165
166 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
167 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
168 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
169
170 // Sort both sets of predefined buffer lines, since we allow some extra
171 // definitions and they may appear at any point in the output.
172 std::sort(CmdLineLines.begin(), CmdLineLines.end());
173 std::sort(PCHLines.begin(), PCHLines.end());
174
175 // Determine which predefines that were used to build the PCH file are missing
176 // from the command line.
177 std::vector<llvm::StringRef> MissingPredefines;
178 std::set_difference(PCHLines.begin(), PCHLines.end(),
179 CmdLineLines.begin(), CmdLineLines.end(),
180 std::back_inserter(MissingPredefines));
181
182 bool MissingDefines = false;
183 bool ConflictingDefines = false;
184 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
185 llvm::StringRef Missing = MissingPredefines[I];
186 if (!Missing.startswith("#define ")) {
187 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
188 return true;
189 }
190
191 // This is a macro definition. Determine the name of the macro we're
192 // defining.
193 std::string::size_type StartOfMacroName = strlen("#define ");
194 std::string::size_type EndOfMacroName
195 = Missing.find_first_of("( \n\r", StartOfMacroName);
196 assert(EndOfMacroName != std::string::npos &&
197 "Couldn't find the end of the macro name");
198 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
199
200 // Determine whether this macro was given a different definition on the
201 // command line.
202 std::string MacroDefStart = "#define " + MacroName.str();
203 std::string::size_type MacroDefLen = MacroDefStart.size();
204 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
205 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
206 MacroDefStart);
207 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
208 if (!ConflictPos->startswith(MacroDefStart)) {
209 // Different macro; we're done.
210 ConflictPos = CmdLineLines.end();
211 break;
212 }
213
214 assert(ConflictPos->size() > MacroDefLen &&
215 "Invalid #define in predefines buffer?");
216 if ((*ConflictPos)[MacroDefLen] != ' ' &&
217 (*ConflictPos)[MacroDefLen] != '(')
218 continue; // Longer macro name; keep trying.
219
220 // We found a conflicting macro definition.
221 break;
222 }
223
224 if (ConflictPos != CmdLineLines.end()) {
225 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
226 << MacroName;
227
228 // Show the definition of this macro within the PCH file.
229 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
230 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
231 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
232 .getFileLocWithOffset(Offset);
233 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
234
235 ConflictingDefines = true;
236 continue;
237 }
238
239 // If the macro doesn't conflict, then we'll just pick up the macro
240 // definition from the PCH file. Warn the user that they made a mistake.
241 if (ConflictingDefines)
242 continue; // Don't complain if there are already conflicting defs
243
244 if (!MissingDefines) {
245 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
246 MissingDefines = true;
247 }
248
249 // Show the definition of this macro within the PCH file.
250 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
251 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
252 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
253 .getFileLocWithOffset(Offset);
254 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
255 }
256
257 if (ConflictingDefines)
258 return true;
259
260 // Determine what predefines were introduced based on command-line
261 // parameters that were not present when building the PCH
262 // file. Extra #defines are okay, so long as the identifiers being
263 // defined were not used within the precompiled header.
264 std::vector<llvm::StringRef> ExtraPredefines;
265 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
266 PCHLines.begin(), PCHLines.end(),
267 std::back_inserter(ExtraPredefines));
268 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
269 llvm::StringRef &Extra = ExtraPredefines[I];
270 if (!Extra.startswith("#define ")) {
271 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
272 return true;
273 }
274
275 // This is an extra macro definition. Determine the name of the
276 // macro we're defining.
277 std::string::size_type StartOfMacroName = strlen("#define ");
278 std::string::size_type EndOfMacroName
279 = Extra.find_first_of("( \n\r", StartOfMacroName);
280 assert(EndOfMacroName != std::string::npos &&
281 "Couldn't find the end of the macro name");
282 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
283
284 // Check whether this name was used somewhere in the PCH file. If
285 // so, defining it as a macro could change behavior, so we reject
286 // the PCH file.
287 if (IdentifierInfo *II = Reader.get(MacroName)) {
288 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
289 return true;
290 }
291
292 // Add this definition to the suggested predefines buffer.
293 SuggestedPredefines += Extra;
294 SuggestedPredefines += '\n';
295 }
296
297 // If we get here, it's because the predefines buffer had compatible
298 // contents. Accept the PCH file.
299 return false;
300}
301
302void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
303 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
304}
305
306void PCHValidator::ReadCounter(unsigned Value) {
307 PP.setCounterValue(Value);
308}
309
310//===----------------------------------------------------------------------===//
311// PCH reader implementation
312//===----------------------------------------------------------------------===//
313
314PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
315 const char *isysroot)
316 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
317 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
318 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
319 IdentifierTableData(0), IdentifierLookupTable(0),
320 IdentifierOffsets(0),
321 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
322 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
323 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
324 NumStatHits(0), NumStatMisses(0),
325 NumSLocEntriesRead(0), NumStatementsRead(0),
326 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
327 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
328 CurrentlyLoadingTypeOrDecl(0) {
329 RelocatablePCH = false;
330}
331
332PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
333 Diagnostic &Diags, const char *isysroot)
334 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
335 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
336 IdentifierTableData(0), IdentifierLookupTable(0),
337 IdentifierOffsets(0),
338 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
339 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
340 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
341 NumStatHits(0), NumStatMisses(0),
342 NumSLocEntriesRead(0), NumStatementsRead(0),
343 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
344 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
345 CurrentlyLoadingTypeOrDecl(0) {
346 RelocatablePCH = false;
347}
348
349PCHReader::~PCHReader() {}
350
351Expr *PCHReader::ReadDeclExpr() {
352 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
353}
354
355Expr *PCHReader::ReadTypeExpr() {
356 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
357}
358
359
360namespace {
361class PCHMethodPoolLookupTrait {
362 PCHReader &Reader;
363
364public:
365 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
366
367 typedef Selector external_key_type;
368 typedef external_key_type internal_key_type;
369
370 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
371
372 static bool EqualKey(const internal_key_type& a,
373 const internal_key_type& b) {
374 return a == b;
375 }
376
377 static unsigned ComputeHash(Selector Sel) {
378 unsigned N = Sel.getNumArgs();
379 if (N == 0)
380 ++N;
381 unsigned R = 5381;
382 for (unsigned I = 0; I != N; ++I)
383 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
384 R = llvm::HashString(II->getName(), R);
385 return R;
386 }
387
388 // This hopefully will just get inlined and removed by the optimizer.
389 static const internal_key_type&
390 GetInternalKey(const external_key_type& x) { return x; }
391
392 static std::pair<unsigned, unsigned>
393 ReadKeyDataLength(const unsigned char*& d) {
394 using namespace clang::io;
395 unsigned KeyLen = ReadUnalignedLE16(d);
396 unsigned DataLen = ReadUnalignedLE16(d);
397 return std::make_pair(KeyLen, DataLen);
398 }
399
400 internal_key_type ReadKey(const unsigned char* d, unsigned) {
401 using namespace clang::io;
402 SelectorTable &SelTable = Reader.getContext()->Selectors;
403 unsigned N = ReadUnalignedLE16(d);
404 IdentifierInfo *FirstII
405 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
406 if (N == 0)
407 return SelTable.getNullarySelector(FirstII);
408 else if (N == 1)
409 return SelTable.getUnarySelector(FirstII);
410
411 llvm::SmallVector<IdentifierInfo *, 16> Args;
412 Args.push_back(FirstII);
413 for (unsigned I = 1; I != N; ++I)
414 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
415
416 return SelTable.getSelector(N, Args.data());
417 }
418
419 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
420 using namespace clang::io;
421 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
422 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
423
424 data_type Result;
425
426 // Load instance methods
427 ObjCMethodList *Prev = 0;
428 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
429 ObjCMethodDecl *Method
430 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
431 if (!Result.first.Method) {
432 // This is the first method, which is the easy case.
433 Result.first.Method = Method;
434 Prev = &Result.first;
435 continue;
436 }
437
438 Prev->Next = new ObjCMethodList(Method, 0);
439 Prev = Prev->Next;
440 }
441
442 // Load factory methods
443 Prev = 0;
444 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
445 ObjCMethodDecl *Method
446 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
447 if (!Result.second.Method) {
448 // This is the first method, which is the easy case.
449 Result.second.Method = Method;
450 Prev = &Result.second;
451 continue;
452 }
453
454 Prev->Next = new ObjCMethodList(Method, 0);
455 Prev = Prev->Next;
456 }
457
458 return Result;
459 }
460};
461
462} // end anonymous namespace
463
464/// \brief The on-disk hash table used for the global method pool.
465typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
466 PCHMethodPoolLookupTable;
467
468namespace {
469class PCHIdentifierLookupTrait {
470 PCHReader &Reader;
471
472 // If we know the IdentifierInfo in advance, it is here and we will
473 // not build a new one. Used when deserializing information about an
474 // identifier that was constructed before the PCH file was read.
475 IdentifierInfo *KnownII;
476
477public:
478 typedef IdentifierInfo * data_type;
479
480 typedef const std::pair<const char*, unsigned> external_key_type;
481
482 typedef external_key_type internal_key_type;
483
484 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
485 : Reader(Reader), KnownII(II) { }
486
487 static bool EqualKey(const internal_key_type& a,
488 const internal_key_type& b) {
489 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
490 : false;
491 }
492
493 static unsigned ComputeHash(const internal_key_type& a) {
494 return llvm::HashString(llvm::StringRef(a.first, a.second));
495 }
496
497 // This hopefully will just get inlined and removed by the optimizer.
498 static const internal_key_type&
499 GetInternalKey(const external_key_type& x) { return x; }
500
501 static std::pair<unsigned, unsigned>
502 ReadKeyDataLength(const unsigned char*& d) {
503 using namespace clang::io;
504 unsigned DataLen = ReadUnalignedLE16(d);
505 unsigned KeyLen = ReadUnalignedLE16(d);
506 return std::make_pair(KeyLen, DataLen);
507 }
508
509 static std::pair<const char*, unsigned>
510 ReadKey(const unsigned char* d, unsigned n) {
511 assert(n >= 2 && d[n-1] == '\0');
512 return std::make_pair((const char*) d, n-1);
513 }
514
515 IdentifierInfo *ReadData(const internal_key_type& k,
516 const unsigned char* d,
517 unsigned DataLen) {
518 using namespace clang::io;
519 pch::IdentID ID = ReadUnalignedLE32(d);
520 bool IsInteresting = ID & 0x01;
521
522 // Wipe out the "is interesting" bit.
523 ID = ID >> 1;
524
525 if (!IsInteresting) {
526 // For unintersting identifiers, just build the IdentifierInfo
527 // and associate it with the persistent ID.
528 IdentifierInfo *II = KnownII;
529 if (!II)
530 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
531 k.first, k.first + k.second);
532 Reader.SetIdentifierInfo(ID, II);
533 return II;
534 }
535
536 unsigned Bits = ReadUnalignedLE16(d);
537 bool CPlusPlusOperatorKeyword = Bits & 0x01;
538 Bits >>= 1;
539 bool Poisoned = Bits & 0x01;
540 Bits >>= 1;
541 bool ExtensionToken = Bits & 0x01;
542 Bits >>= 1;
543 bool hasMacroDefinition = Bits & 0x01;
544 Bits >>= 1;
545 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
546 Bits >>= 10;
547
548 assert(Bits == 0 && "Extra bits in the identifier?");
549 DataLen -= 6;
550
551 // Build the IdentifierInfo itself and link the identifier ID with
552 // the new IdentifierInfo.
553 IdentifierInfo *II = KnownII;
554 if (!II)
555 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
556 k.first, k.first + k.second);
557 Reader.SetIdentifierInfo(ID, II);
558
559 // Set or check the various bits in the IdentifierInfo structure.
560 // FIXME: Load token IDs lazily, too?
561 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
562 assert(II->isExtensionToken() == ExtensionToken &&
563 "Incorrect extension token flag");
564 (void)ExtensionToken;
565 II->setIsPoisoned(Poisoned);
566 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
567 "Incorrect C++ operator keyword flag");
568 (void)CPlusPlusOperatorKeyword;
569
570 // If this identifier is a macro, deserialize the macro
571 // definition.
572 if (hasMacroDefinition) {
573 uint32_t Offset = ReadUnalignedLE32(d);
574 Reader.ReadMacroRecord(Offset);
575 DataLen -= 4;
576 }
577
578 // Read all of the declarations visible at global scope with this
579 // name.
580 if (Reader.getContext() == 0) return II;
581 if (DataLen > 0) {
582 llvm::SmallVector<uint32_t, 4> DeclIDs;
583 for (; DataLen > 0; DataLen -= 4)
584 DeclIDs.push_back(ReadUnalignedLE32(d));
585 Reader.SetGloballyVisibleDecls(II, DeclIDs);
586 }
587
588 return II;
589 }
590};
591
592} // end anonymous namespace
593
594/// \brief The on-disk hash table used to contain information about
595/// all of the identifiers in the program.
596typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
597 PCHIdentifierLookupTable;
598
599bool PCHReader::Error(const char *Msg) {
600 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
601 Diag(DiagID);
602 return true;
603}
604
605/// \brief Check the contents of the predefines buffer against the
606/// contents of the predefines buffer used to build the PCH file.
607///
608/// The contents of the two predefines buffers should be the same. If
609/// not, then some command-line option changed the preprocessor state
610/// and we must reject the PCH file.
611///
612/// \param PCHPredef The start of the predefines buffer in the PCH
613/// file.
614///
615/// \param PCHPredefLen The length of the predefines buffer in the PCH
616/// file.
617///
618/// \param PCHBufferID The FileID for the PCH predefines buffer.
619///
620/// \returns true if there was a mismatch (in which case the PCH file
621/// should be ignored), or false otherwise.
622bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
623 FileID PCHBufferID) {
624 if (Listener)
625 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
626 ActualOriginalFileName,
627 SuggestedPredefines);
628 return false;
629}
630
631//===----------------------------------------------------------------------===//
632// Source Manager Deserialization
633//===----------------------------------------------------------------------===//
634
635/// \brief Read the line table in the source manager block.
636/// \returns true if ther was an error.
637bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
638 unsigned Idx = 0;
639 LineTableInfo &LineTable = SourceMgr.getLineTable();
640
641 // Parse the file names
642 std::map<int, int> FileIDs;
643 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
644 // Extract the file name
645 unsigned FilenameLen = Record[Idx++];
646 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
647 Idx += FilenameLen;
648 MaybeAddSystemRootToFilename(Filename);
649 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
650 Filename.size());
651 }
652
653 // Parse the line entries
654 std::vector<LineEntry> Entries;
655 while (Idx < Record.size()) {
656 int FID = FileIDs[Record[Idx++]];
657
658 // Extract the line entries
659 unsigned NumEntries = Record[Idx++];
660 Entries.clear();
661 Entries.reserve(NumEntries);
662 for (unsigned I = 0; I != NumEntries; ++I) {
663 unsigned FileOffset = Record[Idx++];
664 unsigned LineNo = Record[Idx++];
665 int FilenameID = Record[Idx++];
666 SrcMgr::CharacteristicKind FileKind
667 = (SrcMgr::CharacteristicKind)Record[Idx++];
668 unsigned IncludeOffset = Record[Idx++];
669 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
670 FileKind, IncludeOffset));
671 }
672 LineTable.AddEntry(FID, Entries);
673 }
674
675 return false;
676}
677
678namespace {
679
680class PCHStatData {
681public:
682 const bool hasStat;
683 const ino_t ino;
684 const dev_t dev;
685 const mode_t mode;
686 const time_t mtime;
687 const off_t size;
688
689 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
690 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
691
692 PCHStatData()
693 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
694};
695
696class PCHStatLookupTrait {
697 public:
698 typedef const char *external_key_type;
699 typedef const char *internal_key_type;
700
701 typedef PCHStatData data_type;
702
703 static unsigned ComputeHash(const char *path) {
704 return llvm::HashString(path);
705 }
706
707 static internal_key_type GetInternalKey(const char *path) { return path; }
708
709 static bool EqualKey(internal_key_type a, internal_key_type b) {
710 return strcmp(a, b) == 0;
711 }
712
713 static std::pair<unsigned, unsigned>
714 ReadKeyDataLength(const unsigned char*& d) {
715 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
716 unsigned DataLen = (unsigned) *d++;
717 return std::make_pair(KeyLen + 1, DataLen);
718 }
719
720 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
721 return (const char *)d;
722 }
723
724 static data_type ReadData(const internal_key_type, const unsigned char *d,
725 unsigned /*DataLen*/) {
726 using namespace clang::io;
727
728 if (*d++ == 1)
729 return data_type();
730
731 ino_t ino = (ino_t) ReadUnalignedLE32(d);
732 dev_t dev = (dev_t) ReadUnalignedLE32(d);
733 mode_t mode = (mode_t) ReadUnalignedLE16(d);
734 time_t mtime = (time_t) ReadUnalignedLE64(d);
735 off_t size = (off_t) ReadUnalignedLE64(d);
736 return data_type(ino, dev, mode, mtime, size);
737 }
738};
739
740/// \brief stat() cache for precompiled headers.
741///
742/// This cache is very similar to the stat cache used by pretokenized
743/// headers.
744class PCHStatCache : public StatSysCallCache {
745 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
746 CacheTy *Cache;
747
748 unsigned &NumStatHits, &NumStatMisses;
749public:
750 PCHStatCache(const unsigned char *Buckets,
751 const unsigned char *Base,
752 unsigned &NumStatHits,
753 unsigned &NumStatMisses)
754 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
755 Cache = CacheTy::Create(Buckets, Base);
756 }
757
758 ~PCHStatCache() { delete Cache; }
759
760 int stat(const char *path, struct stat *buf) {
761 // Do the lookup for the file's data in the PCH file.
762 CacheTy::iterator I = Cache->find(path);
763
764 // If we don't get a hit in the PCH file just forward to 'stat'.
765 if (I == Cache->end()) {
766 ++NumStatMisses;
767 return StatSysCallCache::stat(path, buf);
768 }
769
770 ++NumStatHits;
771 PCHStatData Data = *I;
772
773 if (!Data.hasStat)
774 return 1;
775
776 buf->st_ino = Data.ino;
777 buf->st_dev = Data.dev;
778 buf->st_mtime = Data.mtime;
779 buf->st_mode = Data.mode;
780 buf->st_size = Data.size;
781 return 0;
782 }
783};
784} // end anonymous namespace
785
786
787/// \brief Read the source manager block
788PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
789 using namespace SrcMgr;
790
791 // Set the source-location entry cursor to the current position in
792 // the stream. This cursor will be used to read the contents of the
793 // source manager block initially, and then lazily read
794 // source-location entries as needed.
795 SLocEntryCursor = Stream;
796
797 // The stream itself is going to skip over the source manager block.
798 if (Stream.SkipBlock()) {
799 Error("malformed block record in PCH file");
800 return Failure;
801 }
802
803 // Enter the source manager block.
804 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
805 Error("malformed source manager block record in PCH file");
806 return Failure;
807 }
808
809 RecordData Record;
810 while (true) {
811 unsigned Code = SLocEntryCursor.ReadCode();
812 if (Code == llvm::bitc::END_BLOCK) {
813 if (SLocEntryCursor.ReadBlockEnd()) {
814 Error("error at end of Source Manager block in PCH file");
815 return Failure;
816 }
817 return Success;
818 }
819
820 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
821 // No known subblocks, always skip them.
822 SLocEntryCursor.ReadSubBlockID();
823 if (SLocEntryCursor.SkipBlock()) {
824 Error("malformed block record in PCH file");
825 return Failure;
826 }
827 continue;
828 }
829
830 if (Code == llvm::bitc::DEFINE_ABBREV) {
831 SLocEntryCursor.ReadAbbrevRecord();
832 continue;
833 }
834
835 // Read a record.
836 const char *BlobStart;
837 unsigned BlobLen;
838 Record.clear();
839 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
840 default: // Default behavior: ignore.
841 break;
842
843 case pch::SM_LINE_TABLE:
844 if (ParseLineTable(Record))
845 return Failure;
846 break;
847
848 case pch::SM_HEADER_FILE_INFO: {
849 HeaderFileInfo HFI;
850 HFI.isImport = Record[0];
851 HFI.DirInfo = Record[1];
852 HFI.NumIncludes = Record[2];
853 HFI.ControllingMacroID = Record[3];
854 if (Listener)
855 Listener->ReadHeaderFileInfo(HFI);
856 break;
857 }
858
859 case pch::SM_SLOC_FILE_ENTRY:
860 case pch::SM_SLOC_BUFFER_ENTRY:
861 case pch::SM_SLOC_INSTANTIATION_ENTRY:
862 // Once we hit one of the source location entries, we're done.
863 return Success;
864 }
865 }
866}
867
868/// \brief Read in the source location entry with the given ID.
869PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
870 if (ID == 0)
871 return Success;
872
873 if (ID > TotalNumSLocEntries) {
874 Error("source location entry ID out-of-range for PCH file");
875 return Failure;
876 }
877
878 ++NumSLocEntriesRead;
879 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
880 unsigned Code = SLocEntryCursor.ReadCode();
881 if (Code == llvm::bitc::END_BLOCK ||
882 Code == llvm::bitc::ENTER_SUBBLOCK ||
883 Code == llvm::bitc::DEFINE_ABBREV) {
884 Error("incorrectly-formatted source location entry in PCH file");
885 return Failure;
886 }
887
888 RecordData Record;
889 const char *BlobStart;
890 unsigned BlobLen;
891 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
892 default:
893 Error("incorrectly-formatted source location entry in PCH file");
894 return Failure;
895
896 case pch::SM_SLOC_FILE_ENTRY: {
897 std::string Filename(BlobStart, BlobStart + BlobLen);
898 MaybeAddSystemRootToFilename(Filename);
899 const FileEntry *File = FileMgr.getFile(Filename);
900 if (File == 0) {
901 std::string ErrorStr = "could not find file '";
902 ErrorStr += Filename;
903 ErrorStr += "' referenced by PCH file";
904 Error(ErrorStr.c_str());
905 return Failure;
906 }
907
908 FileID FID = SourceMgr.createFileID(File,
909 SourceLocation::getFromRawEncoding(Record[1]),
910 (SrcMgr::CharacteristicKind)Record[2],
911 ID, Record[0]);
912 if (Record[3])
913 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
914 .setHasLineDirectives();
915
916 break;
917 }
918
919 case pch::SM_SLOC_BUFFER_ENTRY: {
920 const char *Name = BlobStart;
921 unsigned Offset = Record[0];
922 unsigned Code = SLocEntryCursor.ReadCode();
923 Record.clear();
924 unsigned RecCode
925 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
926 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
927 (void)RecCode;
928 llvm::MemoryBuffer *Buffer
929 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
930 BlobStart + BlobLen - 1,
931 Name);
932 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
933
934 if (strcmp(Name, "<built-in>") == 0) {
935 PCHPredefinesBufferID = BufferID;
936 PCHPredefines = BlobStart;
937 PCHPredefinesLen = BlobLen - 1;
938 }
939
940 break;
941 }
942
943 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
944 SourceLocation SpellingLoc
945 = SourceLocation::getFromRawEncoding(Record[1]);
946 SourceMgr.createInstantiationLoc(SpellingLoc,
947 SourceLocation::getFromRawEncoding(Record[2]),
948 SourceLocation::getFromRawEncoding(Record[3]),
949 Record[4],
950 ID,
951 Record[0]);
952 break;
953 }
954 }
955
956 return Success;
957}
958
959/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
960/// specified cursor. Read the abbreviations that are at the top of the block
961/// and then leave the cursor pointing into the block.
962bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
963 unsigned BlockID) {
964 if (Cursor.EnterSubBlock(BlockID)) {
965 Error("malformed block record in PCH file");
966 return Failure;
967 }
968
969 while (true) {
970 unsigned Code = Cursor.ReadCode();
971
972 // We expect all abbrevs to be at the start of the block.
973 if (Code != llvm::bitc::DEFINE_ABBREV)
974 return false;
975 Cursor.ReadAbbrevRecord();
976 }
977}
978
979void PCHReader::ReadMacroRecord(uint64_t Offset) {
980 assert(PP && "Forgot to set Preprocessor ?");
981
982 // Keep track of where we are in the stream, then jump back there
983 // after reading this macro.
984 SavedStreamPosition SavedPosition(Stream);
985
986 Stream.JumpToBit(Offset);
987 RecordData Record;
988 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
989 MacroInfo *Macro = 0;
990
991 while (true) {
992 unsigned Code = Stream.ReadCode();
993 switch (Code) {
994 case llvm::bitc::END_BLOCK:
995 return;
996
997 case llvm::bitc::ENTER_SUBBLOCK:
998 // No known subblocks, always skip them.
999 Stream.ReadSubBlockID();
1000 if (Stream.SkipBlock()) {
1001 Error("malformed block record in PCH file");
1002 return;
1003 }
1004 continue;
1005
1006 case llvm::bitc::DEFINE_ABBREV:
1007 Stream.ReadAbbrevRecord();
1008 continue;
1009 default: break;
1010 }
1011
1012 // Read a record.
1013 Record.clear();
1014 pch::PreprocessorRecordTypes RecType =
1015 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1016 switch (RecType) {
1017 case pch::PP_MACRO_OBJECT_LIKE:
1018 case pch::PP_MACRO_FUNCTION_LIKE: {
1019 // If we already have a macro, that means that we've hit the end
1020 // of the definition of the macro we were looking for. We're
1021 // done.
1022 if (Macro)
1023 return;
1024
1025 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1026 if (II == 0) {
1027 Error("macro must have a name in PCH file");
1028 return;
1029 }
1030 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1031 bool isUsed = Record[2];
1032
1033 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1034 MI->setIsUsed(isUsed);
1035
1036 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1037 // Decode function-like macro info.
1038 bool isC99VarArgs = Record[3];
1039 bool isGNUVarArgs = Record[4];
1040 MacroArgs.clear();
1041 unsigned NumArgs = Record[5];
1042 for (unsigned i = 0; i != NumArgs; ++i)
1043 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1044
1045 // Install function-like macro info.
1046 MI->setIsFunctionLike();
1047 if (isC99VarArgs) MI->setIsC99Varargs();
1048 if (isGNUVarArgs) MI->setIsGNUVarargs();
1049 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1050 PP->getPreprocessorAllocator());
1051 }
1052
1053 // Finally, install the macro.
1054 PP->setMacroInfo(II, MI);
1055
1056 // Remember that we saw this macro last so that we add the tokens that
1057 // form its body to it.
1058 Macro = MI;
1059 ++NumMacrosRead;
1060 break;
1061 }
1062
1063 case pch::PP_TOKEN: {
1064 // If we see a TOKEN before a PP_MACRO_*, then the file is
1065 // erroneous, just pretend we didn't see this.
1066 if (Macro == 0) break;
1067
1068 Token Tok;
1069 Tok.startToken();
1070 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1071 Tok.setLength(Record[1]);
1072 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1073 Tok.setIdentifierInfo(II);
1074 Tok.setKind((tok::TokenKind)Record[3]);
1075 Tok.setFlag((Token::TokenFlags)Record[4]);
1076 Macro->AddTokenToBody(Tok);
1077 break;
1078 }
1079 }
1080 }
1081}
1082
1083void PCHReader::ReadDefinedMacros() {
1084 // If there was no preprocessor block, do nothing.
1085 if (!MacroCursor.getBitStreamReader())
1086 return;
1087
1088 llvm::BitstreamCursor Cursor = MacroCursor;
1089 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1090 Error("malformed preprocessor block record in PCH file");
1091 return;
1092 }
1093
1094 RecordData Record;
1095 while (true) {
1096 unsigned Code = Cursor.ReadCode();
1097 if (Code == llvm::bitc::END_BLOCK) {
1098 if (Cursor.ReadBlockEnd())
1099 Error("error at end of preprocessor block in PCH file");
1100 return;
1101 }
1102
1103 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1104 // No known subblocks, always skip them.
1105 Cursor.ReadSubBlockID();
1106 if (Cursor.SkipBlock()) {
1107 Error("malformed block record in PCH file");
1108 return;
1109 }
1110 continue;
1111 }
1112
1113 if (Code == llvm::bitc::DEFINE_ABBREV) {
1114 Cursor.ReadAbbrevRecord();
1115 continue;
1116 }
1117
1118 // Read a record.
1119 const char *BlobStart;
1120 unsigned BlobLen;
1121 Record.clear();
1122 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1123 default: // Default behavior: ignore.
1124 break;
1125
1126 case pch::PP_MACRO_OBJECT_LIKE:
1127 case pch::PP_MACRO_FUNCTION_LIKE:
1128 DecodeIdentifierInfo(Record[0]);
1129 break;
1130
1131 case pch::PP_TOKEN:
1132 // Ignore tokens.
1133 break;
1134 }
1135 }
1136}
1137
1138/// \brief If we are loading a relocatable PCH file, and the filename is
1139/// not an absolute path, add the system root to the beginning of the file
1140/// name.
1141void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1142 // If this is not a relocatable PCH file, there's nothing to do.
1143 if (!RelocatablePCH)
1144 return;
1145
1146 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
1147 return;
1148
1149 if (isysroot == 0) {
1150 // If no system root was given, default to '/'
1151 Filename.insert(Filename.begin(), '/');
1152 return;
1153 }
1154
1155 unsigned Length = strlen(isysroot);
1156 if (isysroot[Length - 1] != '/')
1157 Filename.insert(Filename.begin(), '/');
1158
1159 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1160}
1161
1162PCHReader::PCHReadResult
1163PCHReader::ReadPCHBlock() {
1164 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1165 Error("malformed block record in PCH file");
1166 return Failure;
1167 }
1168
1169 // Read all of the records and blocks for the PCH file.
1170 RecordData Record;
1171 while (!Stream.AtEndOfStream()) {
1172 unsigned Code = Stream.ReadCode();
1173 if (Code == llvm::bitc::END_BLOCK) {
1174 if (Stream.ReadBlockEnd()) {
1175 Error("error at end of module block in PCH file");
1176 return Failure;
1177 }
1178
1179 return Success;
1180 }
1181
1182 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1183 switch (Stream.ReadSubBlockID()) {
1184 case pch::DECLTYPES_BLOCK_ID:
1185 // We lazily load the decls block, but we want to set up the
1186 // DeclsCursor cursor to point into it. Clone our current bitcode
1187 // cursor to it, enter the block and read the abbrevs in that block.
1188 // With the main cursor, we just skip over it.
1189 DeclsCursor = Stream;
1190 if (Stream.SkipBlock() || // Skip with the main cursor.
1191 // Read the abbrevs.
1192 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
1193 Error("malformed block record in PCH file");
1194 return Failure;
1195 }
1196 break;
1197
1198 case pch::PREPROCESSOR_BLOCK_ID:
1199 MacroCursor = Stream;
1200 if (PP)
1201 PP->setExternalSource(this);
1202
1203 if (Stream.SkipBlock()) {
1204 Error("malformed block record in PCH file");
1205 return Failure;
1206 }
1207 break;
1208
1209 case pch::SOURCE_MANAGER_BLOCK_ID:
1210 switch (ReadSourceManagerBlock()) {
1211 case Success:
1212 break;
1213
1214 case Failure:
1215 Error("malformed source manager block in PCH file");
1216 return Failure;
1217
1218 case IgnorePCH:
1219 return IgnorePCH;
1220 }
1221 break;
1222 }
1223 continue;
1224 }
1225
1226 if (Code == llvm::bitc::DEFINE_ABBREV) {
1227 Stream.ReadAbbrevRecord();
1228 continue;
1229 }
1230
1231 // Read and process a record.
1232 Record.clear();
1233 const char *BlobStart = 0;
1234 unsigned BlobLen = 0;
1235 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1236 &BlobStart, &BlobLen)) {
1237 default: // Default behavior: ignore.
1238 break;
1239
1240 case pch::TYPE_OFFSET:
1241 if (!TypesLoaded.empty()) {
1242 Error("duplicate TYPE_OFFSET record in PCH file");
1243 return Failure;
1244 }
1245 TypeOffsets = (const uint32_t *)BlobStart;
1246 TypesLoaded.resize(Record[0]);
1247 break;
1248
1249 case pch::DECL_OFFSET:
1250 if (!DeclsLoaded.empty()) {
1251 Error("duplicate DECL_OFFSET record in PCH file");
1252 return Failure;
1253 }
1254 DeclOffsets = (const uint32_t *)BlobStart;
1255 DeclsLoaded.resize(Record[0]);
1256 break;
1257
1258 case pch::LANGUAGE_OPTIONS:
1259 if (ParseLanguageOptions(Record))
1260 return IgnorePCH;
1261 break;
1262
1263 case pch::METADATA: {
1264 if (Record[0] != pch::VERSION_MAJOR) {
1265 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1266 : diag::warn_pch_version_too_new);
1267 return IgnorePCH;
1268 }
1269
1270 RelocatablePCH = Record[4];
1271 if (Listener) {
1272 std::string TargetTriple(BlobStart, BlobLen);
1273 if (Listener->ReadTargetTriple(TargetTriple))
1274 return IgnorePCH;
1275 }
1276 break;
1277 }
1278
1279 case pch::IDENTIFIER_TABLE:
1280 IdentifierTableData = BlobStart;
1281 if (Record[0]) {
1282 IdentifierLookupTable
1283 = PCHIdentifierLookupTable::Create(
1284 (const unsigned char *)IdentifierTableData + Record[0],
1285 (const unsigned char *)IdentifierTableData,
1286 PCHIdentifierLookupTrait(*this));
1287 if (PP)
1288 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1289 }
1290 break;
1291
1292 case pch::IDENTIFIER_OFFSET:
1293 if (!IdentifiersLoaded.empty()) {
1294 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
1295 return Failure;
1296 }
1297 IdentifierOffsets = (const uint32_t *)BlobStart;
1298 IdentifiersLoaded.resize(Record[0]);
1299 if (PP)
1300 PP->getHeaderSearchInfo().SetExternalLookup(this);
1301 break;
1302
1303 case pch::EXTERNAL_DEFINITIONS:
1304 if (!ExternalDefinitions.empty()) {
1305 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
1306 return Failure;
1307 }
1308 ExternalDefinitions.swap(Record);
1309 break;
1310
1311 case pch::SPECIAL_TYPES:
1312 SpecialTypes.swap(Record);
1313 break;
1314
1315 case pch::STATISTICS:
1316 TotalNumStatements = Record[0];
1317 TotalNumMacros = Record[1];
1318 TotalLexicalDeclContexts = Record[2];
1319 TotalVisibleDeclContexts = Record[3];
1320 break;
1321
1322 case pch::TENTATIVE_DEFINITIONS:
1323 if (!TentativeDefinitions.empty()) {
1324 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
1325 return Failure;
1326 }
1327 TentativeDefinitions.swap(Record);
1328 break;
1329
1330 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1331 if (!LocallyScopedExternalDecls.empty()) {
1332 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1333 return Failure;
1334 }
1335 LocallyScopedExternalDecls.swap(Record);
1336 break;
1337
1338 case pch::SELECTOR_OFFSETS:
1339 SelectorOffsets = (const uint32_t *)BlobStart;
1340 TotalNumSelectors = Record[0];
1341 SelectorsLoaded.resize(TotalNumSelectors);
1342 break;
1343
1344 case pch::METHOD_POOL:
1345 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1346 if (Record[0])
1347 MethodPoolLookupTable
1348 = PCHMethodPoolLookupTable::Create(
1349 MethodPoolLookupTableData + Record[0],
1350 MethodPoolLookupTableData,
1351 PCHMethodPoolLookupTrait(*this));
1352 TotalSelectorsInMethodPool = Record[1];
1353 break;
1354
1355 case pch::PP_COUNTER_VALUE:
1356 if (!Record.empty() && Listener)
1357 Listener->ReadCounter(Record[0]);
1358 break;
1359
1360 case pch::SOURCE_LOCATION_OFFSETS:
1361 SLocOffsets = (const uint32_t *)BlobStart;
1362 TotalNumSLocEntries = Record[0];
1363 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
1364 break;
1365
1366 case pch::SOURCE_LOCATION_PRELOADS:
1367 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1368 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1369 if (Result != Success)
1370 return Result;
1371 }
1372 break;
1373
1374 case pch::STAT_CACHE: {
1375 PCHStatCache *MyStatCache =
1376 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1377 (const unsigned char *)BlobStart,
1378 NumStatHits, NumStatMisses);
1379 FileMgr.addStatCache(MyStatCache);
1380 StatCache = MyStatCache;
1381 break;
1382 }
1383
1384 case pch::EXT_VECTOR_DECLS:
1385 if (!ExtVectorDecls.empty()) {
1386 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
1387 return Failure;
1388 }
1389 ExtVectorDecls.swap(Record);
1390 break;
1391
1392 case pch::ORIGINAL_FILE_NAME:
1393 ActualOriginalFileName.assign(BlobStart, BlobLen);
1394 OriginalFileName = ActualOriginalFileName;
1395 MaybeAddSystemRootToFilename(OriginalFileName);
1396 break;
1397
1398 case pch::COMMENT_RANGES:
1399 Comments = (SourceRange *)BlobStart;
1400 NumComments = BlobLen / sizeof(SourceRange);
1401 break;
1402
1403 case pch::VERSION_CONTROL_BRANCH_REVISION: {
1404 llvm::StringRef CurBranch = getClangFullRepositoryVersion();
1405 llvm::StringRef PCHBranch(BlobStart, BlobLen);
1406 if (CurBranch != PCHBranch) {
1407 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1408 return IgnorePCH;
1409 }
1410 break;
1411 }
1412 }
1413 }
1414 Error("premature end of bitstream in PCH file");
1415 return Failure;
1416}
1417
1418PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
1419 // Set the PCH file name.
1420 this->FileName = FileName;
1421
1422 // Open the PCH file.
1423 //
1424 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1425 std::string ErrStr;
1426 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1427 if (!Buffer) {
1428 Error(ErrStr.c_str());
1429 return IgnorePCH;
1430 }
1431
1432 // Initialize the stream
1433 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1434 (const unsigned char *)Buffer->getBufferEnd());
1435 Stream.init(StreamFile);
1436
1437 // Sniff for the signature.
1438 if (Stream.Read(8) != 'C' ||
1439 Stream.Read(8) != 'P' ||
1440 Stream.Read(8) != 'C' ||
1441 Stream.Read(8) != 'H') {
1442 Diag(diag::err_not_a_pch_file) << FileName;
1443 return Failure;
1444 }
1445
1446 while (!Stream.AtEndOfStream()) {
1447 unsigned Code = Stream.ReadCode();
1448
1449 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1450 Error("invalid record at top-level of PCH file");
1451 return Failure;
1452 }
1453
1454 unsigned BlockID = Stream.ReadSubBlockID();
1455
1456 // We only know the PCH subblock ID.
1457 switch (BlockID) {
1458 case llvm::bitc::BLOCKINFO_BLOCK_ID:
1459 if (Stream.ReadBlockInfoBlock()) {
1460 Error("malformed BlockInfoBlock in PCH file");
1461 return Failure;
1462 }
1463 break;
1464 case pch::PCH_BLOCK_ID:
1465 switch (ReadPCHBlock()) {
1466 case Success:
1467 break;
1468
1469 case Failure:
1470 return Failure;
1471
1472 case IgnorePCH:
1473 // FIXME: We could consider reading through to the end of this
1474 // PCH block, skipping subblocks, to see if there are other
1475 // PCH blocks elsewhere.
1476
1477 // Clear out any preallocated source location entries, so that
1478 // the source manager does not try to resolve them later.
1479 SourceMgr.ClearPreallocatedSLocEntries();
1480
1481 // Remove the stat cache.
1482 if (StatCache)
1483 FileMgr.removeStatCache((PCHStatCache*)StatCache);
1484
1485 return IgnorePCH;
1486 }
1487 break;
1488 default:
1489 if (Stream.SkipBlock()) {
1490 Error("malformed block record in PCH file");
1491 return Failure;
1492 }
1493 break;
1494 }
1495 }
1496
1497 // Check the predefines buffer.
1498 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
1499 PCHPredefinesBufferID))
1500 return IgnorePCH;
1501
1502 if (PP) {
1503 // Initialization of keywords and pragmas occurs before the
1504 // PCH file is read, so there may be some identifiers that were
1505 // loaded into the IdentifierTable before we intercepted the
1506 // creation of identifiers. Iterate through the list of known
1507 // identifiers and determine whether we have to establish
1508 // preprocessor definitions or top-level identifier declaration
1509 // chains for those identifiers.
1510 //
1511 // We copy the IdentifierInfo pointers to a small vector first,
1512 // since de-serializing declarations or macro definitions can add
1513 // new entries into the identifier table, invalidating the
1514 // iterators.
1515 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1516 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1517 IdEnd = PP->getIdentifierTable().end();
1518 Id != IdEnd; ++Id)
1519 Identifiers.push_back(Id->second);
1520 PCHIdentifierLookupTable *IdTable
1521 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1522 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1523 IdentifierInfo *II = Identifiers[I];
1524 // Look in the on-disk hash table for an entry for
1525 PCHIdentifierLookupTrait Info(*this, II);
1526 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
1527 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1528 if (Pos == IdTable->end())
1529 continue;
1530
1531 // Dereferencing the iterator has the effect of populating the
1532 // IdentifierInfo node with the various declarations it needs.
1533 (void)*Pos;
1534 }
1535 }
1536
1537 if (Context)
1538 InitializeContext(*Context);
1539
1540 return Success;
1541}
1542
1543void PCHReader::InitializeContext(ASTContext &Ctx) {
1544 Context = &Ctx;
1545 assert(Context && "Passed null context!");
1546
1547 assert(PP && "Forgot to set Preprocessor ?");
1548 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1549 PP->getHeaderSearchInfo().SetExternalLookup(this);
1550 PP->setExternalSource(this);
1551
1552 // Load the translation unit declaration
1553 ReadDeclRecord(DeclOffsets[0], 0);
1554
1555 // Load the special types.
1556 Context->setBuiltinVaListType(
1557 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1558 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1559 Context->setObjCIdType(GetType(Id));
1560 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1561 Context->setObjCSelType(GetType(Sel));
1562 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1563 Context->setObjCProtoType(GetType(Proto));
1564 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1565 Context->setObjCClassType(GetType(Class));
1566
1567 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1568 Context->setCFConstantStringType(GetType(String));
1569 if (unsigned FastEnum
1570 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1571 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1572 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1573 QualType FileType = GetType(File);
1574 assert(!FileType.isNull() && "FILE type is NULL");
1575 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
1576 Context->setFILEDecl(Typedef->getDecl());
1577 else {
1578 const TagType *Tag = FileType->getAs<TagType>();
1579 assert(Tag && "Invalid FILE type in PCH file");
1580 Context->setFILEDecl(Tag->getDecl());
1581 }
1582 }
1583 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1584 QualType Jmp_bufType = GetType(Jmp_buf);
1585 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
1586 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
1587 Context->setjmp_bufDecl(Typedef->getDecl());
1588 else {
1589 const TagType *Tag = Jmp_bufType->getAs<TagType>();
1590 assert(Tag && "Invalid jmp_bug type in PCH file");
1591 Context->setjmp_bufDecl(Tag->getDecl());
1592 }
1593 }
1594 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1595 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1596 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
1597 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
1598 Context->setsigjmp_bufDecl(Typedef->getDecl());
1599 else {
1600 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
1601 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1602 Context->setsigjmp_bufDecl(Tag->getDecl());
1603 }
1604 }
1605 if (unsigned ObjCIdRedef
1606 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1607 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
1608 if (unsigned ObjCClassRedef
1609 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1610 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
1611#if 0
1612 // FIXME. Accommodate for this in several PCH/Index tests
1613 if (unsigned ObjCSelRedef
1614 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1615 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1616#endif
1617 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1618 Context->setBlockDescriptorType(GetType(String));
1619 if (unsigned String
1620 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1621 Context->setBlockDescriptorExtendedType(GetType(String));
1622}
1623
1624/// \brief Retrieve the name of the original source file name
1625/// directly from the PCH file, without actually loading the PCH
1626/// file.
1627std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1628 Diagnostic &Diags) {
1629 // Open the PCH file.
1630 std::string ErrStr;
1631 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1632 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1633 if (!Buffer) {
1634 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
1635 return std::string();
1636 }
1637
1638 // Initialize the stream
1639 llvm::BitstreamReader StreamFile;
1640 llvm::BitstreamCursor Stream;
1641 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1642 (const unsigned char *)Buffer->getBufferEnd());
1643 Stream.init(StreamFile);
1644
1645 // Sniff for the signature.
1646 if (Stream.Read(8) != 'C' ||
1647 Stream.Read(8) != 'P' ||
1648 Stream.Read(8) != 'C' ||
1649 Stream.Read(8) != 'H') {
1650 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
1651 return std::string();
1652 }
1653
1654 RecordData Record;
1655 while (!Stream.AtEndOfStream()) {
1656 unsigned Code = Stream.ReadCode();
1657
1658 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1659 unsigned BlockID = Stream.ReadSubBlockID();
1660
1661 // We only know the PCH subblock ID.
1662 switch (BlockID) {
1663 case pch::PCH_BLOCK_ID:
1664 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1665 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
1666 return std::string();
1667 }
1668 break;
1669
1670 default:
1671 if (Stream.SkipBlock()) {
1672 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
1673 return std::string();
1674 }
1675 break;
1676 }
1677 continue;
1678 }
1679
1680 if (Code == llvm::bitc::END_BLOCK) {
1681 if (Stream.ReadBlockEnd()) {
1682 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
1683 return std::string();
1684 }
1685 continue;
1686 }
1687
1688 if (Code == llvm::bitc::DEFINE_ABBREV) {
1689 Stream.ReadAbbrevRecord();
1690 continue;
1691 }
1692
1693 Record.clear();
1694 const char *BlobStart = 0;
1695 unsigned BlobLen = 0;
1696 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1697 == pch::ORIGINAL_FILE_NAME)
1698 return std::string(BlobStart, BlobLen);
1699 }
1700
1701 return std::string();
1702}
1703
1704/// \brief Parse the record that corresponds to a LangOptions data
1705/// structure.
1706///
1707/// This routine compares the language options used to generate the
1708/// PCH file against the language options set for the current
1709/// compilation. For each option, we classify differences between the
1710/// two compiler states as either "benign" or "important". Benign
1711/// differences don't matter, and we accept them without complaint
1712/// (and without modifying the language options). Differences between
1713/// the states for important options cause the PCH file to be
1714/// unusable, so we emit a warning and return true to indicate that
1715/// there was an error.
1716///
1717/// \returns true if the PCH file is unacceptable, false otherwise.
1718bool PCHReader::ParseLanguageOptions(
1719 const llvm::SmallVectorImpl<uint64_t> &Record) {
1720 if (Listener) {
1721 LangOptions LangOpts;
1722
1723 #define PARSE_LANGOPT(Option) \
1724 LangOpts.Option = Record[Idx]; \
1725 ++Idx
1726
1727 unsigned Idx = 0;
1728 PARSE_LANGOPT(Trigraphs);
1729 PARSE_LANGOPT(BCPLComment);
1730 PARSE_LANGOPT(DollarIdents);
1731 PARSE_LANGOPT(AsmPreprocessor);
1732 PARSE_LANGOPT(GNUMode);
1733 PARSE_LANGOPT(ImplicitInt);
1734 PARSE_LANGOPT(Digraphs);
1735 PARSE_LANGOPT(HexFloats);
1736 PARSE_LANGOPT(C99);
1737 PARSE_LANGOPT(Microsoft);
1738 PARSE_LANGOPT(CPlusPlus);
1739 PARSE_LANGOPT(CPlusPlus0x);
1740 PARSE_LANGOPT(CXXOperatorNames);
1741 PARSE_LANGOPT(ObjC1);
1742 PARSE_LANGOPT(ObjC2);
1743 PARSE_LANGOPT(ObjCNonFragileABI);
1744 PARSE_LANGOPT(ObjCNonFragileABI2);
1745 PARSE_LANGOPT(PascalStrings);
1746 PARSE_LANGOPT(WritableStrings);
1747 PARSE_LANGOPT(LaxVectorConversions);
1748 PARSE_LANGOPT(AltiVec);
1749 PARSE_LANGOPT(Exceptions);
1750 PARSE_LANGOPT(NeXTRuntime);
1751 PARSE_LANGOPT(Freestanding);
1752 PARSE_LANGOPT(NoBuiltin);
1753 PARSE_LANGOPT(ThreadsafeStatics);
1754 PARSE_LANGOPT(POSIXThreads);
1755 PARSE_LANGOPT(Blocks);
1756 PARSE_LANGOPT(EmitAllDecls);
1757 PARSE_LANGOPT(MathErrno);
1758 PARSE_LANGOPT(OverflowChecking);
1759 PARSE_LANGOPT(HeinousExtensions);
1760 PARSE_LANGOPT(Optimize);
1761 PARSE_LANGOPT(OptimizeSize);
1762 PARSE_LANGOPT(Static);
1763 PARSE_LANGOPT(PICLevel);
1764 PARSE_LANGOPT(GNUInline);
1765 PARSE_LANGOPT(NoInline);
1766 PARSE_LANGOPT(AccessControl);
1767 PARSE_LANGOPT(CharIsSigned);
1768 PARSE_LANGOPT(ShortWChar);
1769 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1770 ++Idx;
1771 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1772 ++Idx;
1773 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1774 Record[Idx]);
1775 ++Idx;
1776 PARSE_LANGOPT(InstantiationDepth);
1777 PARSE_LANGOPT(OpenCL);
1778 PARSE_LANGOPT(CatchUndefined);
1779 // FIXME: Missing ElideConstructors?!
1780 #undef PARSE_LANGOPT
1781
1782 return Listener->ReadLanguageOptions(LangOpts);
1783 }
1784
1785 return false;
1786}
1787
1788void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1789 Comments.resize(NumComments);
1790 std::copy(this->Comments, this->Comments + NumComments,
1791 Comments.begin());
1792}
1793
1794/// \brief Read and return the type at the given offset.
1795///
1796/// This routine actually reads the record corresponding to the type
1797/// at the given offset in the bitstream. It is a helper routine for
1798/// GetType, which deals with reading type IDs.
1799QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
1800 // Keep track of where we are in the stream, then jump back there
1801 // after reading this type.
1802 SavedStreamPosition SavedPosition(DeclsCursor);
1803
1804 // Note that we are loading a type record.
1805 LoadingTypeOrDecl Loading(*this);
1806
1807 DeclsCursor.JumpToBit(Offset);
1808 RecordData Record;
1809 unsigned Code = DeclsCursor.ReadCode();
1810 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
1811 case pch::TYPE_EXT_QUAL: {
1812 assert(Record.size() == 2 &&
1813 "Incorrect encoding of extended qualifier type");
1814 QualType Base = GetType(Record[0]);
1815 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1816 return Context->getQualifiedType(Base, Quals);
1817 }
1818
1819 case pch::TYPE_COMPLEX: {
1820 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1821 QualType ElemType = GetType(Record[0]);
1822 return Context->getComplexType(ElemType);
1823 }
1824
1825 case pch::TYPE_POINTER: {
1826 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1827 QualType PointeeType = GetType(Record[0]);
1828 return Context->getPointerType(PointeeType);
1829 }
1830
1831 case pch::TYPE_BLOCK_POINTER: {
1832 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1833 QualType PointeeType = GetType(Record[0]);
1834 return Context->getBlockPointerType(PointeeType);
1835 }
1836
1837 case pch::TYPE_LVALUE_REFERENCE: {
1838 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1839 QualType PointeeType = GetType(Record[0]);
1840 return Context->getLValueReferenceType(PointeeType);
1841 }
1842
1843 case pch::TYPE_RVALUE_REFERENCE: {
1844 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1845 QualType PointeeType = GetType(Record[0]);
1846 return Context->getRValueReferenceType(PointeeType);
1847 }
1848
1849 case pch::TYPE_MEMBER_POINTER: {
1850 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1851 QualType PointeeType = GetType(Record[0]);
1852 QualType ClassType = GetType(Record[1]);
1853 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
1854 }
1855
1856 case pch::TYPE_CONSTANT_ARRAY: {
1857 QualType ElementType = GetType(Record[0]);
1858 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1859 unsigned IndexTypeQuals = Record[2];
1860 unsigned Idx = 3;
1861 llvm::APInt Size = ReadAPInt(Record, Idx);
1862 return Context->getConstantArrayType(ElementType, Size,
1863 ASM, IndexTypeQuals);
1864 }
1865
1866 case pch::TYPE_INCOMPLETE_ARRAY: {
1867 QualType ElementType = GetType(Record[0]);
1868 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1869 unsigned IndexTypeQuals = Record[2];
1870 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1871 }
1872
1873 case pch::TYPE_VARIABLE_ARRAY: {
1874 QualType ElementType = GetType(Record[0]);
1875 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1876 unsigned IndexTypeQuals = Record[2];
1877 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1878 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1879 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1880 ASM, IndexTypeQuals,
1881 SourceRange(LBLoc, RBLoc));
1882 }
1883
1884 case pch::TYPE_VECTOR: {
1885 if (Record.size() != 4) {
1886 Error("incorrect encoding of vector type in PCH file");
1887 return QualType();
1888 }
1889
1890 QualType ElementType = GetType(Record[0]);
1891 unsigned NumElements = Record[1];
1892 bool AltiVec = Record[2];
1893 bool Pixel = Record[3];
1894 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
1895 }
1896
1897 case pch::TYPE_EXT_VECTOR: {
1898 if (Record.size() != 4) {
1899 Error("incorrect encoding of extended vector type in PCH file");
1900 return QualType();
1901 }
1902
1903 QualType ElementType = GetType(Record[0]);
1904 unsigned NumElements = Record[1];
1905 return Context->getExtVectorType(ElementType, NumElements);
1906 }
1907
1908 case pch::TYPE_FUNCTION_NO_PROTO: {
1909 if (Record.size() != 3) {
1910 Error("incorrect encoding of no-proto function type");
1911 return QualType();
1912 }
1913 QualType ResultType = GetType(Record[0]);
1914 return Context->getFunctionNoProtoType(ResultType, Record[1],
1915 (CallingConv)Record[2]);
1916 }
1917
1918 case pch::TYPE_FUNCTION_PROTO: {
1919 QualType ResultType = GetType(Record[0]);
1920 bool NoReturn = Record[1];
1921 CallingConv CallConv = (CallingConv)Record[2];
1922 unsigned Idx = 3;
1923 unsigned NumParams = Record[Idx++];
1924 llvm::SmallVector<QualType, 16> ParamTypes;
1925 for (unsigned I = 0; I != NumParams; ++I)
1926 ParamTypes.push_back(GetType(Record[Idx++]));
1927 bool isVariadic = Record[Idx++];
1928 unsigned Quals = Record[Idx++];
1929 bool hasExceptionSpec = Record[Idx++];
1930 bool hasAnyExceptionSpec = Record[Idx++];
1931 unsigned NumExceptions = Record[Idx++];
1932 llvm::SmallVector<QualType, 2> Exceptions;
1933 for (unsigned I = 0; I != NumExceptions; ++I)
1934 Exceptions.push_back(GetType(Record[Idx++]));
1935 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
1936 isVariadic, Quals, hasExceptionSpec,
1937 hasAnyExceptionSpec, NumExceptions,
1938 Exceptions.data(), NoReturn, CallConv);
1939 }
1940
1941 case pch::TYPE_UNRESOLVED_USING:
1942 return Context->getTypeDeclType(
1943 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1944
1945 case pch::TYPE_TYPEDEF:
1946 assert(Record.size() == 1 && "incorrect encoding of typedef type");
1947 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1948
1949 case pch::TYPE_TYPEOF_EXPR:
1950 return Context->getTypeOfExprType(ReadTypeExpr());
1951
1952 case pch::TYPE_TYPEOF: {
1953 if (Record.size() != 1) {
1954 Error("incorrect encoding of typeof(type) in PCH file");
1955 return QualType();
1956 }
1957 QualType UnderlyingType = GetType(Record[0]);
1958 return Context->getTypeOfType(UnderlyingType);
1959 }
1960
1961 case pch::TYPE_DECLTYPE:
1962 return Context->getDecltypeType(ReadTypeExpr());
1963
1964 case pch::TYPE_RECORD:
1965 assert(Record.size() == 1 && "incorrect encoding of record type");
1966 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
1967
1968 case pch::TYPE_ENUM:
1969 assert(Record.size() == 1 && "incorrect encoding of enum type");
1970 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1971
1972 case pch::TYPE_ELABORATED: {
1973 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1974 unsigned Tag = Record[1];
1975 return Context->getElaboratedType(GetType(Record[0]),
1976 (ElaboratedType::TagKind) Tag);
1977 }
1978
1979 case pch::TYPE_OBJC_INTERFACE: {
1980 unsigned Idx = 0;
1981 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1982 unsigned NumProtos = Record[Idx++];
1983 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1984 for (unsigned I = 0; I != NumProtos; ++I)
1985 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1986 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
1987 }
1988
1989 case pch::TYPE_OBJC_OBJECT_POINTER: {
1990 unsigned Idx = 0;
1991 QualType OIT = GetType(Record[Idx++]);
1992 unsigned NumProtos = Record[Idx++];
1993 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1994 for (unsigned I = 0; I != NumProtos; ++I)
1995 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1996 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
1997 }
1998
1999 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2000 unsigned Idx = 0;
2001 QualType Parm = GetType(Record[Idx++]);
2002 QualType Replacement = GetType(Record[Idx++]);
2003 return
2004 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2005 Replacement);
2006 }
2007 }
2008 // Suppress a GCC warning
2009 return QualType();
2010}
2011
2012namespace {
2013
2014class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2015 PCHReader &Reader;
2016 const PCHReader::RecordData &Record;
2017 unsigned &Idx;
2018
2019public:
2020 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2021 unsigned &Idx)
2022 : Reader(Reader), Record(Record), Idx(Idx) { }
2023
2024 // We want compile-time assurance that we've enumerated all of
2025 // these, so unfortunately we have to declare them first, then
2026 // define them out-of-line.
2027#define ABSTRACT_TYPELOC(CLASS, PARENT)
2028#define TYPELOC(CLASS, PARENT) \
2029 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
2030#include "clang/AST/TypeLocNodes.def"
2031
2032 void VisitFunctionTypeLoc(FunctionTypeLoc);
2033 void VisitArrayTypeLoc(ArrayTypeLoc);
2034};
2035
2036}
2037
2038void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2039 // nothing to do
2040}
2041void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2042 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2043 if (TL.needsExtraLocalData()) {
2044 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2045 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2046 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2047 TL.setModeAttr(Record[Idx++]);
2048 }
2049}
2050void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2051 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2052}
2053void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2054 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2055}
2056void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2057 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2058}
2059void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2060 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2061}
2062void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2063 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2064}
2065void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2066 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
2068void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2069 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2071 if (Record[Idx++])
2072 TL.setSizeExpr(Reader.ReadDeclExpr());
2073 else
2074 TL.setSizeExpr(0);
2075}
2076void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2077 VisitArrayTypeLoc(TL);
2078}
2079void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2080 VisitArrayTypeLoc(TL);
2081}
2082void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2083 VisitArrayTypeLoc(TL);
2084}
2085void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2086 DependentSizedArrayTypeLoc TL) {
2087 VisitArrayTypeLoc(TL);
2088}
2089void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2090 DependentSizedExtVectorTypeLoc TL) {
2091 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092}
2093void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2094 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095}
2096void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2097 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098}
2099void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2100 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2102 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2103 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2104 }
2105}
2106void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2107 VisitFunctionTypeLoc(TL);
2108}
2109void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2110 VisitFunctionTypeLoc(TL);
2111}
2112void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2113 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2114}
2115void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2116 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2117}
2118void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2119 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2120 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2122}
2123void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2124 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2125 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2126 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
2128}
2129void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2130 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2131}
2132void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2133 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2134}
2135void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2136 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2137}
2138void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2139 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2140}
2141void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2142 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2143}
2144void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2145 SubstTemplateTypeParmTypeLoc TL) {
2146 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2147}
2148void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2149 TemplateSpecializationTypeLoc TL) {
2150 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2151 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2152 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2153 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2154 TL.setArgLocInfo(i,
2155 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2156 Record, Idx));
2157}
2158void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2159 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2160}
2161void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2162 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2163}
2164void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2165 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2166 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2167 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2168 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2169 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2170}
2171void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2172 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2173 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2174 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2175 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2176 TL.setHasProtocolsAsWritten(Record[Idx++]);
2177 if (TL.hasProtocolsAsWritten())
2178 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2179 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2180}
2181
2182TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
2183 unsigned &Idx) {
2184 QualType InfoTy = GetType(Record[Idx++]);
2185 if (InfoTy.isNull())
2186 return 0;
2187
2188 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
2189 TypeLocReader TLR(*this, Record, Idx);
2190 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2191 TLR.Visit(TL);
2192 return TInfo;
2193}
2194
2195QualType PCHReader::GetType(pch::TypeID ID) {
2196 unsigned FastQuals = ID & Qualifiers::FastMask;
2197 unsigned Index = ID >> Qualifiers::FastWidth;
2198
2199 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2200 QualType T;
2201 switch ((pch::PredefinedTypeIDs)Index) {
2202 case pch::PREDEF_TYPE_NULL_ID: return QualType();
2203 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2204 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
2205
2206 case pch::PREDEF_TYPE_CHAR_U_ID:
2207 case pch::PREDEF_TYPE_CHAR_S_ID:
2208 // FIXME: Check that the signedness of CharTy is correct!
2209 T = Context->CharTy;
2210 break;
2211
2212 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2213 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2214 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2215 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2216 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
2217 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
2218 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2219 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2220 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2221 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2222 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2223 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
2224 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
2225 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2226 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2227 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2228 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2229 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
2230 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
2231 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2232 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
2233 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2234 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
2235 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
2236 }
2237
2238 assert(!T.isNull() && "Unknown predefined type");
2239 return T.withFastQualifiers(FastQuals);
2240 }
2241
2242 Index -= pch::NUM_PREDEF_TYPE_IDS;
2243 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
2244 if (TypesLoaded[Index].isNull())
2245 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
2246
2247 return TypesLoaded[Index].withFastQualifiers(FastQuals);
2248}
2249
2250TemplateArgumentLocInfo
2251PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2252 const RecordData &Record,
2253 unsigned &Index) {
2254 switch (Kind) {
2255 case TemplateArgument::Expression:
2256 return ReadDeclExpr();
2257 case TemplateArgument::Type:
2258 return GetTypeSourceInfo(Record, Index);
2259 case TemplateArgument::Template: {
2260 SourceLocation
2261 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2262 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2263 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2264 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2265 TemplateNameLoc);
2266 }
2267 case TemplateArgument::Null:
2268 case TemplateArgument::Integral:
2269 case TemplateArgument::Declaration:
2270 case TemplateArgument::Pack:
2271 return TemplateArgumentLocInfo();
2272 }
2273 llvm_unreachable("unexpected template argument loc");
2274 return TemplateArgumentLocInfo();
2275}
2276
2277Decl *PCHReader::GetDecl(pch::DeclID ID) {
2278 if (ID == 0)
2279 return 0;
2280
2281 if (ID > DeclsLoaded.size()) {
2282 Error("declaration ID out-of-range for PCH file");
2283 return 0;
2284 }
2285
2286 unsigned Index = ID - 1;
2287 if (!DeclsLoaded[Index])
2288 ReadDeclRecord(DeclOffsets[Index], Index);
2289
2290 return DeclsLoaded[Index];
2291}
2292
2293/// \brief Resolve the offset of a statement into a statement.
2294///
2295/// This operation will read a new statement from the external
2296/// source each time it is called, and is meant to be used via a
2297/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2298Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
2299 // Since we know tha this statement is part of a decl, make sure to use the
2300 // decl cursor to read it.
2301 DeclsCursor.JumpToBit(Offset);
2302 return ReadStmt(DeclsCursor);
2303}
2304
2305bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
2306 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
2307 assert(DC->hasExternalLexicalStorage() &&
2308 "DeclContext has no lexical decls in storage");
2309 uint64_t Offset = DeclContextOffsets[DC].first;
2310 assert(Offset && "DeclContext has no lexical decls in storage");
2311
2312 // Keep track of where we are in the stream, then jump back there
2313 // after reading this context.
2314 SavedStreamPosition SavedPosition(DeclsCursor);
2315
2316 // Load the record containing all of the declarations lexically in
2317 // this context.
2318 DeclsCursor.JumpToBit(Offset);
2319 RecordData Record;
2320 unsigned Code = DeclsCursor.ReadCode();
2321 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2322 (void)RecCode;
2323 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2324
2325 // Load all of the declaration IDs
2326 Decls.clear();
2327 Decls.insert(Decls.end(), Record.begin(), Record.end());
2328 ++NumLexicalDeclContextsRead;
2329 return false;
2330}
2331
2332bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
2333 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
2334 assert(DC->hasExternalVisibleStorage() &&
2335 "DeclContext has no visible decls in storage");
2336 uint64_t Offset = DeclContextOffsets[DC].second;
2337 assert(Offset && "DeclContext has no visible decls in storage");
2338
2339 // Keep track of where we are in the stream, then jump back there
2340 // after reading this context.
2341 SavedStreamPosition SavedPosition(DeclsCursor);
2342
2343 // Load the record containing all of the declarations visible in
2344 // this context.
2345 DeclsCursor.JumpToBit(Offset);
2346 RecordData Record;
2347 unsigned Code = DeclsCursor.ReadCode();
2348 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2349 (void)RecCode;
2350 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2351 if (Record.size() == 0)
2352 return false;
2353
2354 Decls.clear();
2355
2356 unsigned Idx = 0;
2357 while (Idx < Record.size()) {
2358 Decls.push_back(VisibleDeclaration());
2359 Decls.back().Name = ReadDeclarationName(Record, Idx);
2360
2361 unsigned Size = Record[Idx++];
2362 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2363 LoadedDecls.reserve(Size);
2364 for (unsigned I = 0; I < Size; ++I)
2365 LoadedDecls.push_back(Record[Idx++]);
2366 }
2367
2368 ++NumVisibleDeclContextsRead;
2369 return false;
2370}
2371
2372void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
2373 this->Consumer = Consumer;
2374
2375 if (!Consumer)
2376 return;
2377
2378 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2379 // Force deserialization of this decl, which will cause it to be passed to
2380 // the consumer (or queued).
2381 GetDecl(ExternalDefinitions[I]);
2382 }
2383
2384 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2385 DeclGroupRef DG(InterestingDecls[I]);
2386 Consumer->HandleTopLevelDecl(DG);
2387 }
2388}
2389
2390void PCHReader::PrintStats() {
2391 std::fprintf(stderr, "*** PCH Statistics:\n");
2392
2393 unsigned NumTypesLoaded
2394 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2395 QualType());
2396 unsigned NumDeclsLoaded
2397 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2398 (Decl *)0);
2399 unsigned NumIdentifiersLoaded
2400 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2401 IdentifiersLoaded.end(),
2402 (IdentifierInfo *)0);
2403 unsigned NumSelectorsLoaded
2404 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2405 SelectorsLoaded.end(),
2406 Selector());
2407
2408 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2409 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
2410 if (TotalNumSLocEntries)
2411 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2412 NumSLocEntriesRead, TotalNumSLocEntries,
2413 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
2414 if (!TypesLoaded.empty())
2415 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
2416 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2417 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2418 if (!DeclsLoaded.empty())
2419 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
2420 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2421 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
2422 if (!IdentifiersLoaded.empty())
2423 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
2424 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2425 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
2426 if (TotalNumSelectors)
2427 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2428 NumSelectorsLoaded, TotalNumSelectors,
2429 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2430 if (TotalNumStatements)
2431 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2432 NumStatementsRead, TotalNumStatements,
2433 ((float)NumStatementsRead/TotalNumStatements * 100));
2434 if (TotalNumMacros)
2435 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2436 NumMacrosRead, TotalNumMacros,
2437 ((float)NumMacrosRead/TotalNumMacros * 100));
2438 if (TotalLexicalDeclContexts)
2439 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2440 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2441 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2442 * 100));
2443 if (TotalVisibleDeclContexts)
2444 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2445 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2446 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2447 * 100));
2448 if (TotalSelectorsInMethodPool) {
2449 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2450 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2451 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2452 * 100));
2453 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2454 }
2455 std::fprintf(stderr, "\n");
2456}
2457
2458void PCHReader::InitializeSema(Sema &S) {
2459 SemaObj = &S;
2460 S.ExternalSource = this;
2461
2462 // Makes sure any declarations that were deserialized "too early"
2463 // still get added to the identifier's declaration chains.
2464 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2465 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2466 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
2467 }
2468 PreloadedDecls.clear();
2469
2470 // If there were any tentative definitions, deserialize them and add
2471 // them to Sema's list of tentative definitions.
2472 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2473 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2474 SemaObj->TentativeDefinitions.push_back(Var);
2475 }
2476
2477 // If there were any locally-scoped external declarations,
2478 // deserialize them and add them to Sema's table of locally-scoped
2479 // external declarations.
2480 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2481 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2482 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2483 }
2484
2485 // If there were any ext_vector type declarations, deserialize them
2486 // and add them to Sema's vector of such declarations.
2487 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2488 SemaObj->ExtVectorDecls.push_back(
2489 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2490}
2491
2492IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2493 // Try to find this name within our on-disk hash table
2494 PCHIdentifierLookupTable *IdTable
2495 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2496 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2497 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2498 if (Pos == IdTable->end())
2499 return 0;
2500
2501 // Dereferencing the iterator has the effect of building the
2502 // IdentifierInfo node and populating it with the various
2503 // declarations it needs.
2504 return *Pos;
2505}
2506
2507std::pair<ObjCMethodList, ObjCMethodList>
2508PCHReader::ReadMethodPool(Selector Sel) {
2509 if (!MethodPoolLookupTable)
2510 return std::pair<ObjCMethodList, ObjCMethodList>();
2511
2512 // Try to find this selector within our on-disk hash table.
2513 PCHMethodPoolLookupTable *PoolTable
2514 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2515 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
2516 if (Pos == PoolTable->end()) {
2517 ++NumMethodPoolMisses;
2518 return std::pair<ObjCMethodList, ObjCMethodList>();;
2519 }
2520
2521 ++NumMethodPoolSelectorsRead;
2522 return *Pos;
2523}
2524
2525void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
2526 assert(ID && "Non-zero identifier ID required");
2527 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
2528 IdentifiersLoaded[ID - 1] = II;
2529}
2530
2531/// \brief Set the globally-visible declarations associated with the given
2532/// identifier.
2533///
2534/// If the PCH reader is currently in a state where the given declaration IDs
2535/// cannot safely be resolved, they are queued until it is safe to resolve
2536/// them.
2537///
2538/// \param II an IdentifierInfo that refers to one or more globally-visible
2539/// declarations.
2540///
2541/// \param DeclIDs the set of declaration IDs with the name @p II that are
2542/// visible at global scope.
2543///
2544/// \param Nonrecursive should be true to indicate that the caller knows that
2545/// this call is non-recursive, and therefore the globally-visible declarations
2546/// will not be placed onto the pending queue.
2547void
2548PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2549 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2550 bool Nonrecursive) {
2551 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2552 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2553 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2554 PII.II = II;
2555 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2556 PII.DeclIDs.push_back(DeclIDs[I]);
2557 return;
2558 }
2559
2560 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2561 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2562 if (SemaObj) {
2563 // Introduce this declaration into the translation-unit scope
2564 // and add it to the declaration chain for this identifier, so
2565 // that (unqualified) name lookup will find it.
2566 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2567 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2568 } else {
2569 // Queue this declaration so that it will be added to the
2570 // translation unit scope and identifier's declaration chain
2571 // once a Sema object is known.
2572 PreloadedDecls.push_back(D);
2573 }
2574 }
2575}
2576
2577IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
2578 if (ID == 0)
2579 return 0;
2580
2581 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
2582 Error("no identifier table in PCH file");
2583 return 0;
2584 }
2585
2586 assert(PP && "Forgot to set Preprocessor ?");
2587 if (!IdentifiersLoaded[ID - 1]) {
2588 uint32_t Offset = IdentifierOffsets[ID - 1];
2589 const char *Str = IdentifierTableData + Offset;
2590
2591 // All of the strings in the PCH file are preceded by a 16-bit
2592 // length. Extract that 16-bit length to avoid having to execute
2593 // strlen().
2594 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2595 // unsigned integers. This is important to avoid integer overflow when
2596 // we cast them to 'unsigned'.
2597 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
2598 unsigned StrLen = (((unsigned) StrLenPtr[0])
2599 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2600 IdentifiersLoaded[ID - 1]
2601 = &PP->getIdentifierTable().get(Str, Str + StrLen);
2602 }
2603
2604 return IdentifiersLoaded[ID - 1];
2605}
2606
2607void PCHReader::ReadSLocEntry(unsigned ID) {
2608 ReadSLocEntryRecord(ID);
2609}
2610
2611Selector PCHReader::DecodeSelector(unsigned ID) {
2612 if (ID == 0)
2613 return Selector();
2614
2615 if (!MethodPoolLookupTableData)
2616 return Selector();
2617
2618 if (ID > TotalNumSelectors) {
2619 Error("selector ID out of range in PCH file");
2620 return Selector();
2621 }
2622
2623 unsigned Index = ID - 1;
2624 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2625 // Load this selector from the selector table.
2626 // FIXME: endianness portability issues with SelectorOffsets table
2627 PCHMethodPoolLookupTrait Trait(*this);
2628 SelectorsLoaded[Index]
2629 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2630 }
2631
2632 return SelectorsLoaded[Index];
2633}
2634
2635DeclarationName
2636PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2637 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2638 switch (Kind) {
2639 case DeclarationName::Identifier:
2640 return DeclarationName(GetIdentifierInfo(Record, Idx));
2641
2642 case DeclarationName::ObjCZeroArgSelector:
2643 case DeclarationName::ObjCOneArgSelector:
2644 case DeclarationName::ObjCMultiArgSelector:
2645 return DeclarationName(GetSelector(Record, Idx));
2646
2647 case DeclarationName::CXXConstructorName:
2648 return Context->DeclarationNames.getCXXConstructorName(
2649 Context->getCanonicalType(GetType(Record[Idx++])));
2650
2651 case DeclarationName::CXXDestructorName:
2652 return Context->DeclarationNames.getCXXDestructorName(
2653 Context->getCanonicalType(GetType(Record[Idx++])));
2654
2655 case DeclarationName::CXXConversionFunctionName:
2656 return Context->DeclarationNames.getCXXConversionFunctionName(
2657 Context->getCanonicalType(GetType(Record[Idx++])));
2658
2659 case DeclarationName::CXXOperatorName:
2660 return Context->DeclarationNames.getCXXOperatorName(
2661 (OverloadedOperatorKind)Record[Idx++]);
2662
2663 case DeclarationName::CXXLiteralOperatorName:
2664 return Context->DeclarationNames.getCXXLiteralOperatorName(
2665 GetIdentifierInfo(Record, Idx));
2666
2667 case DeclarationName::CXXUsingDirective:
2668 return DeclarationName::getUsingDirectiveName();
2669 }
2670
2671 // Required to silence GCC warning
2672 return DeclarationName();
2673}
2674
2675/// \brief Read an integral value
2676llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2677 unsigned BitWidth = Record[Idx++];
2678 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2679 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2680 Idx += NumWords;
2681 return Result;
2682}
2683
2684/// \brief Read a signed integral value
2685llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2686 bool isUnsigned = Record[Idx++];
2687 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2688}
2689
2690/// \brief Read a floating-point value
2691llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
2692 return llvm::APFloat(ReadAPInt(Record, Idx));
2693}
2694
2695// \brief Read a string
2696std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2697 unsigned Len = Record[Idx++];
2698 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
2699 Idx += Len;
2700 return Result;
2701}
2702
2703DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
2704 return Diag(SourceLocation(), DiagID);
2705}
2706
2707DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2708 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
2709}
2710
2711/// \brief Retrieve the identifier table associated with the
2712/// preprocessor.
2713IdentifierTable &PCHReader::getIdentifierTable() {
2714 assert(PP && "Forgot to set Preprocessor ?");
2715 return PP->getIdentifierTable();
2716}
2717
2718/// \brief Record that the given ID maps to the given switch-case
2719/// statement.
2720void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2721 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2722 SwitchCaseStmts[ID] = SC;
2723}
2724
2725/// \brief Retrieve the switch-case statement with the given ID.
2726SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2727 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2728 return SwitchCaseStmts[ID];
2729}
2730
2731/// \brief Record that the given label statement has been
2732/// deserialized and has the given ID.
2733void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2734 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2735 "Deserialized label twice");
2736 LabelStmts[ID] = S;
2737
2738 // If we've already seen any goto statements that point to this
2739 // label, resolve them now.
2740 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2741 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2742 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2743 Goto->second->setLabel(S);
2744 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
2745
2746 // If we've already seen any address-label statements that point to
2747 // this label, resolve them now.
2748 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2749 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2750 = UnresolvedAddrLabelExprs.equal_range(ID);
2751 for (AddrLabelIter AddrLabel = AddrLabels.first;
2752 AddrLabel != AddrLabels.second; ++AddrLabel)
2753 AddrLabel->second->setLabel(S);
2754 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
2755}
2756
2757/// \brief Set the label of the given statement to the label
2758/// identified by ID.
2759///
2760/// Depending on the order in which the label and other statements
2761/// referencing that label occur, this operation may complete
2762/// immediately (updating the statement) or it may queue the
2763/// statement to be back-patched later.
2764void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2765 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2766 if (Label != LabelStmts.end()) {
2767 // We've already seen this label, so set the label of the goto and
2768 // we're done.
2769 S->setLabel(Label->second);
2770 } else {
2771 // We haven't seen this label yet, so add this goto to the set of
2772 // unresolved goto statements.
2773 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2774 }
2775}
2776
2777/// \brief Set the label of the given expression to the label
2778/// identified by ID.
2779///
2780/// Depending on the order in which the label and other statements
2781/// referencing that label occur, this operation may complete
2782/// immediately (updating the statement) or it may queue the
2783/// statement to be back-patched later.
2784void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2785 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2786 if (Label != LabelStmts.end()) {
2787 // We've already seen this label, so set the label of the
2788 // label-address expression and we're done.
2789 S->setLabel(Label->second);
2790 } else {
2791 // We haven't seen this label yet, so add this label-address
2792 // expression to the set of unresolved label-address expressions.
2793 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2794 }
2795}
2796
2797
2798PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2799 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2800 Reader.CurrentlyLoadingTypeOrDecl = this;
2801}
2802
2803PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2804 if (!Parent) {
2805 // If any identifiers with corresponding top-level declarations have
2806 // been loaded, load those declarations now.
2807 while (!Reader.PendingIdentifierInfos.empty()) {
2808 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2809 Reader.PendingIdentifierInfos.front().DeclIDs,
2810 true);
2811 Reader.PendingIdentifierInfos.pop_front();
2812 }
2813 }
2814
2815 Reader.CurrentlyLoadingTypeOrDecl = Parent;
2816}