blob: 765655b01dd0cf67a0fef64562d39fa6921894ca [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- 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//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000039// PCH reader validator implementation
40//===----------------------------------------------------------------------===//
41
42PCHReaderListener::~PCHReaderListener() {}
43
44bool
45PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
46 const LangOptions &PPLangOpts = PP.getLangOptions();
47#define PARSE_LANGOPT_BENIGN(Option)
48#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
49 if (PPLangOpts.Option != LangOpts.Option) { \
50 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
51 return true; \
52 }
53
54 PARSE_LANGOPT_BENIGN(Trigraphs);
55 PARSE_LANGOPT_BENIGN(BCPLComment);
56 PARSE_LANGOPT_BENIGN(DollarIdents);
57 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
58 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
59 PARSE_LANGOPT_BENIGN(ImplicitInt);
60 PARSE_LANGOPT_BENIGN(Digraphs);
61 PARSE_LANGOPT_BENIGN(HexFloats);
62 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
63 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
64 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
66 PARSE_LANGOPT_BENIGN(CXXOperatorName);
67 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
68 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
69 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
70 PARSE_LANGOPT_BENIGN(PascalStrings);
71 PARSE_LANGOPT_BENIGN(WritableStrings);
72 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
73 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000075 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
76 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
77 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
78 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
79 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
80 diag::warn_pch_thread_safe_statics);
81 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
82 PARSE_LANGOPT_BENIGN(EmitAllDecls);
83 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
84 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
85 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
86 diag::warn_pch_heinous_extensions);
87 // FIXME: Most of the options below are benign if the macro wasn't
88 // used. Unfortunately, this means that a PCH compiled without
89 // optimization can't be used with optimization turned on, even
90 // though the only thing that changes is whether __OPTIMIZE__ was
91 // defined... but if __OPTIMIZE__ never showed up in the header, it
92 // doesn't matter. We could consider making this some special kind
93 // of check.
94 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
95 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
96 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
97 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
98 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
99 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
100 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
101 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
102 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
103 Reader.Diag(diag::warn_pch_gc_mode)
104 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
105 return true;
106 }
107 PARSE_LANGOPT_BENIGN(getVisibilityMode());
108 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000109 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000110#undef PARSE_LANGOPT_IRRELEVANT
111#undef PARSE_LANGOPT_BENIGN
112
113 return false;
114}
115
116bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
117 if (Triple != PP.getTargetInfo().getTargetTriple()) {
118 Reader.Diag(diag::warn_pch_target_triple)
119 << Triple << PP.getTargetInfo().getTargetTriple();
120 return true;
121 }
122 return false;
123}
124
125/// \brief Split the given string into a vector of lines, eliminating
126/// any empty lines in the process.
127///
128/// \param Str the string to split.
129/// \param Len the length of Str.
130/// \param KeepEmptyLines true if empty lines should be included
131/// \returns a vector of lines, with the line endings removed
132static std::vector<std::string> splitLines(const char *Str, unsigned Len,
133 bool KeepEmptyLines = false) {
134 std::vector<std::string> Lines;
135 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
136 unsigned LineEnd = LineStart;
137 while (LineEnd < Len && Str[LineEnd] != '\n')
138 ++LineEnd;
139 if (LineStart != LineEnd || KeepEmptyLines)
140 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
141 LineStart = LineEnd;
142 }
143 return Lines;
144}
145
146/// \brief Determine whether the string Haystack starts with the
147/// substring Needle.
148static bool startsWith(const std::string &Haystack, const char *Needle) {
149 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
150 if (I == N)
151 return false;
152 if (Haystack[I] != Needle[I])
153 return false;
154 }
155
156 return true;
157}
158
159/// \brief Determine whether the string Haystack starts with the
160/// substring Needle.
161static inline bool startsWith(const std::string &Haystack,
162 const std::string &Needle) {
163 return startsWith(Haystack, Needle.c_str());
164}
165
166bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
167 unsigned PCHPredefLen,
168 FileID PCHBufferID,
169 std::string &SuggestedPredefines) {
170 const char *Predef = PP.getPredefines().c_str();
171 unsigned PredefLen = PP.getPredefines().size();
172
173 // If the two predefines buffers compare equal, we're done!
174 if (PredefLen == PCHPredefLen &&
175 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
176 return false;
177
178 SourceManager &SourceMgr = PP.getSourceManager();
179
180 // The predefines buffers are different. Determine what the
181 // differences are, and whether they require us to reject the PCH
182 // file.
183 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
184 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
185
186 // Sort both sets of predefined buffer lines, since
187 std::sort(CmdLineLines.begin(), CmdLineLines.end());
188 std::sort(PCHLines.begin(), PCHLines.end());
189
190 // Determine which predefines that where used to build the PCH file
191 // are missing from the command line.
192 std::vector<std::string> MissingPredefines;
193 std::set_difference(PCHLines.begin(), PCHLines.end(),
194 CmdLineLines.begin(), CmdLineLines.end(),
195 std::back_inserter(MissingPredefines));
196
197 bool MissingDefines = false;
198 bool ConflictingDefines = false;
199 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
200 const std::string &Missing = MissingPredefines[I];
201 if (!startsWith(Missing, "#define ") != 0) {
202 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
203 return true;
204 }
205
206 // This is a macro definition. Determine the name of the macro
207 // we're defining.
208 std::string::size_type StartOfMacroName = strlen("#define ");
209 std::string::size_type EndOfMacroName
210 = Missing.find_first_of("( \n\r", StartOfMacroName);
211 assert(EndOfMacroName != std::string::npos &&
212 "Couldn't find the end of the macro name");
213 std::string MacroName = Missing.substr(StartOfMacroName,
214 EndOfMacroName - StartOfMacroName);
215
216 // Determine whether this macro was given a different definition
217 // on the command line.
218 std::string MacroDefStart = "#define " + MacroName;
219 std::string::size_type MacroDefLen = MacroDefStart.size();
220 std::vector<std::string>::iterator ConflictPos
221 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
222 MacroDefStart);
223 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
224 if (!startsWith(*ConflictPos, MacroDefStart)) {
225 // Different macro; we're done.
226 ConflictPos = CmdLineLines.end();
227 break;
228 }
229
230 assert(ConflictPos->size() > MacroDefLen &&
231 "Invalid #define in predefines buffer?");
232 if ((*ConflictPos)[MacroDefLen] != ' ' &&
233 (*ConflictPos)[MacroDefLen] != '(')
234 continue; // Longer macro name; keep trying.
235
236 // We found a conflicting macro definition.
237 break;
238 }
239
240 if (ConflictPos != CmdLineLines.end()) {
241 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
242 << MacroName;
243
244 // Show the definition of this macro within the PCH file.
245 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
246 unsigned Offset = MissingDef - PCHPredef;
247 SourceLocation PCHMissingLoc
248 = SourceMgr.getLocForStartOfFile(PCHBufferID)
249 .getFileLocWithOffset(Offset);
250 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
251 << MacroName;
252
253 ConflictingDefines = true;
254 continue;
255 }
256
257 // If the macro doesn't conflict, then we'll just pick up the
258 // macro definition from the PCH file. Warn the user that they
259 // made a mistake.
260 if (ConflictingDefines)
261 continue; // Don't complain if there are already conflicting defs
262
263 if (!MissingDefines) {
264 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
265 MissingDefines = true;
266 }
267
268 // Show the definition of this macro within the PCH file.
269 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
270 unsigned Offset = MissingDef - PCHPredef;
271 SourceLocation PCHMissingLoc
272 = SourceMgr.getLocForStartOfFile(PCHBufferID)
273 .getFileLocWithOffset(Offset);
274 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
275 }
276
277 if (ConflictingDefines)
278 return true;
279
280 // Determine what predefines were introduced based on command-line
281 // parameters that were not present when building the PCH
282 // file. Extra #defines are okay, so long as the identifiers being
283 // defined were not used within the precompiled header.
284 std::vector<std::string> ExtraPredefines;
285 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
286 PCHLines.begin(), PCHLines.end(),
287 std::back_inserter(ExtraPredefines));
288 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
289 const std::string &Extra = ExtraPredefines[I];
290 if (!startsWith(Extra, "#define ") != 0) {
291 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
292 return true;
293 }
294
295 // This is an extra macro definition. Determine the name of the
296 // macro we're defining.
297 std::string::size_type StartOfMacroName = strlen("#define ");
298 std::string::size_type EndOfMacroName
299 = Extra.find_first_of("( \n\r", StartOfMacroName);
300 assert(EndOfMacroName != std::string::npos &&
301 "Couldn't find the end of the macro name");
302 std::string MacroName = Extra.substr(StartOfMacroName,
303 EndOfMacroName - StartOfMacroName);
304
305 // Check whether this name was used somewhere in the PCH file. If
306 // so, defining it as a macro could change behavior, so we reject
307 // the PCH file.
308 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
309 MacroName.c_str() + MacroName.size())) {
310 Reader.Diag(diag::warn_macro_name_used_in_pch)
311 << II;
312 return true;
313 }
314
315 // Add this definition to the suggested predefines buffer.
316 SuggestedPredefines += Extra;
317 SuggestedPredefines += '\n';
318 }
319
320 // If we get here, it's because the predefines buffer had compatible
321 // contents. Accept the PCH file.
322 return false;
323}
324
325void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
326 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
327}
328
329void PCHValidator::ReadCounter(unsigned Value) {
330 PP.setCounterValue(Value);
331}
332
333
334
335//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000336// PCH reader implementation
337//===----------------------------------------------------------------------===//
338
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000339PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
341 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
342 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
343 IdentifierTableData(0), IdentifierLookupTable(0),
344 IdentifierOffsets(0),
345 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
346 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
347 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
348 NumSLocEntriesRead(0), NumStatementsRead(0),
349 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
350 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
351
352PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
353 Diagnostic &Diags)
354 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000355 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000356 IdentifierTableData(0), IdentifierLookupTable(0),
357 IdentifierOffsets(0),
358 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
359 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000360 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
361 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000362 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000363 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
364
365PCHReader::~PCHReader() {}
366
Chris Lattnerda930612009-04-27 05:58:23 +0000367Expr *PCHReader::ReadDeclExpr() {
368 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
369}
370
371Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000372 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000373}
374
375
Douglas Gregor668c1a42009-04-21 22:25:48 +0000376namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000377class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
378 PCHReader &Reader;
379
380public:
381 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
382
383 typedef Selector external_key_type;
384 typedef external_key_type internal_key_type;
385
386 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
387
388 static bool EqualKey(const internal_key_type& a,
389 const internal_key_type& b) {
390 return a == b;
391 }
392
393 static unsigned ComputeHash(Selector Sel) {
394 unsigned N = Sel.getNumArgs();
395 if (N == 0)
396 ++N;
397 unsigned R = 5381;
398 for (unsigned I = 0; I != N; ++I)
399 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
400 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
401 return R;
402 }
403
404 // This hopefully will just get inlined and removed by the optimizer.
405 static const internal_key_type&
406 GetInternalKey(const external_key_type& x) { return x; }
407
408 static std::pair<unsigned, unsigned>
409 ReadKeyDataLength(const unsigned char*& d) {
410 using namespace clang::io;
411 unsigned KeyLen = ReadUnalignedLE16(d);
412 unsigned DataLen = ReadUnalignedLE16(d);
413 return std::make_pair(KeyLen, DataLen);
414 }
415
Douglas Gregor83941df2009-04-25 17:48:32 +0000416 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000417 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000418 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000419 unsigned N = ReadUnalignedLE16(d);
420 IdentifierInfo *FirstII
421 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
422 if (N == 0)
423 return SelTable.getNullarySelector(FirstII);
424 else if (N == 1)
425 return SelTable.getUnarySelector(FirstII);
426
427 llvm::SmallVector<IdentifierInfo *, 16> Args;
428 Args.push_back(FirstII);
429 for (unsigned I = 1; I != N; ++I)
430 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
431
Douglas Gregor75fdb232009-05-22 22:45:36 +0000432 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000433 }
434
435 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
436 using namespace clang::io;
437 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
438 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
439
440 data_type Result;
441
442 // Load instance methods
443 ObjCMethodList *Prev = 0;
444 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
445 ObjCMethodDecl *Method
446 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
447 if (!Result.first.Method) {
448 // This is the first method, which is the easy case.
449 Result.first.Method = Method;
450 Prev = &Result.first;
451 continue;
452 }
453
454 Prev->Next = new ObjCMethodList(Method, 0);
455 Prev = Prev->Next;
456 }
457
458 // Load factory methods
459 Prev = 0;
460 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
461 ObjCMethodDecl *Method
462 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
463 if (!Result.second.Method) {
464 // This is the first method, which is the easy case.
465 Result.second.Method = Method;
466 Prev = &Result.second;
467 continue;
468 }
469
470 Prev->Next = new ObjCMethodList(Method, 0);
471 Prev = Prev->Next;
472 }
473
474 return Result;
475 }
476};
477
478} // end anonymous namespace
479
480/// \brief The on-disk hash table used for the global method pool.
481typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
482 PCHMethodPoolLookupTable;
483
484namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000485class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
486 PCHReader &Reader;
487
488 // If we know the IdentifierInfo in advance, it is here and we will
489 // not build a new one. Used when deserializing information about an
490 // identifier that was constructed before the PCH file was read.
491 IdentifierInfo *KnownII;
492
493public:
494 typedef IdentifierInfo * data_type;
495
496 typedef const std::pair<const char*, unsigned> external_key_type;
497
498 typedef external_key_type internal_key_type;
499
500 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
501 : Reader(Reader), KnownII(II) { }
502
503 static bool EqualKey(const internal_key_type& a,
504 const internal_key_type& b) {
505 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
506 : false;
507 }
508
509 static unsigned ComputeHash(const internal_key_type& a) {
510 return BernsteinHash(a.first, a.second);
511 }
512
513 // This hopefully will just get inlined and removed by the optimizer.
514 static const internal_key_type&
515 GetInternalKey(const external_key_type& x) { return x; }
516
517 static std::pair<unsigned, unsigned>
518 ReadKeyDataLength(const unsigned char*& d) {
519 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000520 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000521 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000522 return std::make_pair(KeyLen, DataLen);
523 }
524
525 static std::pair<const char*, unsigned>
526 ReadKey(const unsigned char* d, unsigned n) {
527 assert(n >= 2 && d[n-1] == '\0');
528 return std::make_pair((const char*) d, n-1);
529 }
530
531 IdentifierInfo *ReadData(const internal_key_type& k,
532 const unsigned char* d,
533 unsigned DataLen) {
534 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000535 pch::IdentID ID = ReadUnalignedLE32(d);
536 bool IsInteresting = ID & 0x01;
537
538 // Wipe out the "is interesting" bit.
539 ID = ID >> 1;
540
541 if (!IsInteresting) {
542 // For unintersting identifiers, just build the IdentifierInfo
543 // and associate it with the persistent ID.
544 IdentifierInfo *II = KnownII;
545 if (!II)
546 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
547 k.first, k.first + k.second);
548 Reader.SetIdentifierInfo(ID, II);
549 return II;
550 }
551
Douglas Gregor5998da52009-04-28 21:32:13 +0000552 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000553 bool CPlusPlusOperatorKeyword = Bits & 0x01;
554 Bits >>= 1;
555 bool Poisoned = Bits & 0x01;
556 Bits >>= 1;
557 bool ExtensionToken = Bits & 0x01;
558 Bits >>= 1;
559 bool hasMacroDefinition = Bits & 0x01;
560 Bits >>= 1;
561 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
562 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000563
Douglas Gregor2deaea32009-04-22 18:49:13 +0000564 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000565 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000566
567 // Build the IdentifierInfo itself and link the identifier ID with
568 // the new IdentifierInfo.
569 IdentifierInfo *II = KnownII;
570 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000571 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
572 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000573 Reader.SetIdentifierInfo(ID, II);
574
Douglas Gregor2deaea32009-04-22 18:49:13 +0000575 // Set or check the various bits in the IdentifierInfo structure.
576 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000577 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
578 assert(II->isExtensionToken() == ExtensionToken &&
579 "Incorrect extension token flag");
580 (void)ExtensionToken;
581 II->setIsPoisoned(Poisoned);
582 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
583 "Incorrect C++ operator keyword flag");
584 (void)CPlusPlusOperatorKeyword;
585
Douglas Gregor37e26842009-04-21 23:56:24 +0000586 // If this identifier is a macro, deserialize the macro
587 // definition.
588 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000589 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000590 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000591 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000592 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000593
594 // Read all of the declarations visible at global scope with this
595 // name.
596 Sema *SemaObj = Reader.getSema();
Chris Lattner6bf690f2009-04-27 22:17:41 +0000597 if (Reader.getContext() == 0) return II;
Chris Lattnercc7dea82009-04-27 22:02:30 +0000598
Douglas Gregor668c1a42009-04-21 22:25:48 +0000599 while (DataLen > 0) {
600 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000601 if (SemaObj) {
602 // Introduce this declaration into the translation-unit scope
603 // and add it to the declaration chain for this identifier, so
604 // that (unqualified) name lookup will find it.
605 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
606 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
607 } else {
608 // Queue this declaration so that it will be added to the
609 // translation unit scope and identifier's declaration chain
610 // once a Sema object is known.
Douglas Gregor6cfc1a82009-04-22 21:15:06 +0000611 Reader.PreloadedDecls.push_back(D);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000612 }
613
614 DataLen -= 4;
615 }
616 return II;
617 }
618};
619
620} // end anonymous namespace
621
622/// \brief The on-disk hash table used to contain information about
623/// all of the identifiers in the program.
624typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
625 PCHIdentifierLookupTable;
626
Douglas Gregor2cf26342009-04-09 22:27:44 +0000627// FIXME: use the diagnostics machinery
Douglas Gregora02b1472009-04-28 21:53:25 +0000628bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000629 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
630 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000631 return true;
632}
633
Douglas Gregore1d918e2009-04-10 23:10:45 +0000634/// \brief Check the contents of the predefines buffer against the
635/// contents of the predefines buffer used to build the PCH file.
636///
637/// The contents of the two predefines buffers should be the same. If
638/// not, then some command-line option changed the preprocessor state
639/// and we must reject the PCH file.
640///
641/// \param PCHPredef The start of the predefines buffer in the PCH
642/// file.
643///
644/// \param PCHPredefLen The length of the predefines buffer in the PCH
645/// file.
646///
647/// \param PCHBufferID The FileID for the PCH predefines buffer.
648///
649/// \returns true if there was a mismatch (in which case the PCH file
650/// should be ignored), or false otherwise.
651bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
652 unsigned PCHPredefLen,
653 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000654 if (Listener)
655 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
656 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000657 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000658}
659
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000660//===----------------------------------------------------------------------===//
661// Source Manager Deserialization
662//===----------------------------------------------------------------------===//
663
Douglas Gregorbd945002009-04-13 16:31:14 +0000664/// \brief Read the line table in the source manager block.
665/// \returns true if ther was an error.
666static bool ParseLineTable(SourceManager &SourceMgr,
667 llvm::SmallVectorImpl<uint64_t> &Record) {
668 unsigned Idx = 0;
669 LineTableInfo &LineTable = SourceMgr.getLineTable();
670
671 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000672 std::map<int, int> FileIDs;
673 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000674 // Extract the file name
675 unsigned FilenameLen = Record[Idx++];
676 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
677 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000678 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
679 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000680 }
681
682 // Parse the line entries
683 std::vector<LineEntry> Entries;
684 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000685 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000686
687 // Extract the line entries
688 unsigned NumEntries = Record[Idx++];
689 Entries.clear();
690 Entries.reserve(NumEntries);
691 for (unsigned I = 0; I != NumEntries; ++I) {
692 unsigned FileOffset = Record[Idx++];
693 unsigned LineNo = Record[Idx++];
694 int FilenameID = Record[Idx++];
695 SrcMgr::CharacteristicKind FileKind
696 = (SrcMgr::CharacteristicKind)Record[Idx++];
697 unsigned IncludeOffset = Record[Idx++];
698 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
699 FileKind, IncludeOffset));
700 }
701 LineTable.AddEntry(FID, Entries);
702 }
703
704 return false;
705}
706
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000707namespace {
708
709class VISIBILITY_HIDDEN PCHStatData {
710public:
711 const bool hasStat;
712 const ino_t ino;
713 const dev_t dev;
714 const mode_t mode;
715 const time_t mtime;
716 const off_t size;
717
718 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
719 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
720
721 PCHStatData()
722 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
723};
724
725class VISIBILITY_HIDDEN PCHStatLookupTrait {
726 public:
727 typedef const char *external_key_type;
728 typedef const char *internal_key_type;
729
730 typedef PCHStatData data_type;
731
732 static unsigned ComputeHash(const char *path) {
733 return BernsteinHash(path);
734 }
735
736 static internal_key_type GetInternalKey(const char *path) { return path; }
737
738 static bool EqualKey(internal_key_type a, internal_key_type b) {
739 return strcmp(a, b) == 0;
740 }
741
742 static std::pair<unsigned, unsigned>
743 ReadKeyDataLength(const unsigned char*& d) {
744 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
745 unsigned DataLen = (unsigned) *d++;
746 return std::make_pair(KeyLen + 1, DataLen);
747 }
748
749 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
750 return (const char *)d;
751 }
752
753 static data_type ReadData(const internal_key_type, const unsigned char *d,
754 unsigned /*DataLen*/) {
755 using namespace clang::io;
756
757 if (*d++ == 1)
758 return data_type();
759
760 ino_t ino = (ino_t) ReadUnalignedLE32(d);
761 dev_t dev = (dev_t) ReadUnalignedLE32(d);
762 mode_t mode = (mode_t) ReadUnalignedLE16(d);
763 time_t mtime = (time_t) ReadUnalignedLE64(d);
764 off_t size = (off_t) ReadUnalignedLE64(d);
765 return data_type(ino, dev, mode, mtime, size);
766 }
767};
768
769/// \brief stat() cache for precompiled headers.
770///
771/// This cache is very similar to the stat cache used by pretokenized
772/// headers.
773class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
774 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
775 CacheTy *Cache;
776
777 unsigned &NumStatHits, &NumStatMisses;
778public:
779 PCHStatCache(const unsigned char *Buckets,
780 const unsigned char *Base,
781 unsigned &NumStatHits,
782 unsigned &NumStatMisses)
783 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
784 Cache = CacheTy::Create(Buckets, Base);
785 }
786
787 ~PCHStatCache() { delete Cache; }
788
789 int stat(const char *path, struct stat *buf) {
790 // Do the lookup for the file's data in the PCH file.
791 CacheTy::iterator I = Cache->find(path);
792
793 // If we don't get a hit in the PCH file just forward to 'stat'.
794 if (I == Cache->end()) {
795 ++NumStatMisses;
796 return ::stat(path, buf);
797 }
798
799 ++NumStatHits;
800 PCHStatData Data = *I;
801
802 if (!Data.hasStat)
803 return 1;
804
805 buf->st_ino = Data.ino;
806 buf->st_dev = Data.dev;
807 buf->st_mtime = Data.mtime;
808 buf->st_mode = Data.mode;
809 buf->st_size = Data.size;
810 return 0;
811 }
812};
813} // end anonymous namespace
814
815
Douglas Gregor14f79002009-04-10 03:52:48 +0000816/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000817PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000818 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000819
820 // Set the source-location entry cursor to the current position in
821 // the stream. This cursor will be used to read the contents of the
822 // source manager block initially, and then lazily read
823 // source-location entries as needed.
824 SLocEntryCursor = Stream;
825
826 // The stream itself is going to skip over the source manager block.
827 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000828 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000829 return Failure;
830 }
831
832 // Enter the source manager block.
833 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000834 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000835 return Failure;
836 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000837
Douglas Gregor14f79002009-04-10 03:52:48 +0000838 RecordData Record;
839 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000840 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000841 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000842 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000843 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000844 return Failure;
845 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000846 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000847 }
848
849 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
850 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000851 SLocEntryCursor.ReadSubBlockID();
852 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000853 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000854 return Failure;
855 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000856 continue;
857 }
858
859 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000860 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000861 continue;
862 }
863
864 // Read a record.
865 const char *BlobStart;
866 unsigned BlobLen;
867 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000868 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000869 default: // Default behavior: ignore.
870 break;
871
Chris Lattner2c78b872009-04-14 23:22:57 +0000872 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000873 if (ParseLineTable(SourceMgr, Record))
874 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000875 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000876
877 case pch::SM_HEADER_FILE_INFO: {
878 HeaderFileInfo HFI;
879 HFI.isImport = Record[0];
880 HFI.DirInfo = Record[1];
881 HFI.NumIncludes = Record[2];
882 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000883 if (Listener)
884 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000885 break;
886 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000887
888 case pch::SM_SLOC_FILE_ENTRY:
889 case pch::SM_SLOC_BUFFER_ENTRY:
890 case pch::SM_SLOC_INSTANTIATION_ENTRY:
891 // Once we hit one of the source location entries, we're done.
892 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000893 }
894 }
895}
896
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000897/// \brief Read in the source location entry with the given ID.
898PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
899 if (ID == 0)
900 return Success;
901
902 if (ID > TotalNumSLocEntries) {
903 Error("source location entry ID out-of-range for PCH file");
904 return Failure;
905 }
906
907 ++NumSLocEntriesRead;
908 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
909 unsigned Code = SLocEntryCursor.ReadCode();
910 if (Code == llvm::bitc::END_BLOCK ||
911 Code == llvm::bitc::ENTER_SUBBLOCK ||
912 Code == llvm::bitc::DEFINE_ABBREV) {
913 Error("incorrectly-formatted source location entry in PCH file");
914 return Failure;
915 }
916
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000917 RecordData Record;
918 const char *BlobStart;
919 unsigned BlobLen;
920 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
921 default:
922 Error("incorrectly-formatted source location entry in PCH file");
923 return Failure;
924
925 case pch::SM_SLOC_FILE_ENTRY: {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000926 const FileEntry *File = FileMgr.getFile(BlobStart, BlobStart + BlobLen);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000927 if (File == 0) {
928 std::string ErrorStr = "could not find file '";
929 ErrorStr.append(BlobStart, BlobLen);
930 ErrorStr += "' referenced by PCH file";
931 Error(ErrorStr.c_str());
932 return Failure;
933 }
934
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000935 FileID FID = SourceMgr.createFileID(File,
936 SourceLocation::getFromRawEncoding(Record[1]),
937 (SrcMgr::CharacteristicKind)Record[2],
938 ID, Record[0]);
939 if (Record[3])
940 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
941 .setHasLineDirectives();
942
943 break;
944 }
945
946 case pch::SM_SLOC_BUFFER_ENTRY: {
947 const char *Name = BlobStart;
948 unsigned Offset = Record[0];
949 unsigned Code = SLocEntryCursor.ReadCode();
950 Record.clear();
951 unsigned RecCode
952 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
953 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
954 (void)RecCode;
955 llvm::MemoryBuffer *Buffer
956 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
957 BlobStart + BlobLen - 1,
958 Name);
959 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
960
Douglas Gregor92b059e2009-04-28 20:33:11 +0000961 if (strcmp(Name, "<built-in>") == 0) {
962 PCHPredefinesBufferID = BufferID;
963 PCHPredefines = BlobStart;
964 PCHPredefinesLen = BlobLen - 1;
965 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000966
967 break;
968 }
969
970 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
971 SourceLocation SpellingLoc
972 = SourceLocation::getFromRawEncoding(Record[1]);
973 SourceMgr.createInstantiationLoc(SpellingLoc,
974 SourceLocation::getFromRawEncoding(Record[2]),
975 SourceLocation::getFromRawEncoding(Record[3]),
976 Record[4],
977 ID,
978 Record[0]);
979 break;
980 }
981 }
982
983 return Success;
984}
985
Chris Lattner6367f6d2009-04-27 01:05:14 +0000986/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
987/// specified cursor. Read the abbreviations that are at the top of the block
988/// and then leave the cursor pointing into the block.
989bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
990 unsigned BlockID) {
991 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000992 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000993 return Failure;
994 }
995
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 while (true) {
997 unsigned Code = Cursor.ReadCode();
998
999 // We expect all abbrevs to be at the start of the block.
1000 if (Code != llvm::bitc::DEFINE_ABBREV)
1001 return false;
1002 Cursor.ReadAbbrevRecord();
1003 }
1004}
1005
Douglas Gregor37e26842009-04-21 23:56:24 +00001006void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001007 assert(PP && "Forgot to set Preprocessor ?");
1008
Douglas Gregor37e26842009-04-21 23:56:24 +00001009 // Keep track of where we are in the stream, then jump back there
1010 // after reading this macro.
1011 SavedStreamPosition SavedPosition(Stream);
1012
1013 Stream.JumpToBit(Offset);
1014 RecordData Record;
1015 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1016 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +00001017
Douglas Gregor37e26842009-04-21 23:56:24 +00001018 while (true) {
1019 unsigned Code = Stream.ReadCode();
1020 switch (Code) {
1021 case llvm::bitc::END_BLOCK:
1022 return;
1023
1024 case llvm::bitc::ENTER_SUBBLOCK:
1025 // No known subblocks, always skip them.
1026 Stream.ReadSubBlockID();
1027 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001028 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001029 return;
1030 }
1031 continue;
1032
1033 case llvm::bitc::DEFINE_ABBREV:
1034 Stream.ReadAbbrevRecord();
1035 continue;
1036 default: break;
1037 }
1038
1039 // Read a record.
1040 Record.clear();
1041 pch::PreprocessorRecordTypes RecType =
1042 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1043 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001044 case pch::PP_MACRO_OBJECT_LIKE:
1045 case pch::PP_MACRO_FUNCTION_LIKE: {
1046 // If we already have a macro, that means that we've hit the end
1047 // of the definition of the macro we were looking for. We're
1048 // done.
1049 if (Macro)
1050 return;
1051
1052 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1053 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001054 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001055 return;
1056 }
1057 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1058 bool isUsed = Record[2];
1059
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001060 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001061 MI->setIsUsed(isUsed);
1062
1063 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1064 // Decode function-like macro info.
1065 bool isC99VarArgs = Record[3];
1066 bool isGNUVarArgs = Record[4];
1067 MacroArgs.clear();
1068 unsigned NumArgs = Record[5];
1069 for (unsigned i = 0; i != NumArgs; ++i)
1070 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1071
1072 // Install function-like macro info.
1073 MI->setIsFunctionLike();
1074 if (isC99VarArgs) MI->setIsC99Varargs();
1075 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001076 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001077 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001078 }
1079
1080 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001081 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001082
1083 // Remember that we saw this macro last so that we add the tokens that
1084 // form its body to it.
1085 Macro = MI;
1086 ++NumMacrosRead;
1087 break;
1088 }
1089
1090 case pch::PP_TOKEN: {
1091 // If we see a TOKEN before a PP_MACRO_*, then the file is
1092 // erroneous, just pretend we didn't see this.
1093 if (Macro == 0) break;
1094
1095 Token Tok;
1096 Tok.startToken();
1097 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1098 Tok.setLength(Record[1]);
1099 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1100 Tok.setIdentifierInfo(II);
1101 Tok.setKind((tok::TokenKind)Record[3]);
1102 Tok.setFlag((Token::TokenFlags)Record[4]);
1103 Macro->AddTokenToBody(Tok);
1104 break;
1105 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001106 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001107 }
1108}
1109
Douglas Gregor668c1a42009-04-21 22:25:48 +00001110PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001111PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001112 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001113 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001114 return Failure;
1115 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001116
1117 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001118 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001119 while (!Stream.AtEndOfStream()) {
1120 unsigned Code = Stream.ReadCode();
1121 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001122 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001123 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001124 return Failure;
1125 }
Chris Lattner7356a312009-04-11 21:15:38 +00001126
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001127 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001128 }
1129
1130 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1131 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001132 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1133 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001134 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001135 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001136 return Failure;
1137 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001138 break;
1139
Chris Lattner6367f6d2009-04-27 01:05:14 +00001140 case pch::DECLS_BLOCK_ID:
1141 // We lazily load the decls block, but we want to set up the
1142 // DeclsCursor cursor to point into it. Clone our current bitcode
1143 // cursor to it, enter the block and read the abbrevs in that block.
1144 // With the main cursor, we just skip over it.
1145 DeclsCursor = Stream;
1146 if (Stream.SkipBlock() || // Skip with the main cursor.
1147 // Read the abbrevs.
1148 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001149 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001150 return Failure;
1151 }
1152 break;
1153
Chris Lattner7356a312009-04-11 21:15:38 +00001154 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001155 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001156 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001157 return Failure;
1158 }
1159 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001160
Douglas Gregor14f79002009-04-10 03:52:48 +00001161 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001162 switch (ReadSourceManagerBlock()) {
1163 case Success:
1164 break;
1165
1166 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001167 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001168 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001169
1170 case IgnorePCH:
1171 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001172 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001173 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001174 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001175 continue;
1176 }
1177
1178 if (Code == llvm::bitc::DEFINE_ABBREV) {
1179 Stream.ReadAbbrevRecord();
1180 continue;
1181 }
1182
1183 // Read and process a record.
1184 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001185 const char *BlobStart = 0;
1186 unsigned BlobLen = 0;
1187 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1188 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001189 default: // Default behavior: ignore.
1190 break;
1191
1192 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001193 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001194 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001195 return Failure;
1196 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001197 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001198 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001199 break;
1200
1201 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001202 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001203 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001204 return Failure;
1205 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001206 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001207 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001208 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001209
1210 case pch::LANGUAGE_OPTIONS:
1211 if (ParseLanguageOptions(Record))
1212 return IgnorePCH;
1213 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001214
Douglas Gregorab41e632009-04-27 22:23:34 +00001215 case pch::METADATA: {
1216 if (Record[0] != pch::VERSION_MAJOR) {
1217 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1218 : diag::warn_pch_version_too_new);
1219 return IgnorePCH;
1220 }
1221
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001222 if (Listener) {
1223 std::string TargetTriple(BlobStart, BlobLen);
1224 if (Listener->ReadTargetTriple(TargetTriple))
1225 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001226 }
1227 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001228 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001229
1230 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001231 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001232 if (Record[0]) {
1233 IdentifierLookupTable
1234 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001235 (const unsigned char *)IdentifierTableData + Record[0],
1236 (const unsigned char *)IdentifierTableData,
1237 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001238 if (PP)
1239 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001240 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001241 break;
1242
1243 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001244 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001245 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001246 return Failure;
1247 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001248 IdentifierOffsets = (const uint32_t *)BlobStart;
1249 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001250 if (PP)
1251 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001252 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001253
1254 case pch::EXTERNAL_DEFINITIONS:
1255 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001256 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001257 return Failure;
1258 }
1259 ExternalDefinitions.swap(Record);
1260 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001261
Douglas Gregorad1de002009-04-18 05:55:16 +00001262 case pch::SPECIAL_TYPES:
1263 SpecialTypes.swap(Record);
1264 break;
1265
Douglas Gregor3e1af842009-04-17 22:13:46 +00001266 case pch::STATISTICS:
1267 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001268 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001269 TotalLexicalDeclContexts = Record[2];
1270 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001271 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001272
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001273 case pch::TENTATIVE_DEFINITIONS:
1274 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001275 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001276 return Failure;
1277 }
1278 TentativeDefinitions.swap(Record);
1279 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001280
1281 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1282 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001283 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001284 return Failure;
1285 }
1286 LocallyScopedExternalDecls.swap(Record);
1287 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001288
Douglas Gregor83941df2009-04-25 17:48:32 +00001289 case pch::SELECTOR_OFFSETS:
1290 SelectorOffsets = (const uint32_t *)BlobStart;
1291 TotalNumSelectors = Record[0];
1292 SelectorsLoaded.resize(TotalNumSelectors);
1293 break;
1294
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001295 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001296 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1297 if (Record[0])
1298 MethodPoolLookupTable
1299 = PCHMethodPoolLookupTable::Create(
1300 MethodPoolLookupTableData + Record[0],
1301 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001302 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001303 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001304 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001305
1306 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001307 if (!Record.empty() && Listener)
1308 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001309 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001310
1311 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001312 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001313 TotalNumSLocEntries = Record[0];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001314 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001315 TotalNumSLocEntries,
1316 Record[1]);
1317 break;
1318
1319 case pch::SOURCE_LOCATION_PRELOADS:
1320 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1321 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1322 if (Result != Success)
1323 return Result;
1324 }
1325 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001326
1327 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001328 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001329 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1330 (const unsigned char *)BlobStart,
1331 NumStatHits, NumStatMisses));
1332 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001333
1334 case pch::EXT_VECTOR_DECLS:
1335 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001336 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001337 return Failure;
1338 }
1339 ExtVectorDecls.swap(Record);
1340 break;
1341
1342 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1343 if (!ObjCCategoryImpls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001344 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001345 return Failure;
1346 }
1347 ObjCCategoryImpls.swap(Record);
1348 break;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001349
1350 case pch::ORIGINAL_FILE_NAME:
1351 OriginalFileName.assign(BlobStart, BlobLen);
1352 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001353 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001354 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001355 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001356 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001357}
1358
Douglas Gregore1d918e2009-04-10 23:10:45 +00001359PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001360 // Set the PCH file name.
1361 this->FileName = FileName;
1362
Douglas Gregor2cf26342009-04-09 22:27:44 +00001363 // Open the PCH file.
1364 std::string ErrStr;
1365 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001366 if (!Buffer) {
1367 Error(ErrStr.c_str());
1368 return IgnorePCH;
1369 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001370
1371 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001372 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1373 (const unsigned char *)Buffer->getBufferEnd());
1374 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001375
1376 // Sniff for the signature.
1377 if (Stream.Read(8) != 'C' ||
1378 Stream.Read(8) != 'P' ||
1379 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001380 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001381 Diag(diag::err_not_a_pch_file) << FileName;
1382 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001383 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001384
Douglas Gregor2cf26342009-04-09 22:27:44 +00001385 while (!Stream.AtEndOfStream()) {
1386 unsigned Code = Stream.ReadCode();
1387
Douglas Gregore1d918e2009-04-10 23:10:45 +00001388 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001389 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001390 return Failure;
1391 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001392
1393 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001394
Douglas Gregor2cf26342009-04-09 22:27:44 +00001395 // We only know the PCH subblock ID.
1396 switch (BlockID) {
1397 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001398 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001399 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001400 return Failure;
1401 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001402 break;
1403 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001404 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001405 case Success:
1406 break;
1407
1408 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001409 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001410
1411 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001412 // FIXME: We could consider reading through to the end of this
1413 // PCH block, skipping subblocks, to see if there are other
1414 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001415
1416 // Clear out any preallocated source location entries, so that
1417 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001418 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001419
1420 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001421 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001422
Douglas Gregore1d918e2009-04-10 23:10:45 +00001423 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001424 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425 break;
1426 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001427 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001428 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001429 return Failure;
1430 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001431 break;
1432 }
1433 }
Douglas Gregor92b059e2009-04-28 20:33:11 +00001434
1435 // Check the predefines buffer.
1436 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1437 PCHPredefinesBufferID))
1438 return IgnorePCH;
1439
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001440 if (PP) {
1441 // Initialization of builtins and library builtins occurs before the
1442 // PCH file is read, so there may be some identifiers that were
1443 // loaded into the IdentifierTable before we intercepted the
1444 // creation of identifiers. Iterate through the list of known
1445 // identifiers and determine whether we have to establish
1446 // preprocessor definitions or top-level identifier declaration
1447 // chains for those identifiers.
1448 //
1449 // We copy the IdentifierInfo pointers to a small vector first,
1450 // since de-serializing declarations or macro definitions can add
1451 // new entries into the identifier table, invalidating the
1452 // iterators.
1453 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1454 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1455 IdEnd = PP->getIdentifierTable().end();
1456 Id != IdEnd; ++Id)
1457 Identifiers.push_back(Id->second);
1458 PCHIdentifierLookupTable *IdTable
1459 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1460 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1461 IdentifierInfo *II = Identifiers[I];
1462 // Look in the on-disk hash table for an entry for
1463 PCHIdentifierLookupTrait Info(*this, II);
1464 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1465 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1466 if (Pos == IdTable->end())
1467 continue;
1468
1469 // Dereferencing the iterator has the effect of populating the
1470 // IdentifierInfo node with the various declarations it needs.
1471 (void)*Pos;
1472 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001473 }
1474
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001475 if (Context)
1476 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001477
Douglas Gregor668c1a42009-04-21 22:25:48 +00001478 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001479}
1480
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001481void PCHReader::InitializeContext(ASTContext &Ctx) {
1482 Context = &Ctx;
1483 assert(Context && "Passed null context!");
1484
1485 assert(PP && "Forgot to set Preprocessor ?");
1486 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1487 PP->getHeaderSearchInfo().SetExternalLookup(this);
1488
1489 // Load the translation unit declaration
1490 ReadDeclRecord(DeclOffsets[0], 0);
1491
1492 // Load the special types.
1493 Context->setBuiltinVaListType(
1494 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1495 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1496 Context->setObjCIdType(GetType(Id));
1497 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1498 Context->setObjCSelType(GetType(Sel));
1499 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1500 Context->setObjCProtoType(GetType(Proto));
1501 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1502 Context->setObjCClassType(GetType(Class));
1503 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1504 Context->setCFConstantStringType(GetType(String));
1505 if (unsigned FastEnum
1506 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1507 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1508}
1509
Douglas Gregorb64c1932009-05-12 01:31:05 +00001510/// \brief Retrieve the name of the original source file name
1511/// directly from the PCH file, without actually loading the PCH
1512/// file.
1513std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1514 // Open the PCH file.
1515 std::string ErrStr;
1516 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1517 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1518 if (!Buffer) {
1519 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1520 return std::string();
1521 }
1522
1523 // Initialize the stream
1524 llvm::BitstreamReader StreamFile;
1525 llvm::BitstreamCursor Stream;
1526 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1527 (const unsigned char *)Buffer->getBufferEnd());
1528 Stream.init(StreamFile);
1529
1530 // Sniff for the signature.
1531 if (Stream.Read(8) != 'C' ||
1532 Stream.Read(8) != 'P' ||
1533 Stream.Read(8) != 'C' ||
1534 Stream.Read(8) != 'H') {
1535 fprintf(stderr,
1536 "error: '%s' does not appear to be a precompiled header file\n",
1537 PCHFileName.c_str());
1538 return std::string();
1539 }
1540
1541 RecordData Record;
1542 while (!Stream.AtEndOfStream()) {
1543 unsigned Code = Stream.ReadCode();
1544
1545 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1546 unsigned BlockID = Stream.ReadSubBlockID();
1547
1548 // We only know the PCH subblock ID.
1549 switch (BlockID) {
1550 case pch::PCH_BLOCK_ID:
1551 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1552 fprintf(stderr, "error: malformed block record in PCH file\n");
1553 return std::string();
1554 }
1555 break;
1556
1557 default:
1558 if (Stream.SkipBlock()) {
1559 fprintf(stderr, "error: malformed block record in PCH file\n");
1560 return std::string();
1561 }
1562 break;
1563 }
1564 continue;
1565 }
1566
1567 if (Code == llvm::bitc::END_BLOCK) {
1568 if (Stream.ReadBlockEnd()) {
1569 fprintf(stderr, "error: error at end of module block in PCH file\n");
1570 return std::string();
1571 }
1572 continue;
1573 }
1574
1575 if (Code == llvm::bitc::DEFINE_ABBREV) {
1576 Stream.ReadAbbrevRecord();
1577 continue;
1578 }
1579
1580 Record.clear();
1581 const char *BlobStart = 0;
1582 unsigned BlobLen = 0;
1583 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1584 == pch::ORIGINAL_FILE_NAME)
1585 return std::string(BlobStart, BlobLen);
1586 }
1587
1588 return std::string();
1589}
1590
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001591/// \brief Parse the record that corresponds to a LangOptions data
1592/// structure.
1593///
1594/// This routine compares the language options used to generate the
1595/// PCH file against the language options set for the current
1596/// compilation. For each option, we classify differences between the
1597/// two compiler states as either "benign" or "important". Benign
1598/// differences don't matter, and we accept them without complaint
1599/// (and without modifying the language options). Differences between
1600/// the states for important options cause the PCH file to be
1601/// unusable, so we emit a warning and return true to indicate that
1602/// there was an error.
1603///
1604/// \returns true if the PCH file is unacceptable, false otherwise.
1605bool PCHReader::ParseLanguageOptions(
1606 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001607 if (Listener) {
1608 LangOptions LangOpts;
1609
1610 #define PARSE_LANGOPT(Option) \
1611 LangOpts.Option = Record[Idx]; \
1612 ++Idx
1613
1614 unsigned Idx = 0;
1615 PARSE_LANGOPT(Trigraphs);
1616 PARSE_LANGOPT(BCPLComment);
1617 PARSE_LANGOPT(DollarIdents);
1618 PARSE_LANGOPT(AsmPreprocessor);
1619 PARSE_LANGOPT(GNUMode);
1620 PARSE_LANGOPT(ImplicitInt);
1621 PARSE_LANGOPT(Digraphs);
1622 PARSE_LANGOPT(HexFloats);
1623 PARSE_LANGOPT(C99);
1624 PARSE_LANGOPT(Microsoft);
1625 PARSE_LANGOPT(CPlusPlus);
1626 PARSE_LANGOPT(CPlusPlus0x);
1627 PARSE_LANGOPT(CXXOperatorNames);
1628 PARSE_LANGOPT(ObjC1);
1629 PARSE_LANGOPT(ObjC2);
1630 PARSE_LANGOPT(ObjCNonFragileABI);
1631 PARSE_LANGOPT(PascalStrings);
1632 PARSE_LANGOPT(WritableStrings);
1633 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001634 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001635 PARSE_LANGOPT(Exceptions);
1636 PARSE_LANGOPT(NeXTRuntime);
1637 PARSE_LANGOPT(Freestanding);
1638 PARSE_LANGOPT(NoBuiltin);
1639 PARSE_LANGOPT(ThreadsafeStatics);
1640 PARSE_LANGOPT(Blocks);
1641 PARSE_LANGOPT(EmitAllDecls);
1642 PARSE_LANGOPT(MathErrno);
1643 PARSE_LANGOPT(OverflowChecking);
1644 PARSE_LANGOPT(HeinousExtensions);
1645 PARSE_LANGOPT(Optimize);
1646 PARSE_LANGOPT(OptimizeSize);
1647 PARSE_LANGOPT(Static);
1648 PARSE_LANGOPT(PICLevel);
1649 PARSE_LANGOPT(GNUInline);
1650 PARSE_LANGOPT(NoInline);
1651 PARSE_LANGOPT(AccessControl);
1652 PARSE_LANGOPT(CharIsSigned);
1653 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1654 ++Idx;
1655 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1656 ++Idx;
1657 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001658 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001659 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001660
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001661 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001662 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001663
1664 return false;
1665}
1666
Douglas Gregor2cf26342009-04-09 22:27:44 +00001667/// \brief Read and return the type at the given offset.
1668///
1669/// This routine actually reads the record corresponding to the type
1670/// at the given offset in the bitstream. It is a helper routine for
1671/// GetType, which deals with reading type IDs.
1672QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001673 // Keep track of where we are in the stream, then jump back there
1674 // after reading this type.
1675 SavedStreamPosition SavedPosition(Stream);
1676
Douglas Gregor2cf26342009-04-09 22:27:44 +00001677 Stream.JumpToBit(Offset);
1678 RecordData Record;
1679 unsigned Code = Stream.ReadCode();
1680 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001681 case pch::TYPE_EXT_QUAL: {
1682 assert(Record.size() == 3 &&
1683 "Incorrect encoding of extended qualifier type");
1684 QualType Base = GetType(Record[0]);
1685 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1686 unsigned AddressSpace = Record[2];
1687
1688 QualType T = Base;
1689 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001690 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001691 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001692 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001693 return T;
1694 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001695
Douglas Gregor2cf26342009-04-09 22:27:44 +00001696 case pch::TYPE_FIXED_WIDTH_INT: {
1697 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001698 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001699 }
1700
1701 case pch::TYPE_COMPLEX: {
1702 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1703 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001704 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001705 }
1706
1707 case pch::TYPE_POINTER: {
1708 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1709 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001710 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001711 }
1712
1713 case pch::TYPE_BLOCK_POINTER: {
1714 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1715 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001716 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001717 }
1718
1719 case pch::TYPE_LVALUE_REFERENCE: {
1720 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1721 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001722 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001723 }
1724
1725 case pch::TYPE_RVALUE_REFERENCE: {
1726 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1727 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001728 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001729 }
1730
1731 case pch::TYPE_MEMBER_POINTER: {
1732 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1733 QualType PointeeType = GetType(Record[0]);
1734 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001735 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001736 }
1737
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001738 case pch::TYPE_CONSTANT_ARRAY: {
1739 QualType ElementType = GetType(Record[0]);
1740 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1741 unsigned IndexTypeQuals = Record[2];
1742 unsigned Idx = 3;
1743 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001744 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001745 }
1746
1747 case pch::TYPE_INCOMPLETE_ARRAY: {
1748 QualType ElementType = GetType(Record[0]);
1749 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1750 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001751 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001752 }
1753
1754 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001755 QualType ElementType = GetType(Record[0]);
1756 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1757 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001758 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1759 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001760 }
1761
1762 case pch::TYPE_VECTOR: {
1763 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001764 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001765 return QualType();
1766 }
1767
1768 QualType ElementType = GetType(Record[0]);
1769 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001770 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001771 }
1772
1773 case pch::TYPE_EXT_VECTOR: {
1774 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001775 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001776 return QualType();
1777 }
1778
1779 QualType ElementType = GetType(Record[0]);
1780 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001781 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001782 }
1783
1784 case pch::TYPE_FUNCTION_NO_PROTO: {
1785 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001786 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001787 return QualType();
1788 }
1789 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001790 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001791 }
1792
1793 case pch::TYPE_FUNCTION_PROTO: {
1794 QualType ResultType = GetType(Record[0]);
1795 unsigned Idx = 1;
1796 unsigned NumParams = Record[Idx++];
1797 llvm::SmallVector<QualType, 16> ParamTypes;
1798 for (unsigned I = 0; I != NumParams; ++I)
1799 ParamTypes.push_back(GetType(Record[Idx++]));
1800 bool isVariadic = Record[Idx++];
1801 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001802 bool hasExceptionSpec = Record[Idx++];
1803 bool hasAnyExceptionSpec = Record[Idx++];
1804 unsigned NumExceptions = Record[Idx++];
1805 llvm::SmallVector<QualType, 2> Exceptions;
1806 for (unsigned I = 0; I != NumExceptions; ++I)
1807 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001808 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001809 isVariadic, Quals, hasExceptionSpec,
1810 hasAnyExceptionSpec, NumExceptions,
1811 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001812 }
1813
1814 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001815 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001816 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001817
1818 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001819 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001820
1821 case pch::TYPE_TYPEOF: {
1822 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001823 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001824 return QualType();
1825 }
1826 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001827 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001828 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001829
1830 case pch::TYPE_DECLTYPE:
1831 return Context->getDecltypeType(ReadTypeExpr());
1832
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001833 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001834 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001835 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001836
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001837 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001838 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001839 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001840
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001841 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregora02b1472009-04-28 21:53:25 +00001842 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001843 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001844 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001845
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001846 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1847 unsigned Idx = 0;
1848 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1849 unsigned NumProtos = Record[Idx++];
1850 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1851 for (unsigned I = 0; I != NumProtos; ++I)
1852 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Douglas Gregor75fdb232009-05-22 22:45:36 +00001853 return Context->getObjCQualifiedInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001854 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001855
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001856 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001857 unsigned Idx = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001858 ObjCInterfaceDecl *ItfD =
1859 cast_or_null<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001860 unsigned NumProtos = Record[Idx++];
1861 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1862 for (unsigned I = 0; I != NumProtos; ++I)
1863 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001864 return Context->getObjCObjectPointerType(ItfD, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001865 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001866 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001867 // Suppress a GCC warning
1868 return QualType();
1869}
1870
Douglas Gregor2cf26342009-04-09 22:27:44 +00001871
Douglas Gregor8038d512009-04-10 17:25:41 +00001872QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001873 unsigned Quals = ID & 0x07;
1874 unsigned Index = ID >> 3;
1875
1876 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1877 QualType T;
1878 switch ((pch::PredefinedTypeIDs)Index) {
1879 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001880 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1881 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001882
1883 case pch::PREDEF_TYPE_CHAR_U_ID:
1884 case pch::PREDEF_TYPE_CHAR_S_ID:
1885 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001886 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001887 break;
1888
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001889 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1890 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1891 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1892 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1893 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001894 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001895 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1896 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1897 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1898 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1899 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1900 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001901 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001902 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1903 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1904 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1905 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1906 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001907 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001908 }
1909
1910 assert(!T.isNull() && "Unknown predefined type");
1911 return T.getQualifiedType(Quals);
1912 }
1913
1914 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001915 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001916 if (!TypesLoaded[Index])
1917 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001918
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001919 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001920}
1921
Douglas Gregor8038d512009-04-10 17:25:41 +00001922Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001923 if (ID == 0)
1924 return 0;
1925
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001926 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001927 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001928 return 0;
1929 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001930
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001931 unsigned Index = ID - 1;
1932 if (!DeclsLoaded[Index])
1933 ReadDeclRecord(DeclOffsets[Index], Index);
1934
1935 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001936}
1937
Chris Lattner887e2b32009-04-27 05:46:25 +00001938/// \brief Resolve the offset of a statement into a statement.
1939///
1940/// This operation will read a new statement from the external
1941/// source each time it is called, and is meant to be used via a
1942/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1943Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001944 // Since we know tha this statement is part of a decl, make sure to use the
1945 // decl cursor to read it.
1946 DeclsCursor.JumpToBit(Offset);
1947 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001948}
1949
Douglas Gregor2cf26342009-04-09 22:27:44 +00001950bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001951 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001952 assert(DC->hasExternalLexicalStorage() &&
1953 "DeclContext has no lexical decls in storage");
1954 uint64_t Offset = DeclContextOffsets[DC].first;
1955 assert(Offset && "DeclContext has no lexical decls in storage");
1956
Douglas Gregor0b748912009-04-14 21:18:50 +00001957 // Keep track of where we are in the stream, then jump back there
1958 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001959 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001960
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961 // Load the record containing all of the declarations lexically in
1962 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001963 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001964 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001965 unsigned Code = DeclsCursor.ReadCode();
1966 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001967 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001968 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1969
1970 // Load all of the declaration IDs
1971 Decls.clear();
1972 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001973 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001974 return false;
1975}
1976
1977bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001978 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001979 assert(DC->hasExternalVisibleStorage() &&
1980 "DeclContext has no visible decls in storage");
1981 uint64_t Offset = DeclContextOffsets[DC].second;
1982 assert(Offset && "DeclContext has no visible decls in storage");
1983
Douglas Gregor0b748912009-04-14 21:18:50 +00001984 // Keep track of where we are in the stream, then jump back there
1985 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001986 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001987
Douglas Gregor2cf26342009-04-09 22:27:44 +00001988 // Load the record containing all of the declarations visible in
1989 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001990 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001991 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001992 unsigned Code = DeclsCursor.ReadCode();
1993 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001994 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001995 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1996 if (Record.size() == 0)
1997 return false;
1998
1999 Decls.clear();
2000
2001 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002002 while (Idx < Record.size()) {
2003 Decls.push_back(VisibleDeclaration());
2004 Decls.back().Name = ReadDeclarationName(Record, Idx);
2005
Douglas Gregor2cf26342009-04-09 22:27:44 +00002006 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002007 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002008 LoadedDecls.reserve(Size);
2009 for (unsigned I = 0; I < Size; ++I)
2010 LoadedDecls.push_back(Record[Idx++]);
2011 }
2012
Douglas Gregor25123082009-04-22 22:34:57 +00002013 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002014 return false;
2015}
2016
Douglas Gregorfdd01722009-04-14 00:24:19 +00002017void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002018 this->Consumer = Consumer;
2019
Douglas Gregorfdd01722009-04-14 00:24:19 +00002020 if (!Consumer)
2021 return;
2022
2023 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2024 Decl *D = GetDecl(ExternalDefinitions[I]);
2025 DeclGroupRef DG(D);
2026 Consumer->HandleTopLevelDecl(DG);
2027 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002028
2029 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2030 DeclGroupRef DG(InterestingDecls[I]);
2031 Consumer->HandleTopLevelDecl(DG);
2032 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002033}
2034
Douglas Gregor2cf26342009-04-09 22:27:44 +00002035void PCHReader::PrintStats() {
2036 std::fprintf(stderr, "*** PCH Statistics:\n");
2037
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002038 unsigned NumTypesLoaded
2039 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2040 (Type *)0);
2041 unsigned NumDeclsLoaded
2042 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2043 (Decl *)0);
2044 unsigned NumIdentifiersLoaded
2045 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2046 IdentifiersLoaded.end(),
2047 (IdentifierInfo *)0);
2048 unsigned NumSelectorsLoaded
2049 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2050 SelectorsLoaded.end(),
2051 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002052
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002053 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2054 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002055 if (TotalNumSLocEntries)
2056 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2057 NumSLocEntriesRead, TotalNumSLocEntries,
2058 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002059 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002060 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002061 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2062 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2063 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002064 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002065 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2066 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002067 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002068 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002069 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2070 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002071 if (TotalNumSelectors)
2072 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2073 NumSelectorsLoaded, TotalNumSelectors,
2074 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2075 if (TotalNumStatements)
2076 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2077 NumStatementsRead, TotalNumStatements,
2078 ((float)NumStatementsRead/TotalNumStatements * 100));
2079 if (TotalNumMacros)
2080 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2081 NumMacrosRead, TotalNumMacros,
2082 ((float)NumMacrosRead/TotalNumMacros * 100));
2083 if (TotalLexicalDeclContexts)
2084 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2085 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2086 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2087 * 100));
2088 if (TotalVisibleDeclContexts)
2089 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2090 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2091 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2092 * 100));
2093 if (TotalSelectorsInMethodPool) {
2094 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2095 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2096 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2097 * 100));
2098 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2099 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002100 std::fprintf(stderr, "\n");
2101}
2102
Douglas Gregor668c1a42009-04-21 22:25:48 +00002103void PCHReader::InitializeSema(Sema &S) {
2104 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002105 S.ExternalSource = this;
2106
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002107 // Makes sure any declarations that were deserialized "too early"
2108 // still get added to the identifier's declaration chains.
2109 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2110 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2111 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002112 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002113 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002114
2115 // If there were any tentative definitions, deserialize them and add
2116 // them to Sema's table of tentative definitions.
2117 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2118 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2119 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2120 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002121
2122 // If there were any locally-scoped external declarations,
2123 // deserialize them and add them to Sema's table of locally-scoped
2124 // external declarations.
2125 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2126 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2127 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2128 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002129
2130 // If there were any ext_vector type declarations, deserialize them
2131 // and add them to Sema's vector of such declarations.
2132 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2133 SemaObj->ExtVectorDecls.push_back(
2134 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2135
2136 // If there were any Objective-C category implementations,
2137 // deserialize them and add them to Sema's vector of such
2138 // definitions.
2139 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
2140 SemaObj->ObjCCategoryImpls.push_back(
2141 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002142}
2143
2144IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2145 // Try to find this name within our on-disk hash table
2146 PCHIdentifierLookupTable *IdTable
2147 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2148 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2149 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2150 if (Pos == IdTable->end())
2151 return 0;
2152
2153 // Dereferencing the iterator has the effect of building the
2154 // IdentifierInfo node and populating it with the various
2155 // declarations it needs.
2156 return *Pos;
2157}
2158
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002159std::pair<ObjCMethodList, ObjCMethodList>
2160PCHReader::ReadMethodPool(Selector Sel) {
2161 if (!MethodPoolLookupTable)
2162 return std::pair<ObjCMethodList, ObjCMethodList>();
2163
2164 // Try to find this selector within our on-disk hash table.
2165 PCHMethodPoolLookupTable *PoolTable
2166 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2167 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002168 if (Pos == PoolTable->end()) {
2169 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002170 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002171 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002172
Douglas Gregor83941df2009-04-25 17:48:32 +00002173 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002174 return *Pos;
2175}
2176
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002177void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002178 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002179 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002180 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002181}
2182
Chris Lattner7356a312009-04-11 21:15:38 +00002183IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002184 if (ID == 0)
2185 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002186
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002187 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002188 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002189 return 0;
2190 }
Chris Lattner7356a312009-04-11 21:15:38 +00002191
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002192 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002193 if (!IdentifiersLoaded[ID - 1]) {
2194 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002195 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002196
Douglas Gregor02fc7512009-04-28 20:01:51 +00002197 // All of the strings in the PCH file are preceded by a 16-bit
2198 // length. Extract that 16-bit length to avoid having to execute
2199 // strlen().
2200 const char *StrLenPtr = Str - 2;
2201 unsigned StrLen = (((unsigned) StrLenPtr[0])
2202 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2203 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002204 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002205 }
Chris Lattner7356a312009-04-11 21:15:38 +00002206
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002207 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002208}
2209
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002210void PCHReader::ReadSLocEntry(unsigned ID) {
2211 ReadSLocEntryRecord(ID);
2212}
2213
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002214Selector PCHReader::DecodeSelector(unsigned ID) {
2215 if (ID == 0)
2216 return Selector();
2217
Douglas Gregora02b1472009-04-28 21:53:25 +00002218 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002219 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002220
2221 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002222 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002223 return Selector();
2224 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002225
2226 unsigned Index = ID - 1;
2227 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2228 // Load this selector from the selector table.
2229 // FIXME: endianness portability issues with SelectorOffsets table
2230 PCHMethodPoolLookupTrait Trait(*this);
2231 SelectorsLoaded[Index]
2232 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2233 }
2234
2235 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002236}
2237
Douglas Gregor2cf26342009-04-09 22:27:44 +00002238DeclarationName
2239PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2240 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2241 switch (Kind) {
2242 case DeclarationName::Identifier:
2243 return DeclarationName(GetIdentifierInfo(Record, Idx));
2244
2245 case DeclarationName::ObjCZeroArgSelector:
2246 case DeclarationName::ObjCOneArgSelector:
2247 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002248 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002249
2250 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002251 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002252 GetType(Record[Idx++]));
2253
2254 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002255 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002256 GetType(Record[Idx++]));
2257
2258 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002259 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002260 GetType(Record[Idx++]));
2261
2262 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002263 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002264 (OverloadedOperatorKind)Record[Idx++]);
2265
2266 case DeclarationName::CXXUsingDirective:
2267 return DeclarationName::getUsingDirectiveName();
2268 }
2269
2270 // Required to silence GCC warning
2271 return DeclarationName();
2272}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002273
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002274/// \brief Read an integral value
2275llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2276 unsigned BitWidth = Record[Idx++];
2277 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2278 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2279 Idx += NumWords;
2280 return Result;
2281}
2282
2283/// \brief Read a signed integral value
2284llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2285 bool isUnsigned = Record[Idx++];
2286 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2287}
2288
Douglas Gregor17fc2232009-04-14 21:55:33 +00002289/// \brief Read a floating-point value
2290llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002291 return llvm::APFloat(ReadAPInt(Record, Idx));
2292}
2293
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002294// \brief Read a string
2295std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2296 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002297 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002298 Idx += Len;
2299 return Result;
2300}
2301
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002302DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002303 return Diag(SourceLocation(), DiagID);
2304}
2305
2306DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002307 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002308}
Douglas Gregor025452f2009-04-17 00:04:06 +00002309
Douglas Gregor668c1a42009-04-21 22:25:48 +00002310/// \brief Retrieve the identifier table associated with the
2311/// preprocessor.
2312IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002313 assert(PP && "Forgot to set Preprocessor ?");
2314 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002315}
2316
Douglas Gregor025452f2009-04-17 00:04:06 +00002317/// \brief Record that the given ID maps to the given switch-case
2318/// statement.
2319void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2320 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2321 SwitchCaseStmts[ID] = SC;
2322}
2323
2324/// \brief Retrieve the switch-case statement with the given ID.
2325SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2326 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2327 return SwitchCaseStmts[ID];
2328}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002329
2330/// \brief Record that the given label statement has been
2331/// deserialized and has the given ID.
2332void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2333 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2334 "Deserialized label twice");
2335 LabelStmts[ID] = S;
2336
2337 // If we've already seen any goto statements that point to this
2338 // label, resolve them now.
2339 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2340 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2341 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2342 Goto->second->setLabel(S);
2343 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002344
2345 // If we've already seen any address-label statements that point to
2346 // this label, resolve them now.
2347 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2348 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2349 = UnresolvedAddrLabelExprs.equal_range(ID);
2350 for (AddrLabelIter AddrLabel = AddrLabels.first;
2351 AddrLabel != AddrLabels.second; ++AddrLabel)
2352 AddrLabel->second->setLabel(S);
2353 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002354}
2355
2356/// \brief Set the label of the given statement to the label
2357/// identified by ID.
2358///
2359/// Depending on the order in which the label and other statements
2360/// referencing that label occur, this operation may complete
2361/// immediately (updating the statement) or it may queue the
2362/// statement to be back-patched later.
2363void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2364 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2365 if (Label != LabelStmts.end()) {
2366 // We've already seen this label, so set the label of the goto and
2367 // we're done.
2368 S->setLabel(Label->second);
2369 } else {
2370 // We haven't seen this label yet, so add this goto to the set of
2371 // unresolved goto statements.
2372 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2373 }
2374}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002375
2376/// \brief Set the label of the given expression to the label
2377/// identified by ID.
2378///
2379/// Depending on the order in which the label and other statements
2380/// referencing that label occur, this operation may complete
2381/// immediately (updating the statement) or it may queue the
2382/// statement to be back-patched later.
2383void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2384 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2385 if (Label != LabelStmts.end()) {
2386 // We've already seen this label, so set the label of the
2387 // label-address expression and we're done.
2388 S->setLabel(Label->second);
2389 } else {
2390 // We haven't seen this label yet, so add this label-address
2391 // expression to the set of unresolved label-address expressions.
2392 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2393 }
2394}