blob: 44c108210bd27d91703f1236c8e020c34a2aadd4 [file] [log] [blame]
Douglas Gregorc34897d2009-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 Lattner09547942009-04-27 05:14:47 +000013
Douglas Gregorc34897d2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor631f6c62009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-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 Gregor32de6312009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregorc34897d2009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor6cc5d192009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregorc34897d2009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argiris Kirtzidise3f4bda2009-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 Begeman31f83512009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argiris Kirtzidise3f4bda2009-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 Begeman31f83512009-06-25 22:57:40 +0000109 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Argiris Kirtzidise3f4bda2009-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 Gregorc713da92009-04-21 22:25:48 +0000336// PCH reader implementation
337//===----------------------------------------------------------------------===//
338
Chris Lattner270d29a2009-04-27 21:45:14 +0000339PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Argiris Kirtzidise3f4bda2009-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),
Argiris Kirtzidiscae77de2009-06-19 07:55:35 +0000355 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner09547942009-04-27 05:14:47 +0000356 IdentifierTableData(0), IdentifierLookupTable(0),
357 IdentifierOffsets(0),
358 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
359 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000360 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
361 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor32e231c2009-04-27 06:38:32 +0000362 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner09547942009-04-27 05:14:47 +0000363 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
364
365PCHReader::~PCHReader() {}
366
Chris Lattner3ef21962009-04-27 05:58:23 +0000367Expr *PCHReader::ReadDeclExpr() {
368 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
369}
370
371Expr *PCHReader::ReadTypeExpr() {
Chris Lattner3282c392009-04-27 05:41:06 +0000372 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner09547942009-04-27 05:14:47 +0000373}
374
375
Douglas Gregorc713da92009-04-21 22:25:48 +0000376namespace {
Douglas Gregorc3221aa2009-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 Gregor2d711832009-04-25 17:48:32 +0000416 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000417 using namespace clang::io;
Chris Lattner270d29a2009-04-27 21:45:14 +0000418 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc3221aa2009-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 Gregor4e284192009-05-22 22:45:36 +0000432 return SelTable.getSelector(N, Args.data());
Douglas Gregorc3221aa2009-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 Gregorc713da92009-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 Gregor4bb24882009-04-25 20:26:24 +0000520 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor85c4a872009-04-25 21:04:17 +0000521 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregorc713da92009-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 Gregor2c09dad2009-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 Gregor67d91172009-04-28 21:32:13 +0000552 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregorda38c6c2009-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 Gregor2c09dad2009-04-28 21:18:29 +0000563
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000564 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor67d91172009-04-28 21:32:13 +0000565 DataLen -= 6;
Douglas Gregorc713da92009-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 Gregor4bb24882009-04-25 20:26:24 +0000571 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
572 k.first, k.first + k.second);
Douglas Gregorc713da92009-04-21 22:25:48 +0000573 Reader.SetIdentifierInfo(ID, II);
574
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000575 // Set or check the various bits in the IdentifierInfo structure.
576 // FIXME: Load token IDs lazily, too?
Douglas Gregorda38c6c2009-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 Gregore0ad2dd2009-04-21 23:56:24 +0000586 // If this identifier is a macro, deserialize the macro
587 // definition.
588 if (hasMacroDefinition) {
Douglas Gregor67d91172009-04-28 21:32:13 +0000589 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000590 Reader.ReadMacroRecord(Offset);
Douglas Gregor67d91172009-04-28 21:32:13 +0000591 DataLen -= 4;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000592 }
Douglas Gregorc713da92009-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 Lattnerea436b82009-04-27 22:17:41 +0000597 if (Reader.getContext() == 0) return II;
Chris Lattner772a7c12009-04-27 22:02:30 +0000598
Douglas Gregorc713da92009-04-21 22:25:48 +0000599 while (DataLen > 0) {
600 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregorc713da92009-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 Gregor2554cf22009-04-22 21:15:06 +0000611 Reader.PreloadedDecls.push_back(D);
Douglas Gregorc713da92009-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 Gregorc34897d2009-04-09 22:27:44 +0000627// FIXME: use the diagnostics machinery
Douglas Gregoreae710d2009-04-28 21:53:25 +0000628bool PCHReader::Error(const char *Msg) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000629 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
630 Diag(DiagID);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000631 return true;
632}
633
Douglas Gregorb3a04c82009-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) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000654 if (Listener)
655 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
656 SuggestedPredefines);
Douglas Gregor32de6312009-04-28 18:58:38 +0000657 return false;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000658}
659
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000660//===----------------------------------------------------------------------===//
661// Source Manager Deserialization
662//===----------------------------------------------------------------------===//
663
Douglas Gregor635f97f2009-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 Gregor183ad602009-04-13 17:12:42 +0000672 std::map<int, int> FileIDs;
673 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-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 Gregor183ad602009-04-13 17:12:42 +0000678 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
679 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000680 }
681
682 // Parse the line entries
683 std::vector<LineEntry> Entries;
684 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000685 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-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 Gregor6cc5d192009-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 Gregorab1cef72009-04-10 03:52:48 +0000816/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000817PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000818 using namespace SrcMgr;
Douglas Gregor32e231c2009-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 Gregoreae710d2009-04-28 21:53:25 +0000828 Error("malformed block record in PCH file");
Douglas Gregor32e231c2009-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 Gregoreae710d2009-04-28 21:53:25 +0000834 Error("malformed source manager block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000835 return Failure;
836 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000837
Douglas Gregorab1cef72009-04-10 03:52:48 +0000838 RecordData Record;
839 while (true) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000840 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000841 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000842 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000843 Error("error at end of Source Manager block in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000844 return Failure;
845 }
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000846 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000847 }
848
849 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
850 // No known subblocks, always skip them.
Douglas Gregor32e231c2009-04-27 06:38:32 +0000851 SLocEntryCursor.ReadSubBlockID();
852 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000853 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000854 return Failure;
855 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000856 continue;
857 }
858
859 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000860 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000861 continue;
862 }
863
864 // Read a record.
865 const char *BlobStart;
866 unsigned BlobLen;
867 Record.clear();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000868 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000869 default: // Default behavior: ignore.
870 break;
871
Chris Lattnere1be6022009-04-14 23:22:57 +0000872 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000873 if (ParseLineTable(SourceMgr, Record))
874 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000875 break;
Douglas Gregorf6e1fb22009-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];
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000883 if (Listener)
884 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000885 break;
886 }
Douglas Gregor32e231c2009-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 Gregorab1cef72009-04-10 03:52:48 +0000893 }
894 }
895}
896
Douglas Gregor32e231c2009-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 Gregor32e231c2009-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: {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000926 const FileEntry *File = FileMgr.getFile(BlobStart, BlobStart + BlobLen);
Chris Lattner8c5a4772009-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 Gregor32e231c2009-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 Gregor91137812009-04-28 20:33:11 +0000961 if (strcmp(Name, "<built-in>") == 0) {
962 PCHPredefinesBufferID = BufferID;
963 PCHPredefines = BlobStart;
964 PCHPredefinesLen = BlobLen - 1;
965 }
Douglas Gregor32e231c2009-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 Lattner4fc71eb2009-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 Gregoreae710d2009-04-28 21:53:25 +0000992 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000993 return Failure;
994 }
995
Chris Lattner4fc71eb2009-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 Gregore0ad2dd2009-04-21 23:56:24 +00001006void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001007 assert(PP && "Forgot to set Preprocessor ?");
1008
Douglas Gregore0ad2dd2009-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 Naroffcda68f22009-04-24 20:03:17 +00001017
Douglas Gregore0ad2dd2009-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 Gregoreae710d2009-04-28 21:53:25 +00001028 Error("malformed block record in PCH file");
Douglas Gregore0ad2dd2009-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 Gregore0ad2dd2009-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 Gregoreae710d2009-04-28 21:53:25 +00001054 Error("macro must have a name in PCH file");
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001055 return;
1056 }
1057 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1058 bool isUsed = Record[2];
1059
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001060 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregore0ad2dd2009-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 Gregor4e284192009-05-22 22:45:36 +00001076 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001077 PP->getPreprocessorAllocator());
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001078 }
1079
1080 // Finally, install the macro.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001081 PP->setMacroInfo(II, MI);
Douglas Gregore0ad2dd2009-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 Naroffcda68f22009-04-24 20:03:17 +00001106 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001107 }
1108}
1109
Douglas Gregorc713da92009-04-21 22:25:48 +00001110PCHReader::PCHReadResult
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001111PCHReader::ReadPCHBlock() {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001112 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001113 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001114 return Failure;
1115 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001116
1117 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +00001118 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001119 while (!Stream.AtEndOfStream()) {
1120 unsigned Code = Stream.ReadCode();
1121 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001122 if (Stream.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001123 Error("error at end of module block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001124 return Failure;
1125 }
Chris Lattner29241862009-04-11 21:15:38 +00001126
Douglas Gregor179cfb12009-04-10 20:39:37 +00001127 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001128 }
1129
1130 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1131 switch (Stream.ReadSubBlockID()) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001132 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1133 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +00001134 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001135 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001136 return Failure;
1137 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001138 break;
1139
Chris Lattner4fc71eb2009-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 Gregoreae710d2009-04-28 21:53:25 +00001149 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001150 return Failure;
1151 }
1152 break;
1153
Chris Lattner29241862009-04-11 21:15:38 +00001154 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner29241862009-04-11 21:15:38 +00001155 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001156 Error("malformed block record in PCH file");
Chris Lattner29241862009-04-11 21:15:38 +00001157 return Failure;
1158 }
1159 break;
Steve Naroff9e84d782009-04-23 10:39:46 +00001160
Douglas Gregorab1cef72009-04-10 03:52:48 +00001161 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001162 switch (ReadSourceManagerBlock()) {
1163 case Success:
1164 break;
1165
1166 case Failure:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001167 Error("malformed source manager block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001168 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001169
1170 case IgnorePCH:
1171 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001172 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001173 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001174 }
Douglas Gregorac8f2802009-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 Gregorb5887f32009-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 Gregorac8f2802009-04-10 17:25:41 +00001189 default: // Default behavior: ignore.
1190 break;
1191
1192 case pch::TYPE_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001193 if (!TypesLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001194 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001195 return Failure;
1196 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001197 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001198 TypesLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001199 break;
1200
1201 case pch::DECL_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001202 if (!DeclsLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001203 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001204 return Failure;
1205 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001206 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001207 DeclsLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001208 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001209
1210 case pch::LANGUAGE_OPTIONS:
1211 if (ParseLanguageOptions(Record))
1212 return IgnorePCH;
1213 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001214
Douglas Gregorb7064742009-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
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001222 if (Listener) {
1223 std::string TargetTriple(BlobStart, BlobLen);
1224 if (Listener->ReadTargetTriple(TargetTriple))
1225 return IgnorePCH;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001226 }
1227 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001228 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001229
1230 case pch::IDENTIFIER_TABLE:
Douglas Gregorc713da92009-04-21 22:25:48 +00001231 IdentifierTableData = BlobStart;
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001232 if (Record[0]) {
1233 IdentifierLookupTable
1234 = PCHIdentifierLookupTable::Create(
Douglas Gregorc713da92009-04-21 22:25:48 +00001235 (const unsigned char *)IdentifierTableData + Record[0],
1236 (const unsigned char *)IdentifierTableData,
1237 PCHIdentifierLookupTrait(*this));
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001238 if (PP)
1239 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001240 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001241 break;
1242
1243 case pch::IDENTIFIER_OFFSET:
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001244 if (!IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001245 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001246 return Failure;
1247 }
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001248 IdentifierOffsets = (const uint32_t *)BlobStart;
1249 IdentifiersLoaded.resize(Record[0]);
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001250 if (PP)
1251 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001252 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001253
1254 case pch::EXTERNAL_DEFINITIONS:
1255 if (!ExternalDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001256 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor631f6c62009-04-14 00:24:19 +00001257 return Failure;
1258 }
1259 ExternalDefinitions.swap(Record);
1260 break;
Douglas Gregor456e0952009-04-17 22:13:46 +00001261
Douglas Gregore01ad442009-04-18 05:55:16 +00001262 case pch::SPECIAL_TYPES:
1263 SpecialTypes.swap(Record);
1264 break;
1265
Douglas Gregor456e0952009-04-17 22:13:46 +00001266 case pch::STATISTICS:
1267 TotalNumStatements = Record[0];
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001268 TotalNumMacros = Record[1];
Douglas Gregoraf136d92009-04-22 22:34:57 +00001269 TotalLexicalDeclContexts = Record[2];
1270 TotalVisibleDeclContexts = Record[3];
Douglas Gregor456e0952009-04-17 22:13:46 +00001271 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001272
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001273 case pch::TENTATIVE_DEFINITIONS:
1274 if (!TentativeDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001275 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001276 return Failure;
1277 }
1278 TentativeDefinitions.swap(Record);
1279 break;
Douglas Gregor062d9482009-04-22 22:18:58 +00001280
1281 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1282 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001283 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor062d9482009-04-22 22:18:58 +00001284 return Failure;
1285 }
1286 LocallyScopedExternalDecls.swap(Record);
1287 break;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001288
Douglas Gregor2d711832009-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 Gregorc3221aa2009-04-24 21:10:55 +00001295 case pch::METHOD_POOL:
Douglas Gregor2d711832009-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 Gregorc3221aa2009-04-24 21:10:55 +00001302 PCHMethodPoolLookupTrait(*this));
Douglas Gregor2d711832009-04-25 17:48:32 +00001303 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001304 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001305
1306 case pch::PP_COUNTER_VALUE:
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001307 if (!Record.empty() && Listener)
1308 Listener->ReadCounter(Record[0]);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001309 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001310
1311 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner93307da2009-04-27 19:01:47 +00001312 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001313 TotalNumSLocEntries = Record[0];
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001314 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor32e231c2009-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 Gregor6cc5d192009-04-27 18:38:38 +00001326
1327 case pch::STAT_CACHE:
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001328 FileMgr.setStatCache(
Douglas Gregor6cc5d192009-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 Gregorb36b20d2009-04-27 20:06:05 +00001333
1334 case pch::EXT_VECTOR_DECLS:
1335 if (!ExtVectorDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001336 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb36b20d2009-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 Gregoreae710d2009-04-28 21:53:25 +00001344 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001345 return Failure;
1346 }
1347 ObjCCategoryImpls.swap(Record);
1348 break;
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001349
1350 case pch::ORIGINAL_FILE_NAME:
1351 OriginalFileName.assign(BlobStart, BlobLen);
1352 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001353 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001354 }
Douglas Gregoreae710d2009-04-28 21:53:25 +00001355 Error("premature end of bitstream in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001356 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001357}
1358
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001359PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001360 // Set the PCH file name.
1361 this->FileName = FileName;
1362
Douglas Gregorc34897d2009-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 Gregorb3a04c82009-04-10 23:10:45 +00001366 if (!Buffer) {
1367 Error(ErrStr.c_str());
1368 return IgnorePCH;
1369 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001370
1371 // Initialize the stream
Chris Lattner587788a2009-04-26 20:59:20 +00001372 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1373 (const unsigned char *)Buffer->getBufferEnd());
1374 Stream.init(StreamFile);
Douglas Gregorc34897d2009-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 Gregorb3a04c82009-04-10 23:10:45 +00001380 Stream.Read(8) != 'H') {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001381 Diag(diag::err_not_a_pch_file) << FileName;
1382 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001383 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001384
Douglas Gregorc34897d2009-04-09 22:27:44 +00001385 while (!Stream.AtEndOfStream()) {
1386 unsigned Code = Stream.ReadCode();
1387
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001388 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001389 Error("invalid record at top-level of PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001390 return Failure;
1391 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001392
1393 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregorc713da92009-04-21 22:25:48 +00001394
Douglas Gregorc34897d2009-04-09 22:27:44 +00001395 // We only know the PCH subblock ID.
1396 switch (BlockID) {
1397 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001398 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001399 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001400 return Failure;
1401 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001402 break;
1403 case pch::PCH_BLOCK_ID:
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001404 switch (ReadPCHBlock()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001405 case Success:
1406 break;
1407
1408 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001409 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001410
1411 case IgnorePCH:
Douglas Gregorb5887f32009-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 Gregor57885192009-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.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001418 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor57885192009-04-27 21:28:04 +00001419
1420 // Remove the stat cache.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001421 FileMgr.setStatCache(0);
Douglas Gregor57885192009-04-27 21:28:04 +00001422
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001423 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001424 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001425 break;
1426 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001427 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001428 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001429 return Failure;
1430 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001431 break;
1432 }
1433 }
Douglas Gregor91137812009-04-28 20:33:11 +00001434
1435 // Check the predefines buffer.
1436 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1437 PCHPredefinesBufferID))
1438 return IgnorePCH;
1439
Argiris Kirtzidise3f4bda2009-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 Gregorc713da92009-04-21 22:25:48 +00001473 }
1474
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001475 if (Context)
1476 InitializeContext(*Context);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001477
Douglas Gregorc713da92009-04-21 22:25:48 +00001478 return Success;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001479}
1480
Argiris Kirtzidise3f4bda2009-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 Gregoreccf0d12009-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 Gregor179cfb12009-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) {
Argiris Kirtzidise3f4bda2009-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);
1634 PARSE_LANGOPT(Exceptions);
1635 PARSE_LANGOPT(NeXTRuntime);
1636 PARSE_LANGOPT(Freestanding);
1637 PARSE_LANGOPT(NoBuiltin);
1638 PARSE_LANGOPT(ThreadsafeStatics);
1639 PARSE_LANGOPT(Blocks);
1640 PARSE_LANGOPT(EmitAllDecls);
1641 PARSE_LANGOPT(MathErrno);
1642 PARSE_LANGOPT(OverflowChecking);
1643 PARSE_LANGOPT(HeinousExtensions);
1644 PARSE_LANGOPT(Optimize);
1645 PARSE_LANGOPT(OptimizeSize);
1646 PARSE_LANGOPT(Static);
1647 PARSE_LANGOPT(PICLevel);
1648 PARSE_LANGOPT(GNUInline);
1649 PARSE_LANGOPT(NoInline);
1650 PARSE_LANGOPT(AccessControl);
1651 PARSE_LANGOPT(CharIsSigned);
1652 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1653 ++Idx;
1654 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1655 ++Idx;
1656 PARSE_LANGOPT(InstantiationDepth);
1657 #undef PARSE_LANGOPT
Douglas Gregor179cfb12009-04-10 20:39:37 +00001658
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001659 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001660 }
Douglas Gregor179cfb12009-04-10 20:39:37 +00001661
1662 return false;
1663}
1664
Douglas Gregorc34897d2009-04-09 22:27:44 +00001665/// \brief Read and return the type at the given offset.
1666///
1667/// This routine actually reads the record corresponding to the type
1668/// at the given offset in the bitstream. It is a helper routine for
1669/// GetType, which deals with reading type IDs.
1670QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001671 // Keep track of where we are in the stream, then jump back there
1672 // after reading this type.
1673 SavedStreamPosition SavedPosition(Stream);
1674
Douglas Gregorc34897d2009-04-09 22:27:44 +00001675 Stream.JumpToBit(Offset);
1676 RecordData Record;
1677 unsigned Code = Stream.ReadCode();
1678 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001679 case pch::TYPE_EXT_QUAL: {
1680 assert(Record.size() == 3 &&
1681 "Incorrect encoding of extended qualifier type");
1682 QualType Base = GetType(Record[0]);
1683 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1684 unsigned AddressSpace = Record[2];
1685
1686 QualType T = Base;
1687 if (GCAttr != QualType::GCNone)
Chris Lattner270d29a2009-04-27 21:45:14 +00001688 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001689 if (AddressSpace)
Chris Lattner270d29a2009-04-27 21:45:14 +00001690 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001691 return T;
1692 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001693
Douglas Gregorc34897d2009-04-09 22:27:44 +00001694 case pch::TYPE_FIXED_WIDTH_INT: {
1695 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001696 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001697 }
1698
1699 case pch::TYPE_COMPLEX: {
1700 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1701 QualType ElemType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001702 return Context->getComplexType(ElemType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001703 }
1704
1705 case pch::TYPE_POINTER: {
1706 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1707 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001708 return Context->getPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001709 }
1710
1711 case pch::TYPE_BLOCK_POINTER: {
1712 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1713 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001714 return Context->getBlockPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001715 }
1716
1717 case pch::TYPE_LVALUE_REFERENCE: {
1718 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1719 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001720 return Context->getLValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001721 }
1722
1723 case pch::TYPE_RVALUE_REFERENCE: {
1724 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1725 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001726 return Context->getRValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001727 }
1728
1729 case pch::TYPE_MEMBER_POINTER: {
1730 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1731 QualType PointeeType = GetType(Record[0]);
1732 QualType ClassType = GetType(Record[1]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001733 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001734 }
1735
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001736 case pch::TYPE_CONSTANT_ARRAY: {
1737 QualType ElementType = GetType(Record[0]);
1738 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1739 unsigned IndexTypeQuals = Record[2];
1740 unsigned Idx = 3;
1741 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattner270d29a2009-04-27 21:45:14 +00001742 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001743 }
1744
1745 case pch::TYPE_INCOMPLETE_ARRAY: {
1746 QualType ElementType = GetType(Record[0]);
1747 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1748 unsigned IndexTypeQuals = Record[2];
Chris Lattner270d29a2009-04-27 21:45:14 +00001749 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001750 }
1751
1752 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001753 QualType ElementType = GetType(Record[0]);
1754 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1755 unsigned IndexTypeQuals = Record[2];
Chris Lattner270d29a2009-04-27 21:45:14 +00001756 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1757 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001758 }
1759
1760 case pch::TYPE_VECTOR: {
1761 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001762 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001763 return QualType();
1764 }
1765
1766 QualType ElementType = GetType(Record[0]);
1767 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001768 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001769 }
1770
1771 case pch::TYPE_EXT_VECTOR: {
1772 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001773 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001774 return QualType();
1775 }
1776
1777 QualType ElementType = GetType(Record[0]);
1778 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001779 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001780 }
1781
1782 case pch::TYPE_FUNCTION_NO_PROTO: {
1783 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001784 Error("incorrect encoding of no-proto function type");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001785 return QualType();
1786 }
1787 QualType ResultType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001788 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001789 }
1790
1791 case pch::TYPE_FUNCTION_PROTO: {
1792 QualType ResultType = GetType(Record[0]);
1793 unsigned Idx = 1;
1794 unsigned NumParams = Record[Idx++];
1795 llvm::SmallVector<QualType, 16> ParamTypes;
1796 for (unsigned I = 0; I != NumParams; ++I)
1797 ParamTypes.push_back(GetType(Record[Idx++]));
1798 bool isVariadic = Record[Idx++];
1799 unsigned Quals = Record[Idx++];
Sebastian Redl2767d882009-05-27 22:11:52 +00001800 bool hasExceptionSpec = Record[Idx++];
1801 bool hasAnyExceptionSpec = Record[Idx++];
1802 unsigned NumExceptions = Record[Idx++];
1803 llvm::SmallVector<QualType, 2> Exceptions;
1804 for (unsigned I = 0; I != NumExceptions; ++I)
1805 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad9e6bef42009-05-21 09:52:38 +00001806 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl2767d882009-05-27 22:11:52 +00001807 isVariadic, Quals, hasExceptionSpec,
1808 hasAnyExceptionSpec, NumExceptions,
1809 Exceptions.data());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001810 }
1811
1812 case pch::TYPE_TYPEDEF:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001813 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001814 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001815
1816 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner270d29a2009-04-27 21:45:14 +00001817 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001818
1819 case pch::TYPE_TYPEOF: {
1820 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001821 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001822 return QualType();
1823 }
1824 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001825 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001826 }
Anders Carlsson93ab5332009-06-24 19:06:50 +00001827
1828 case pch::TYPE_DECLTYPE:
1829 return Context->getDecltypeType(ReadTypeExpr());
1830
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001831 case pch::TYPE_RECORD:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001832 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001833 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001834
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001835 case pch::TYPE_ENUM:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001836 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001837 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001838
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001839 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001840 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001841 return Context->getObjCInterfaceType(
Chris Lattner80f83c62009-04-22 05:57:30 +00001842 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001843
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001844 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1845 unsigned Idx = 0;
1846 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1847 unsigned NumProtos = Record[Idx++];
1848 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1849 for (unsigned I = 0; I != NumProtos; ++I)
1850 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Douglas Gregor4e284192009-05-22 22:45:36 +00001851 return Context->getObjCQualifiedInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001852 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001853
Steve Naroffc75c1a82009-06-17 22:40:22 +00001854 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner9b9f2352009-04-22 06:40:03 +00001855 unsigned Idx = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001856 ObjCInterfaceDecl *ItfD =
1857 cast_or_null<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
Chris Lattner9b9f2352009-04-22 06:40:03 +00001858 unsigned NumProtos = Record[Idx++];
1859 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1860 for (unsigned I = 0; I != NumProtos; ++I)
1861 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc75c1a82009-06-17 22:40:22 +00001862 return Context->getObjCObjectPointerType(ItfD, Protos.data(), NumProtos);
Chris Lattner9b9f2352009-04-22 06:40:03 +00001863 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001864 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001865 // Suppress a GCC warning
1866 return QualType();
1867}
1868
Douglas Gregorc34897d2009-04-09 22:27:44 +00001869
Douglas Gregorac8f2802009-04-10 17:25:41 +00001870QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001871 unsigned Quals = ID & 0x07;
1872 unsigned Index = ID >> 3;
1873
1874 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1875 QualType T;
1876 switch ((pch::PredefinedTypeIDs)Index) {
1877 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner270d29a2009-04-27 21:45:14 +00001878 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1879 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001880
1881 case pch::PREDEF_TYPE_CHAR_U_ID:
1882 case pch::PREDEF_TYPE_CHAR_S_ID:
1883 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner270d29a2009-04-27 21:45:14 +00001884 T = Context->CharTy;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001885 break;
1886
Chris Lattner270d29a2009-04-27 21:45:14 +00001887 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1888 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1889 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1890 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1891 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001892 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001893 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1894 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1895 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1896 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1897 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1898 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001899 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001900 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1901 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1902 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1903 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1904 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001905 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001906 }
1907
1908 assert(!T.isNull() && "Unknown predefined type");
1909 return T.getQualifiedType(Quals);
1910 }
1911
1912 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregore43f0972009-04-26 03:49:13 +00001913 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001914 if (!TypesLoaded[Index])
1915 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001916
Douglas Gregor24a224c2009-04-25 18:35:21 +00001917 return QualType(TypesLoaded[Index], Quals);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001918}
1919
Douglas Gregorac8f2802009-04-10 17:25:41 +00001920Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001921 if (ID == 0)
1922 return 0;
1923
Douglas Gregor24a224c2009-04-25 18:35:21 +00001924 if (ID > DeclsLoaded.size()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001925 Error("declaration ID out-of-range for PCH file");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001926 return 0;
1927 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001928
Douglas Gregor24a224c2009-04-25 18:35:21 +00001929 unsigned Index = ID - 1;
1930 if (!DeclsLoaded[Index])
1931 ReadDeclRecord(DeclOffsets[Index], Index);
1932
1933 return DeclsLoaded[Index];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001934}
1935
Chris Lattner77055f62009-04-27 05:46:25 +00001936/// \brief Resolve the offset of a statement into a statement.
1937///
1938/// This operation will read a new statement from the external
1939/// source each time it is called, and is meant to be used via a
1940/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1941Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner3ef21962009-04-27 05:58:23 +00001942 // Since we know tha this statement is part of a decl, make sure to use the
1943 // decl cursor to read it.
1944 DeclsCursor.JumpToBit(Offset);
1945 return ReadStmt(DeclsCursor);
Douglas Gregor3b9a7c82009-04-18 00:07:54 +00001946}
1947
Douglas Gregorc34897d2009-04-09 22:27:44 +00001948bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001949 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001950 assert(DC->hasExternalLexicalStorage() &&
1951 "DeclContext has no lexical decls in storage");
1952 uint64_t Offset = DeclContextOffsets[DC].first;
1953 assert(Offset && "DeclContext has no lexical decls in storage");
1954
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001955 // Keep track of where we are in the stream, then jump back there
1956 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001957 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001958
Douglas Gregorc34897d2009-04-09 22:27:44 +00001959 // Load the record containing all of the declarations lexically in
1960 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001961 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001962 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00001963 unsigned Code = DeclsCursor.ReadCode();
1964 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001965 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001966 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1967
1968 // Load all of the declaration IDs
1969 Decls.clear();
1970 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregoraf136d92009-04-22 22:34:57 +00001971 ++NumLexicalDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001972 return false;
1973}
1974
1975bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner85e3f642009-04-27 07:35:40 +00001976 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001977 assert(DC->hasExternalVisibleStorage() &&
1978 "DeclContext has no visible decls in storage");
1979 uint64_t Offset = DeclContextOffsets[DC].second;
1980 assert(Offset && "DeclContext has no visible decls in storage");
1981
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001982 // Keep track of where we are in the stream, then jump back there
1983 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001984 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001985
Douglas Gregorc34897d2009-04-09 22:27:44 +00001986 // Load the record containing all of the declarations visible in
1987 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001988 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001989 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00001990 unsigned Code = DeclsCursor.ReadCode();
1991 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001992 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001993 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1994 if (Record.size() == 0)
1995 return false;
1996
1997 Decls.clear();
1998
1999 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002000 while (Idx < Record.size()) {
2001 Decls.push_back(VisibleDeclaration());
2002 Decls.back().Name = ReadDeclarationName(Record, Idx);
2003
Douglas Gregorc34897d2009-04-09 22:27:44 +00002004 unsigned Size = Record[Idx++];
Chris Lattner85e3f642009-04-27 07:35:40 +00002005 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002006 LoadedDecls.reserve(Size);
2007 for (unsigned I = 0; I < Size; ++I)
2008 LoadedDecls.push_back(Record[Idx++]);
2009 }
2010
Douglas Gregoraf136d92009-04-22 22:34:57 +00002011 ++NumVisibleDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002012 return false;
2013}
2014
Douglas Gregor631f6c62009-04-14 00:24:19 +00002015void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor405b6432009-04-22 19:09:20 +00002016 this->Consumer = Consumer;
2017
Douglas Gregor631f6c62009-04-14 00:24:19 +00002018 if (!Consumer)
2019 return;
2020
2021 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2022 Decl *D = GetDecl(ExternalDefinitions[I]);
2023 DeclGroupRef DG(D);
2024 Consumer->HandleTopLevelDecl(DG);
2025 }
Douglas Gregorf93cfee2009-04-25 00:41:30 +00002026
2027 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2028 DeclGroupRef DG(InterestingDecls[I]);
2029 Consumer->HandleTopLevelDecl(DG);
2030 }
Douglas Gregor631f6c62009-04-14 00:24:19 +00002031}
2032
Douglas Gregorc34897d2009-04-09 22:27:44 +00002033void PCHReader::PrintStats() {
2034 std::fprintf(stderr, "*** PCH Statistics:\n");
2035
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002036 unsigned NumTypesLoaded
2037 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2038 (Type *)0);
2039 unsigned NumDeclsLoaded
2040 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2041 (Decl *)0);
2042 unsigned NumIdentifiersLoaded
2043 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2044 IdentifiersLoaded.end(),
2045 (IdentifierInfo *)0);
2046 unsigned NumSelectorsLoaded
2047 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2048 SelectorsLoaded.end(),
2049 Selector());
Douglas Gregor9cf47422009-04-13 20:50:16 +00002050
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002051 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2052 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor32e231c2009-04-27 06:38:32 +00002053 if (TotalNumSLocEntries)
2054 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2055 NumSLocEntriesRead, TotalNumSLocEntries,
2056 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor24a224c2009-04-25 18:35:21 +00002057 if (!TypesLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002058 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002059 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2060 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2061 if (!DeclsLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002062 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002063 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2064 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002065 if (!IdentifiersLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002066 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002067 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2068 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor2d711832009-04-25 17:48:32 +00002069 if (TotalNumSelectors)
2070 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2071 NumSelectorsLoaded, TotalNumSelectors,
2072 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2073 if (TotalNumStatements)
2074 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2075 NumStatementsRead, TotalNumStatements,
2076 ((float)NumStatementsRead/TotalNumStatements * 100));
2077 if (TotalNumMacros)
2078 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2079 NumMacrosRead, TotalNumMacros,
2080 ((float)NumMacrosRead/TotalNumMacros * 100));
2081 if (TotalLexicalDeclContexts)
2082 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2083 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2084 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2085 * 100));
2086 if (TotalVisibleDeclContexts)
2087 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2088 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2089 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2090 * 100));
2091 if (TotalSelectorsInMethodPool) {
2092 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2093 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2094 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2095 * 100));
2096 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2097 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00002098 std::fprintf(stderr, "\n");
2099}
2100
Douglas Gregorc713da92009-04-21 22:25:48 +00002101void PCHReader::InitializeSema(Sema &S) {
2102 SemaObj = &S;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002103 S.ExternalSource = this;
2104
Douglas Gregor2554cf22009-04-22 21:15:06 +00002105 // Makes sure any declarations that were deserialized "too early"
2106 // still get added to the identifier's declaration chains.
2107 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2108 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2109 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregorc713da92009-04-21 22:25:48 +00002110 }
Douglas Gregor2554cf22009-04-22 21:15:06 +00002111 PreloadedDecls.clear();
Douglas Gregor77b2cd52009-04-22 22:02:47 +00002112
2113 // If there were any tentative definitions, deserialize them and add
2114 // them to Sema's table of tentative definitions.
2115 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2116 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2117 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2118 }
Douglas Gregor062d9482009-04-22 22:18:58 +00002119
2120 // If there were any locally-scoped external declarations,
2121 // deserialize them and add them to Sema's table of locally-scoped
2122 // external declarations.
2123 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2124 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2125 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2126 }
Douglas Gregorb36b20d2009-04-27 20:06:05 +00002127
2128 // If there were any ext_vector type declarations, deserialize them
2129 // and add them to Sema's vector of such declarations.
2130 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2131 SemaObj->ExtVectorDecls.push_back(
2132 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2133
2134 // If there were any Objective-C category implementations,
2135 // deserialize them and add them to Sema's vector of such
2136 // definitions.
2137 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
2138 SemaObj->ObjCCategoryImpls.push_back(
2139 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregorc713da92009-04-21 22:25:48 +00002140}
2141
2142IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2143 // Try to find this name within our on-disk hash table
2144 PCHIdentifierLookupTable *IdTable
2145 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2146 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2147 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2148 if (Pos == IdTable->end())
2149 return 0;
2150
2151 // Dereferencing the iterator has the effect of building the
2152 // IdentifierInfo node and populating it with the various
2153 // declarations it needs.
2154 return *Pos;
2155}
2156
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002157std::pair<ObjCMethodList, ObjCMethodList>
2158PCHReader::ReadMethodPool(Selector Sel) {
2159 if (!MethodPoolLookupTable)
2160 return std::pair<ObjCMethodList, ObjCMethodList>();
2161
2162 // Try to find this selector within our on-disk hash table.
2163 PCHMethodPoolLookupTable *PoolTable
2164 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2165 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor2d711832009-04-25 17:48:32 +00002166 if (Pos == PoolTable->end()) {
2167 ++NumMethodPoolMisses;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002168 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor2d711832009-04-25 17:48:32 +00002169 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002170
Douglas Gregor2d711832009-04-25 17:48:32 +00002171 ++NumMethodPoolSelectorsRead;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002172 return *Pos;
2173}
2174
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002175void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregorc713da92009-04-21 22:25:48 +00002176 assert(ID && "Non-zero identifier ID required");
Douglas Gregoreae710d2009-04-28 21:53:25 +00002177 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002178 IdentifiersLoaded[ID - 1] = II;
Douglas Gregorc713da92009-04-21 22:25:48 +00002179}
2180
Chris Lattner29241862009-04-11 21:15:38 +00002181IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002182 if (ID == 0)
2183 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00002184
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002185 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002186 Error("no identifier table in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002187 return 0;
2188 }
Chris Lattner29241862009-04-11 21:15:38 +00002189
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002190 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002191 if (!IdentifiersLoaded[ID - 1]) {
2192 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002193 const char *Str = IdentifierTableData + Offset;
Douglas Gregor85c4a872009-04-25 21:04:17 +00002194
Douglas Gregor68619772009-04-28 20:01:51 +00002195 // All of the strings in the PCH file are preceded by a 16-bit
2196 // length. Extract that 16-bit length to avoid having to execute
2197 // strlen().
2198 const char *StrLenPtr = Str - 2;
2199 unsigned StrLen = (((unsigned) StrLenPtr[0])
2200 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2201 IdentifiersLoaded[ID - 1]
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002202 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002203 }
Chris Lattner29241862009-04-11 21:15:38 +00002204
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002205 return IdentifiersLoaded[ID - 1];
Douglas Gregorc34897d2009-04-09 22:27:44 +00002206}
2207
Douglas Gregor32e231c2009-04-27 06:38:32 +00002208void PCHReader::ReadSLocEntry(unsigned ID) {
2209 ReadSLocEntryRecord(ID);
2210}
2211
Steve Naroff9e84d782009-04-23 10:39:46 +00002212Selector PCHReader::DecodeSelector(unsigned ID) {
2213 if (ID == 0)
2214 return Selector();
2215
Douglas Gregoreae710d2009-04-28 21:53:25 +00002216 if (!MethodPoolLookupTableData)
Steve Naroff9e84d782009-04-23 10:39:46 +00002217 return Selector();
Douglas Gregor2d711832009-04-25 17:48:32 +00002218
2219 if (ID > TotalNumSelectors) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002220 Error("selector ID out of range in PCH file");
Steve Naroff9e84d782009-04-23 10:39:46 +00002221 return Selector();
2222 }
Douglas Gregor2d711832009-04-25 17:48:32 +00002223
2224 unsigned Index = ID - 1;
2225 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2226 // Load this selector from the selector table.
2227 // FIXME: endianness portability issues with SelectorOffsets table
2228 PCHMethodPoolLookupTrait Trait(*this);
2229 SelectorsLoaded[Index]
2230 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2231 }
2232
2233 return SelectorsLoaded[Index];
Steve Naroff9e84d782009-04-23 10:39:46 +00002234}
2235
Douglas Gregorc34897d2009-04-09 22:27:44 +00002236DeclarationName
2237PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2238 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2239 switch (Kind) {
2240 case DeclarationName::Identifier:
2241 return DeclarationName(GetIdentifierInfo(Record, Idx));
2242
2243 case DeclarationName::ObjCZeroArgSelector:
2244 case DeclarationName::ObjCOneArgSelector:
2245 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff104956f2009-04-23 15:15:40 +00002246 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregorc34897d2009-04-09 22:27:44 +00002247
2248 case DeclarationName::CXXConstructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002249 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002250 GetType(Record[Idx++]));
2251
2252 case DeclarationName::CXXDestructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002253 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002254 GetType(Record[Idx++]));
2255
2256 case DeclarationName::CXXConversionFunctionName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002257 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002258 GetType(Record[Idx++]));
2259
2260 case DeclarationName::CXXOperatorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002261 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002262 (OverloadedOperatorKind)Record[Idx++]);
2263
2264 case DeclarationName::CXXUsingDirective:
2265 return DeclarationName::getUsingDirectiveName();
2266 }
2267
2268 // Required to silence GCC warning
2269 return DeclarationName();
2270}
Douglas Gregor179cfb12009-04-10 20:39:37 +00002271
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00002272/// \brief Read an integral value
2273llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2274 unsigned BitWidth = Record[Idx++];
2275 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2276 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2277 Idx += NumWords;
2278 return Result;
2279}
2280
2281/// \brief Read a signed integral value
2282llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2283 bool isUnsigned = Record[Idx++];
2284 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2285}
2286
Douglas Gregore2f37202009-04-14 21:55:33 +00002287/// \brief Read a floating-point value
2288llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00002289 return llvm::APFloat(ReadAPInt(Record, Idx));
2290}
2291
Douglas Gregor1c507882009-04-15 21:30:51 +00002292// \brief Read a string
2293std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2294 unsigned Len = Record[Idx++];
Jay Foad9e6bef42009-05-21 09:52:38 +00002295 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor1c507882009-04-15 21:30:51 +00002296 Idx += Len;
2297 return Result;
2298}
2299
Douglas Gregor179cfb12009-04-10 20:39:37 +00002300DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002301 return Diag(SourceLocation(), DiagID);
2302}
2303
2304DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002305 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor179cfb12009-04-10 20:39:37 +00002306}
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002307
Douglas Gregorc713da92009-04-21 22:25:48 +00002308/// \brief Retrieve the identifier table associated with the
2309/// preprocessor.
2310IdentifierTable &PCHReader::getIdentifierTable() {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002311 assert(PP && "Forgot to set Preprocessor ?");
2312 return PP->getIdentifierTable();
Douglas Gregorc713da92009-04-21 22:25:48 +00002313}
2314
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002315/// \brief Record that the given ID maps to the given switch-case
2316/// statement.
2317void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2318 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2319 SwitchCaseStmts[ID] = SC;
2320}
2321
2322/// \brief Retrieve the switch-case statement with the given ID.
2323SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2324 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2325 return SwitchCaseStmts[ID];
2326}
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002327
2328/// \brief Record that the given label statement has been
2329/// deserialized and has the given ID.
2330void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2331 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2332 "Deserialized label twice");
2333 LabelStmts[ID] = S;
2334
2335 // If we've already seen any goto statements that point to this
2336 // label, resolve them now.
2337 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2338 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2339 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2340 Goto->second->setLabel(S);
2341 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002342
2343 // If we've already seen any address-label statements that point to
2344 // this label, resolve them now.
2345 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2346 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2347 = UnresolvedAddrLabelExprs.equal_range(ID);
2348 for (AddrLabelIter AddrLabel = AddrLabels.first;
2349 AddrLabel != AddrLabels.second; ++AddrLabel)
2350 AddrLabel->second->setLabel(S);
2351 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002352}
2353
2354/// \brief Set the label of the given statement to the label
2355/// identified by ID.
2356///
2357/// Depending on the order in which the label and other statements
2358/// referencing that label occur, this operation may complete
2359/// immediately (updating the statement) or it may queue the
2360/// statement to be back-patched later.
2361void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2362 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2363 if (Label != LabelStmts.end()) {
2364 // We've already seen this label, so set the label of the goto and
2365 // we're done.
2366 S->setLabel(Label->second);
2367 } else {
2368 // We haven't seen this label yet, so add this goto to the set of
2369 // unresolved goto statements.
2370 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2371 }
2372}
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002373
2374/// \brief Set the label of the given expression to the label
2375/// identified by ID.
2376///
2377/// Depending on the order in which the label and other statements
2378/// referencing that label occur, this operation may complete
2379/// immediately (updating the statement) or it may queue the
2380/// statement to be back-patched later.
2381void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2382 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2383 if (Label != LabelStmts.end()) {
2384 // We've already seen this label, so set the label of the
2385 // label-address expression and we're done.
2386 S->setLabel(Label->second);
2387 } else {
2388 // We haven't seen this label yet, so add this label-address
2389 // expression to the set of unresolved label-address expressions.
2390 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2391 }
2392}