blob: 7d65c4b6580741fb57e7fb7b0f35c9fd62f6550b [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),
Douglas Gregora252b232009-07-02 17:08:52 +0000347 TotalNumSelectors(0), Comments(0), NumComments(0),
348 NumStatHits(0), NumStatMisses(0),
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000349 NumSLocEntriesRead(0), NumStatementsRead(0),
350 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
351 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
352
353PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
354 Diagnostic &Diags)
355 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argiris Kirtzidiscae77de2009-06-19 07:55:35 +0000356 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner09547942009-04-27 05:14:47 +0000357 IdentifierTableData(0), IdentifierLookupTable(0),
358 IdentifierOffsets(0),
359 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
360 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000361 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
362 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor32e231c2009-04-27 06:38:32 +0000363 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner09547942009-04-27 05:14:47 +0000364 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
365
366PCHReader::~PCHReader() {}
367
Chris Lattner3ef21962009-04-27 05:58:23 +0000368Expr *PCHReader::ReadDeclExpr() {
369 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
370}
371
372Expr *PCHReader::ReadTypeExpr() {
Chris Lattner3282c392009-04-27 05:41:06 +0000373 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner09547942009-04-27 05:14:47 +0000374}
375
376
Douglas Gregorc713da92009-04-21 22:25:48 +0000377namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000378class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
379 PCHReader &Reader;
380
381public:
382 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
383
384 typedef Selector external_key_type;
385 typedef external_key_type internal_key_type;
386
387 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
388
389 static bool EqualKey(const internal_key_type& a,
390 const internal_key_type& b) {
391 return a == b;
392 }
393
394 static unsigned ComputeHash(Selector Sel) {
395 unsigned N = Sel.getNumArgs();
396 if (N == 0)
397 ++N;
398 unsigned R = 5381;
399 for (unsigned I = 0; I != N; ++I)
400 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
401 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
402 return R;
403 }
404
405 // This hopefully will just get inlined and removed by the optimizer.
406 static const internal_key_type&
407 GetInternalKey(const external_key_type& x) { return x; }
408
409 static std::pair<unsigned, unsigned>
410 ReadKeyDataLength(const unsigned char*& d) {
411 using namespace clang::io;
412 unsigned KeyLen = ReadUnalignedLE16(d);
413 unsigned DataLen = ReadUnalignedLE16(d);
414 return std::make_pair(KeyLen, DataLen);
415 }
416
Douglas Gregor2d711832009-04-25 17:48:32 +0000417 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000418 using namespace clang::io;
Chris Lattner270d29a2009-04-27 21:45:14 +0000419 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000420 unsigned N = ReadUnalignedLE16(d);
421 IdentifierInfo *FirstII
422 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
423 if (N == 0)
424 return SelTable.getNullarySelector(FirstII);
425 else if (N == 1)
426 return SelTable.getUnarySelector(FirstII);
427
428 llvm::SmallVector<IdentifierInfo *, 16> Args;
429 Args.push_back(FirstII);
430 for (unsigned I = 1; I != N; ++I)
431 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
432
Douglas Gregor4e284192009-05-22 22:45:36 +0000433 return SelTable.getSelector(N, Args.data());
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000434 }
435
436 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
437 using namespace clang::io;
438 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
439 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
440
441 data_type Result;
442
443 // Load instance methods
444 ObjCMethodList *Prev = 0;
445 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
446 ObjCMethodDecl *Method
447 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
448 if (!Result.first.Method) {
449 // This is the first method, which is the easy case.
450 Result.first.Method = Method;
451 Prev = &Result.first;
452 continue;
453 }
454
455 Prev->Next = new ObjCMethodList(Method, 0);
456 Prev = Prev->Next;
457 }
458
459 // Load factory methods
460 Prev = 0;
461 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
462 ObjCMethodDecl *Method
463 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
464 if (!Result.second.Method) {
465 // This is the first method, which is the easy case.
466 Result.second.Method = Method;
467 Prev = &Result.second;
468 continue;
469 }
470
471 Prev->Next = new ObjCMethodList(Method, 0);
472 Prev = Prev->Next;
473 }
474
475 return Result;
476 }
477};
478
479} // end anonymous namespace
480
481/// \brief The on-disk hash table used for the global method pool.
482typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
483 PCHMethodPoolLookupTable;
484
485namespace {
Douglas Gregorc713da92009-04-21 22:25:48 +0000486class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
487 PCHReader &Reader;
488
489 // If we know the IdentifierInfo in advance, it is here and we will
490 // not build a new one. Used when deserializing information about an
491 // identifier that was constructed before the PCH file was read.
492 IdentifierInfo *KnownII;
493
494public:
495 typedef IdentifierInfo * data_type;
496
497 typedef const std::pair<const char*, unsigned> external_key_type;
498
499 typedef external_key_type internal_key_type;
500
501 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
502 : Reader(Reader), KnownII(II) { }
503
504 static bool EqualKey(const internal_key_type& a,
505 const internal_key_type& b) {
506 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
507 : false;
508 }
509
510 static unsigned ComputeHash(const internal_key_type& a) {
511 return BernsteinHash(a.first, a.second);
512 }
513
514 // This hopefully will just get inlined and removed by the optimizer.
515 static const internal_key_type&
516 GetInternalKey(const external_key_type& x) { return x; }
517
518 static std::pair<unsigned, unsigned>
519 ReadKeyDataLength(const unsigned char*& d) {
520 using namespace clang::io;
Douglas Gregor4bb24882009-04-25 20:26:24 +0000521 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor85c4a872009-04-25 21:04:17 +0000522 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregorc713da92009-04-21 22:25:48 +0000523 return std::make_pair(KeyLen, DataLen);
524 }
525
526 static std::pair<const char*, unsigned>
527 ReadKey(const unsigned char* d, unsigned n) {
528 assert(n >= 2 && d[n-1] == '\0');
529 return std::make_pair((const char*) d, n-1);
530 }
531
532 IdentifierInfo *ReadData(const internal_key_type& k,
533 const unsigned char* d,
534 unsigned DataLen) {
535 using namespace clang::io;
Douglas Gregor2c09dad2009-04-28 21:18:29 +0000536 pch::IdentID ID = ReadUnalignedLE32(d);
537 bool IsInteresting = ID & 0x01;
538
539 // Wipe out the "is interesting" bit.
540 ID = ID >> 1;
541
542 if (!IsInteresting) {
543 // For unintersting identifiers, just build the IdentifierInfo
544 // and associate it with the persistent ID.
545 IdentifierInfo *II = KnownII;
546 if (!II)
547 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
548 k.first, k.first + k.second);
549 Reader.SetIdentifierInfo(ID, II);
550 return II;
551 }
552
Douglas Gregor67d91172009-04-28 21:32:13 +0000553 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000554 bool CPlusPlusOperatorKeyword = Bits & 0x01;
555 Bits >>= 1;
556 bool Poisoned = Bits & 0x01;
557 Bits >>= 1;
558 bool ExtensionToken = Bits & 0x01;
559 Bits >>= 1;
560 bool hasMacroDefinition = Bits & 0x01;
561 Bits >>= 1;
562 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
563 Bits >>= 10;
Douglas Gregor2c09dad2009-04-28 21:18:29 +0000564
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000565 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor67d91172009-04-28 21:32:13 +0000566 DataLen -= 6;
Douglas Gregorc713da92009-04-21 22:25:48 +0000567
568 // Build the IdentifierInfo itself and link the identifier ID with
569 // the new IdentifierInfo.
570 IdentifierInfo *II = KnownII;
571 if (!II)
Douglas Gregor4bb24882009-04-25 20:26:24 +0000572 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
573 k.first, k.first + k.second);
Douglas Gregorc713da92009-04-21 22:25:48 +0000574 Reader.SetIdentifierInfo(ID, II);
575
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000576 // Set or check the various bits in the IdentifierInfo structure.
577 // FIXME: Load token IDs lazily, too?
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000578 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
579 assert(II->isExtensionToken() == ExtensionToken &&
580 "Incorrect extension token flag");
581 (void)ExtensionToken;
582 II->setIsPoisoned(Poisoned);
583 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
584 "Incorrect C++ operator keyword flag");
585 (void)CPlusPlusOperatorKeyword;
586
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000587 // If this identifier is a macro, deserialize the macro
588 // definition.
589 if (hasMacroDefinition) {
Douglas Gregor67d91172009-04-28 21:32:13 +0000590 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000591 Reader.ReadMacroRecord(Offset);
Douglas Gregor67d91172009-04-28 21:32:13 +0000592 DataLen -= 4;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000593 }
Douglas Gregorc713da92009-04-21 22:25:48 +0000594
595 // Read all of the declarations visible at global scope with this
596 // name.
597 Sema *SemaObj = Reader.getSema();
Chris Lattnerea436b82009-04-27 22:17:41 +0000598 if (Reader.getContext() == 0) return II;
Chris Lattner772a7c12009-04-27 22:02:30 +0000599
Douglas Gregorc713da92009-04-21 22:25:48 +0000600 while (DataLen > 0) {
601 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregorc713da92009-04-21 22:25:48 +0000602 if (SemaObj) {
603 // Introduce this declaration into the translation-unit scope
604 // and add it to the declaration chain for this identifier, so
605 // that (unqualified) name lookup will find it.
606 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
607 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
608 } else {
609 // Queue this declaration so that it will be added to the
610 // translation unit scope and identifier's declaration chain
611 // once a Sema object is known.
Douglas Gregor2554cf22009-04-22 21:15:06 +0000612 Reader.PreloadedDecls.push_back(D);
Douglas Gregorc713da92009-04-21 22:25:48 +0000613 }
614
615 DataLen -= 4;
616 }
617 return II;
618 }
619};
620
621} // end anonymous namespace
622
623/// \brief The on-disk hash table used to contain information about
624/// all of the identifiers in the program.
625typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
626 PCHIdentifierLookupTable;
627
Douglas Gregorc34897d2009-04-09 22:27:44 +0000628// FIXME: use the diagnostics machinery
Douglas Gregoreae710d2009-04-28 21:53:25 +0000629bool PCHReader::Error(const char *Msg) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000630 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
631 Diag(DiagID);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000632 return true;
633}
634
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000635/// \brief Check the contents of the predefines buffer against the
636/// contents of the predefines buffer used to build the PCH file.
637///
638/// The contents of the two predefines buffers should be the same. If
639/// not, then some command-line option changed the preprocessor state
640/// and we must reject the PCH file.
641///
642/// \param PCHPredef The start of the predefines buffer in the PCH
643/// file.
644///
645/// \param PCHPredefLen The length of the predefines buffer in the PCH
646/// file.
647///
648/// \param PCHBufferID The FileID for the PCH predefines buffer.
649///
650/// \returns true if there was a mismatch (in which case the PCH file
651/// should be ignored), or false otherwise.
652bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
653 unsigned PCHPredefLen,
654 FileID PCHBufferID) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000655 if (Listener)
656 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
657 SuggestedPredefines);
Douglas Gregor32de6312009-04-28 18:58:38 +0000658 return false;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000659}
660
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000661//===----------------------------------------------------------------------===//
662// Source Manager Deserialization
663//===----------------------------------------------------------------------===//
664
Douglas Gregor635f97f2009-04-13 16:31:14 +0000665/// \brief Read the line table in the source manager block.
666/// \returns true if ther was an error.
667static bool ParseLineTable(SourceManager &SourceMgr,
668 llvm::SmallVectorImpl<uint64_t> &Record) {
669 unsigned Idx = 0;
670 LineTableInfo &LineTable = SourceMgr.getLineTable();
671
672 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000673 std::map<int, int> FileIDs;
674 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000675 // Extract the file name
676 unsigned FilenameLen = Record[Idx++];
677 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
678 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000679 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
680 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000681 }
682
683 // Parse the line entries
684 std::vector<LineEntry> Entries;
685 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000686 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000687
688 // Extract the line entries
689 unsigned NumEntries = Record[Idx++];
690 Entries.clear();
691 Entries.reserve(NumEntries);
692 for (unsigned I = 0; I != NumEntries; ++I) {
693 unsigned FileOffset = Record[Idx++];
694 unsigned LineNo = Record[Idx++];
695 int FilenameID = Record[Idx++];
696 SrcMgr::CharacteristicKind FileKind
697 = (SrcMgr::CharacteristicKind)Record[Idx++];
698 unsigned IncludeOffset = Record[Idx++];
699 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
700 FileKind, IncludeOffset));
701 }
702 LineTable.AddEntry(FID, Entries);
703 }
704
705 return false;
706}
707
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000708namespace {
709
710class VISIBILITY_HIDDEN PCHStatData {
711public:
712 const bool hasStat;
713 const ino_t ino;
714 const dev_t dev;
715 const mode_t mode;
716 const time_t mtime;
717 const off_t size;
718
719 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
720 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
721
722 PCHStatData()
723 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
724};
725
726class VISIBILITY_HIDDEN PCHStatLookupTrait {
727 public:
728 typedef const char *external_key_type;
729 typedef const char *internal_key_type;
730
731 typedef PCHStatData data_type;
732
733 static unsigned ComputeHash(const char *path) {
734 return BernsteinHash(path);
735 }
736
737 static internal_key_type GetInternalKey(const char *path) { return path; }
738
739 static bool EqualKey(internal_key_type a, internal_key_type b) {
740 return strcmp(a, b) == 0;
741 }
742
743 static std::pair<unsigned, unsigned>
744 ReadKeyDataLength(const unsigned char*& d) {
745 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
746 unsigned DataLen = (unsigned) *d++;
747 return std::make_pair(KeyLen + 1, DataLen);
748 }
749
750 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
751 return (const char *)d;
752 }
753
754 static data_type ReadData(const internal_key_type, const unsigned char *d,
755 unsigned /*DataLen*/) {
756 using namespace clang::io;
757
758 if (*d++ == 1)
759 return data_type();
760
761 ino_t ino = (ino_t) ReadUnalignedLE32(d);
762 dev_t dev = (dev_t) ReadUnalignedLE32(d);
763 mode_t mode = (mode_t) ReadUnalignedLE16(d);
764 time_t mtime = (time_t) ReadUnalignedLE64(d);
765 off_t size = (off_t) ReadUnalignedLE64(d);
766 return data_type(ino, dev, mode, mtime, size);
767 }
768};
769
770/// \brief stat() cache for precompiled headers.
771///
772/// This cache is very similar to the stat cache used by pretokenized
773/// headers.
774class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
775 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
776 CacheTy *Cache;
777
778 unsigned &NumStatHits, &NumStatMisses;
779public:
780 PCHStatCache(const unsigned char *Buckets,
781 const unsigned char *Base,
782 unsigned &NumStatHits,
783 unsigned &NumStatMisses)
784 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
785 Cache = CacheTy::Create(Buckets, Base);
786 }
787
788 ~PCHStatCache() { delete Cache; }
789
790 int stat(const char *path, struct stat *buf) {
791 // Do the lookup for the file's data in the PCH file.
792 CacheTy::iterator I = Cache->find(path);
793
794 // If we don't get a hit in the PCH file just forward to 'stat'.
795 if (I == Cache->end()) {
796 ++NumStatMisses;
797 return ::stat(path, buf);
798 }
799
800 ++NumStatHits;
801 PCHStatData Data = *I;
802
803 if (!Data.hasStat)
804 return 1;
805
806 buf->st_ino = Data.ino;
807 buf->st_dev = Data.dev;
808 buf->st_mtime = Data.mtime;
809 buf->st_mode = Data.mode;
810 buf->st_size = Data.size;
811 return 0;
812 }
813};
814} // end anonymous namespace
815
816
Douglas Gregorab1cef72009-04-10 03:52:48 +0000817/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000818PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000819 using namespace SrcMgr;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000820
821 // Set the source-location entry cursor to the current position in
822 // the stream. This cursor will be used to read the contents of the
823 // source manager block initially, and then lazily read
824 // source-location entries as needed.
825 SLocEntryCursor = Stream;
826
827 // The stream itself is going to skip over the source manager block.
828 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregor32e231c2009-04-27 06:38:32 +0000830 return Failure;
831 }
832
833 // Enter the source manager block.
834 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000835 Error("malformed source manager block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000836 return Failure;
837 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000838
Douglas Gregorab1cef72009-04-10 03:52:48 +0000839 RecordData Record;
840 while (true) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000841 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000842 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000843 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000844 Error("error at end of Source Manager block in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000845 return Failure;
846 }
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000847 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000848 }
849
850 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
851 // No known subblocks, always skip them.
Douglas Gregor32e231c2009-04-27 06:38:32 +0000852 SLocEntryCursor.ReadSubBlockID();
853 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000854 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000855 return Failure;
856 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000857 continue;
858 }
859
860 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000861 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000862 continue;
863 }
864
865 // Read a record.
866 const char *BlobStart;
867 unsigned BlobLen;
868 Record.clear();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000869 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000870 default: // Default behavior: ignore.
871 break;
872
Chris Lattnere1be6022009-04-14 23:22:57 +0000873 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000874 if (ParseLineTable(SourceMgr, Record))
875 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000876 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000877
878 case pch::SM_HEADER_FILE_INFO: {
879 HeaderFileInfo HFI;
880 HFI.isImport = Record[0];
881 HFI.DirInfo = Record[1];
882 HFI.NumIncludes = Record[2];
883 HFI.ControllingMacroID = Record[3];
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000884 if (Listener)
885 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000886 break;
887 }
Douglas Gregor32e231c2009-04-27 06:38:32 +0000888
889 case pch::SM_SLOC_FILE_ENTRY:
890 case pch::SM_SLOC_BUFFER_ENTRY:
891 case pch::SM_SLOC_INSTANTIATION_ENTRY:
892 // Once we hit one of the source location entries, we're done.
893 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000894 }
895 }
896}
897
Douglas Gregor32e231c2009-04-27 06:38:32 +0000898/// \brief Read in the source location entry with the given ID.
899PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
900 if (ID == 0)
901 return Success;
902
903 if (ID > TotalNumSLocEntries) {
904 Error("source location entry ID out-of-range for PCH file");
905 return Failure;
906 }
907
908 ++NumSLocEntriesRead;
909 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
910 unsigned Code = SLocEntryCursor.ReadCode();
911 if (Code == llvm::bitc::END_BLOCK ||
912 Code == llvm::bitc::ENTER_SUBBLOCK ||
913 Code == llvm::bitc::DEFINE_ABBREV) {
914 Error("incorrectly-formatted source location entry in PCH file");
915 return Failure;
916 }
917
Douglas Gregor32e231c2009-04-27 06:38:32 +0000918 RecordData Record;
919 const char *BlobStart;
920 unsigned BlobLen;
921 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
922 default:
923 Error("incorrectly-formatted source location entry in PCH file");
924 return Failure;
925
926 case pch::SM_SLOC_FILE_ENTRY: {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +0000927 const FileEntry *File = FileMgr.getFile(BlobStart, BlobStart + BlobLen);
Chris Lattner8c5a4772009-06-15 04:35:16 +0000928 if (File == 0) {
929 std::string ErrorStr = "could not find file '";
930 ErrorStr.append(BlobStart, BlobLen);
931 ErrorStr += "' referenced by PCH file";
932 Error(ErrorStr.c_str());
933 return Failure;
934 }
935
Douglas Gregor32e231c2009-04-27 06:38:32 +0000936 FileID FID = SourceMgr.createFileID(File,
937 SourceLocation::getFromRawEncoding(Record[1]),
938 (SrcMgr::CharacteristicKind)Record[2],
939 ID, Record[0]);
940 if (Record[3])
941 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
942 .setHasLineDirectives();
943
944 break;
945 }
946
947 case pch::SM_SLOC_BUFFER_ENTRY: {
948 const char *Name = BlobStart;
949 unsigned Offset = Record[0];
950 unsigned Code = SLocEntryCursor.ReadCode();
951 Record.clear();
952 unsigned RecCode
953 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
954 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
955 (void)RecCode;
956 llvm::MemoryBuffer *Buffer
957 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
958 BlobStart + BlobLen - 1,
959 Name);
960 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
961
Douglas Gregor91137812009-04-28 20:33:11 +0000962 if (strcmp(Name, "<built-in>") == 0) {
963 PCHPredefinesBufferID = BufferID;
964 PCHPredefines = BlobStart;
965 PCHPredefinesLen = BlobLen - 1;
966 }
Douglas Gregor32e231c2009-04-27 06:38:32 +0000967
968 break;
969 }
970
971 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
972 SourceLocation SpellingLoc
973 = SourceLocation::getFromRawEncoding(Record[1]);
974 SourceMgr.createInstantiationLoc(SpellingLoc,
975 SourceLocation::getFromRawEncoding(Record[2]),
976 SourceLocation::getFromRawEncoding(Record[3]),
977 Record[4],
978 ID,
979 Record[0]);
980 break;
981 }
982 }
983
984 return Success;
985}
986
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000987/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
988/// specified cursor. Read the abbreviations that are at the top of the block
989/// and then leave the cursor pointing into the block.
990bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
991 unsigned BlockID) {
992 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000993 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000994 return Failure;
995 }
996
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000997 while (true) {
998 unsigned Code = Cursor.ReadCode();
999
1000 // We expect all abbrevs to be at the start of the block.
1001 if (Code != llvm::bitc::DEFINE_ABBREV)
1002 return false;
1003 Cursor.ReadAbbrevRecord();
1004 }
1005}
1006
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001007void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001008 assert(PP && "Forgot to set Preprocessor ?");
1009
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001010 // Keep track of where we are in the stream, then jump back there
1011 // after reading this macro.
1012 SavedStreamPosition SavedPosition(Stream);
1013
1014 Stream.JumpToBit(Offset);
1015 RecordData Record;
1016 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1017 MacroInfo *Macro = 0;
Steve Naroffcda68f22009-04-24 20:03:17 +00001018
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001019 while (true) {
1020 unsigned Code = Stream.ReadCode();
1021 switch (Code) {
1022 case llvm::bitc::END_BLOCK:
1023 return;
1024
1025 case llvm::bitc::ENTER_SUBBLOCK:
1026 // No known subblocks, always skip them.
1027 Stream.ReadSubBlockID();
1028 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001029 Error("malformed block record in PCH file");
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001030 return;
1031 }
1032 continue;
1033
1034 case llvm::bitc::DEFINE_ABBREV:
1035 Stream.ReadAbbrevRecord();
1036 continue;
1037 default: break;
1038 }
1039
1040 // Read a record.
1041 Record.clear();
1042 pch::PreprocessorRecordTypes RecType =
1043 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1044 switch (RecType) {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001045 case pch::PP_MACRO_OBJECT_LIKE:
1046 case pch::PP_MACRO_FUNCTION_LIKE: {
1047 // If we already have a macro, that means that we've hit the end
1048 // of the definition of the macro we were looking for. We're
1049 // done.
1050 if (Macro)
1051 return;
1052
1053 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1054 if (II == 0) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001055 Error("macro must have a name in PCH file");
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001056 return;
1057 }
1058 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1059 bool isUsed = Record[2];
1060
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001061 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001062 MI->setIsUsed(isUsed);
1063
1064 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1065 // Decode function-like macro info.
1066 bool isC99VarArgs = Record[3];
1067 bool isGNUVarArgs = Record[4];
1068 MacroArgs.clear();
1069 unsigned NumArgs = Record[5];
1070 for (unsigned i = 0; i != NumArgs; ++i)
1071 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1072
1073 // Install function-like macro info.
1074 MI->setIsFunctionLike();
1075 if (isC99VarArgs) MI->setIsC99Varargs();
1076 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor4e284192009-05-22 22:45:36 +00001077 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001078 PP->getPreprocessorAllocator());
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001079 }
1080
1081 // Finally, install the macro.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001082 PP->setMacroInfo(II, MI);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001083
1084 // Remember that we saw this macro last so that we add the tokens that
1085 // form its body to it.
1086 Macro = MI;
1087 ++NumMacrosRead;
1088 break;
1089 }
1090
1091 case pch::PP_TOKEN: {
1092 // If we see a TOKEN before a PP_MACRO_*, then the file is
1093 // erroneous, just pretend we didn't see this.
1094 if (Macro == 0) break;
1095
1096 Token Tok;
1097 Tok.startToken();
1098 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1099 Tok.setLength(Record[1]);
1100 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1101 Tok.setIdentifierInfo(II);
1102 Tok.setKind((tok::TokenKind)Record[3]);
1103 Tok.setFlag((Token::TokenFlags)Record[4]);
1104 Macro->AddTokenToBody(Tok);
1105 break;
1106 }
Steve Naroffcda68f22009-04-24 20:03:17 +00001107 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001108 }
1109}
1110
Douglas Gregorc713da92009-04-21 22:25:48 +00001111PCHReader::PCHReadResult
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001112PCHReader::ReadPCHBlock() {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001113 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001114 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001115 return Failure;
1116 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001117
1118 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +00001119 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001120 while (!Stream.AtEndOfStream()) {
1121 unsigned Code = Stream.ReadCode();
1122 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001123 if (Stream.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001124 Error("error at end of module block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001125 return Failure;
1126 }
Chris Lattner29241862009-04-11 21:15:38 +00001127
Douglas Gregor179cfb12009-04-10 20:39:37 +00001128 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001129 }
1130
1131 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1132 switch (Stream.ReadSubBlockID()) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001133 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1134 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +00001135 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001136 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001137 return Failure;
1138 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001139 break;
1140
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001141 case pch::DECLS_BLOCK_ID:
1142 // We lazily load the decls block, but we want to set up the
1143 // DeclsCursor cursor to point into it. Clone our current bitcode
1144 // cursor to it, enter the block and read the abbrevs in that block.
1145 // With the main cursor, we just skip over it.
1146 DeclsCursor = Stream;
1147 if (Stream.SkipBlock() || // Skip with the main cursor.
1148 // Read the abbrevs.
1149 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001150 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001151 return Failure;
1152 }
1153 break;
1154
Chris Lattner29241862009-04-11 21:15:38 +00001155 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner29241862009-04-11 21:15:38 +00001156 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001157 Error("malformed block record in PCH file");
Chris Lattner29241862009-04-11 21:15:38 +00001158 return Failure;
1159 }
1160 break;
Steve Naroff9e84d782009-04-23 10:39:46 +00001161
Douglas Gregorab1cef72009-04-10 03:52:48 +00001162 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001163 switch (ReadSourceManagerBlock()) {
1164 case Success:
1165 break;
1166
1167 case Failure:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001168 Error("malformed source manager block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001169 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001170
1171 case IgnorePCH:
1172 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001173 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001174 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001175 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001176 continue;
1177 }
1178
1179 if (Code == llvm::bitc::DEFINE_ABBREV) {
1180 Stream.ReadAbbrevRecord();
1181 continue;
1182 }
1183
1184 // Read and process a record.
1185 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +00001186 const char *BlobStart = 0;
1187 unsigned BlobLen = 0;
1188 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1189 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001190 default: // Default behavior: ignore.
1191 break;
1192
1193 case pch::TYPE_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001194 if (!TypesLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001195 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001196 return Failure;
1197 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001198 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001199 TypesLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001200 break;
1201
1202 case pch::DECL_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001203 if (!DeclsLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001204 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001205 return Failure;
1206 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001207 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001208 DeclsLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001209 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001210
1211 case pch::LANGUAGE_OPTIONS:
1212 if (ParseLanguageOptions(Record))
1213 return IgnorePCH;
1214 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001215
Douglas Gregorb7064742009-04-27 22:23:34 +00001216 case pch::METADATA: {
1217 if (Record[0] != pch::VERSION_MAJOR) {
1218 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1219 : diag::warn_pch_version_too_new);
1220 return IgnorePCH;
1221 }
1222
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001223 if (Listener) {
1224 std::string TargetTriple(BlobStart, BlobLen);
1225 if (Listener->ReadTargetTriple(TargetTriple))
1226 return IgnorePCH;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001227 }
1228 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001229 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001230
1231 case pch::IDENTIFIER_TABLE:
Douglas Gregorc713da92009-04-21 22:25:48 +00001232 IdentifierTableData = BlobStart;
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001233 if (Record[0]) {
1234 IdentifierLookupTable
1235 = PCHIdentifierLookupTable::Create(
Douglas Gregorc713da92009-04-21 22:25:48 +00001236 (const unsigned char *)IdentifierTableData + Record[0],
1237 (const unsigned char *)IdentifierTableData,
1238 PCHIdentifierLookupTrait(*this));
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001239 if (PP)
1240 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001241 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001242 break;
1243
1244 case pch::IDENTIFIER_OFFSET:
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001245 if (!IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001246 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001247 return Failure;
1248 }
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001249 IdentifierOffsets = (const uint32_t *)BlobStart;
1250 IdentifiersLoaded.resize(Record[0]);
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001251 if (PP)
1252 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001253 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001254
1255 case pch::EXTERNAL_DEFINITIONS:
1256 if (!ExternalDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001257 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor631f6c62009-04-14 00:24:19 +00001258 return Failure;
1259 }
1260 ExternalDefinitions.swap(Record);
1261 break;
Douglas Gregor456e0952009-04-17 22:13:46 +00001262
Douglas Gregore01ad442009-04-18 05:55:16 +00001263 case pch::SPECIAL_TYPES:
1264 SpecialTypes.swap(Record);
1265 break;
1266
Douglas Gregor456e0952009-04-17 22:13:46 +00001267 case pch::STATISTICS:
1268 TotalNumStatements = Record[0];
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001269 TotalNumMacros = Record[1];
Douglas Gregoraf136d92009-04-22 22:34:57 +00001270 TotalLexicalDeclContexts = Record[2];
1271 TotalVisibleDeclContexts = Record[3];
Douglas Gregor456e0952009-04-17 22:13:46 +00001272 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001273
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001274 case pch::TENTATIVE_DEFINITIONS:
1275 if (!TentativeDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001276 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001277 return Failure;
1278 }
1279 TentativeDefinitions.swap(Record);
1280 break;
Douglas Gregor062d9482009-04-22 22:18:58 +00001281
1282 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1283 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001284 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor062d9482009-04-22 22:18:58 +00001285 return Failure;
1286 }
1287 LocallyScopedExternalDecls.swap(Record);
1288 break;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001289
Douglas Gregor2d711832009-04-25 17:48:32 +00001290 case pch::SELECTOR_OFFSETS:
1291 SelectorOffsets = (const uint32_t *)BlobStart;
1292 TotalNumSelectors = Record[0];
1293 SelectorsLoaded.resize(TotalNumSelectors);
1294 break;
1295
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001296 case pch::METHOD_POOL:
Douglas Gregor2d711832009-04-25 17:48:32 +00001297 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1298 if (Record[0])
1299 MethodPoolLookupTable
1300 = PCHMethodPoolLookupTable::Create(
1301 MethodPoolLookupTableData + Record[0],
1302 MethodPoolLookupTableData,
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001303 PCHMethodPoolLookupTrait(*this));
Douglas Gregor2d711832009-04-25 17:48:32 +00001304 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001305 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001306
1307 case pch::PP_COUNTER_VALUE:
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001308 if (!Record.empty() && Listener)
1309 Listener->ReadCounter(Record[0]);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001310 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001311
1312 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner93307da2009-04-27 19:01:47 +00001313 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001314 TotalNumSLocEntries = Record[0];
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001315 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor32e231c2009-04-27 06:38:32 +00001316 TotalNumSLocEntries,
1317 Record[1]);
1318 break;
1319
1320 case pch::SOURCE_LOCATION_PRELOADS:
1321 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1322 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1323 if (Result != Success)
1324 return Result;
1325 }
1326 break;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001327
1328 case pch::STAT_CACHE:
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001329 FileMgr.setStatCache(
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001330 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1331 (const unsigned char *)BlobStart,
1332 NumStatHits, NumStatMisses));
1333 break;
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001334
1335 case pch::EXT_VECTOR_DECLS:
1336 if (!ExtVectorDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001337 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001338 return Failure;
1339 }
1340 ExtVectorDecls.swap(Record);
1341 break;
1342
1343 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1344 if (!ObjCCategoryImpls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001345 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001346 return Failure;
1347 }
1348 ObjCCategoryImpls.swap(Record);
1349 break;
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001350
1351 case pch::ORIGINAL_FILE_NAME:
1352 OriginalFileName.assign(BlobStart, BlobLen);
1353 break;
Douglas Gregora252b232009-07-02 17:08:52 +00001354
1355 case pch::COMMENT_RANGES:
1356 Comments = (SourceRange *)BlobStart;
1357 NumComments = BlobLen / sizeof(SourceRange);
1358 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001359 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001360 }
Douglas Gregoreae710d2009-04-28 21:53:25 +00001361 Error("premature end of bitstream in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001362 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001363}
1364
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001365PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001366 // Set the PCH file name.
1367 this->FileName = FileName;
1368
Douglas Gregorc34897d2009-04-09 22:27:44 +00001369 // Open the PCH file.
1370 std::string ErrStr;
1371 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001372 if (!Buffer) {
1373 Error(ErrStr.c_str());
1374 return IgnorePCH;
1375 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001376
1377 // Initialize the stream
Chris Lattner587788a2009-04-26 20:59:20 +00001378 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1379 (const unsigned char *)Buffer->getBufferEnd());
1380 Stream.init(StreamFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001381
1382 // Sniff for the signature.
1383 if (Stream.Read(8) != 'C' ||
1384 Stream.Read(8) != 'P' ||
1385 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001386 Stream.Read(8) != 'H') {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001387 Diag(diag::err_not_a_pch_file) << FileName;
1388 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001389 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001390
Douglas Gregorc34897d2009-04-09 22:27:44 +00001391 while (!Stream.AtEndOfStream()) {
1392 unsigned Code = Stream.ReadCode();
1393
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001394 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001395 Error("invalid record at top-level of PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001396 return Failure;
1397 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001398
1399 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregorc713da92009-04-21 22:25:48 +00001400
Douglas Gregorc34897d2009-04-09 22:27:44 +00001401 // We only know the PCH subblock ID.
1402 switch (BlockID) {
1403 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001404 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001405 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001406 return Failure;
1407 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001408 break;
1409 case pch::PCH_BLOCK_ID:
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001410 switch (ReadPCHBlock()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001411 case Success:
1412 break;
1413
1414 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001415 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001416
1417 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001418 // FIXME: We could consider reading through to the end of this
1419 // PCH block, skipping subblocks, to see if there are other
1420 // PCH blocks elsewhere.
Douglas Gregor57885192009-04-27 21:28:04 +00001421
1422 // Clear out any preallocated source location entries, so that
1423 // the source manager does not try to resolve them later.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001424 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor57885192009-04-27 21:28:04 +00001425
1426 // Remove the stat cache.
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001427 FileMgr.setStatCache(0);
Douglas Gregor57885192009-04-27 21:28:04 +00001428
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001429 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001430 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001431 break;
1432 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001433 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001434 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001435 return Failure;
1436 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001437 break;
1438 }
1439 }
Douglas Gregor91137812009-04-28 20:33:11 +00001440
1441 // Check the predefines buffer.
1442 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1443 PCHPredefinesBufferID))
1444 return IgnorePCH;
1445
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001446 if (PP) {
1447 // Initialization of builtins and library builtins occurs before the
1448 // PCH file is read, so there may be some identifiers that were
1449 // loaded into the IdentifierTable before we intercepted the
1450 // creation of identifiers. Iterate through the list of known
1451 // identifiers and determine whether we have to establish
1452 // preprocessor definitions or top-level identifier declaration
1453 // chains for those identifiers.
1454 //
1455 // We copy the IdentifierInfo pointers to a small vector first,
1456 // since de-serializing declarations or macro definitions can add
1457 // new entries into the identifier table, invalidating the
1458 // iterators.
1459 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1460 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1461 IdEnd = PP->getIdentifierTable().end();
1462 Id != IdEnd; ++Id)
1463 Identifiers.push_back(Id->second);
1464 PCHIdentifierLookupTable *IdTable
1465 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1466 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1467 IdentifierInfo *II = Identifiers[I];
1468 // Look in the on-disk hash table for an entry for
1469 PCHIdentifierLookupTrait Info(*this, II);
1470 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1471 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1472 if (Pos == IdTable->end())
1473 continue;
1474
1475 // Dereferencing the iterator has the effect of populating the
1476 // IdentifierInfo node with the various declarations it needs.
1477 (void)*Pos;
1478 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001479 }
1480
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001481 if (Context)
1482 InitializeContext(*Context);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001483
Douglas Gregorc713da92009-04-21 22:25:48 +00001484 return Success;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001485}
1486
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001487void PCHReader::InitializeContext(ASTContext &Ctx) {
1488 Context = &Ctx;
1489 assert(Context && "Passed null context!");
1490
1491 assert(PP && "Forgot to set Preprocessor ?");
1492 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1493 PP->getHeaderSearchInfo().SetExternalLookup(this);
1494
1495 // Load the translation unit declaration
1496 ReadDeclRecord(DeclOffsets[0], 0);
1497
1498 // Load the special types.
1499 Context->setBuiltinVaListType(
1500 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1501 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1502 Context->setObjCIdType(GetType(Id));
1503 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1504 Context->setObjCSelType(GetType(Sel));
1505 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1506 Context->setObjCProtoType(GetType(Proto));
1507 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1508 Context->setObjCClassType(GetType(Class));
1509 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1510 Context->setCFConstantStringType(GetType(String));
1511 if (unsigned FastEnum
1512 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1513 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1514}
1515
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001516/// \brief Retrieve the name of the original source file name
1517/// directly from the PCH file, without actually loading the PCH
1518/// file.
1519std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1520 // Open the PCH file.
1521 std::string ErrStr;
1522 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1523 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1524 if (!Buffer) {
1525 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1526 return std::string();
1527 }
1528
1529 // Initialize the stream
1530 llvm::BitstreamReader StreamFile;
1531 llvm::BitstreamCursor Stream;
1532 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1533 (const unsigned char *)Buffer->getBufferEnd());
1534 Stream.init(StreamFile);
1535
1536 // Sniff for the signature.
1537 if (Stream.Read(8) != 'C' ||
1538 Stream.Read(8) != 'P' ||
1539 Stream.Read(8) != 'C' ||
1540 Stream.Read(8) != 'H') {
1541 fprintf(stderr,
1542 "error: '%s' does not appear to be a precompiled header file\n",
1543 PCHFileName.c_str());
1544 return std::string();
1545 }
1546
1547 RecordData Record;
1548 while (!Stream.AtEndOfStream()) {
1549 unsigned Code = Stream.ReadCode();
1550
1551 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1552 unsigned BlockID = Stream.ReadSubBlockID();
1553
1554 // We only know the PCH subblock ID.
1555 switch (BlockID) {
1556 case pch::PCH_BLOCK_ID:
1557 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1558 fprintf(stderr, "error: malformed block record in PCH file\n");
1559 return std::string();
1560 }
1561 break;
1562
1563 default:
1564 if (Stream.SkipBlock()) {
1565 fprintf(stderr, "error: malformed block record in PCH file\n");
1566 return std::string();
1567 }
1568 break;
1569 }
1570 continue;
1571 }
1572
1573 if (Code == llvm::bitc::END_BLOCK) {
1574 if (Stream.ReadBlockEnd()) {
1575 fprintf(stderr, "error: error at end of module block in PCH file\n");
1576 return std::string();
1577 }
1578 continue;
1579 }
1580
1581 if (Code == llvm::bitc::DEFINE_ABBREV) {
1582 Stream.ReadAbbrevRecord();
1583 continue;
1584 }
1585
1586 Record.clear();
1587 const char *BlobStart = 0;
1588 unsigned BlobLen = 0;
1589 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1590 == pch::ORIGINAL_FILE_NAME)
1591 return std::string(BlobStart, BlobLen);
1592 }
1593
1594 return std::string();
1595}
1596
Douglas Gregor179cfb12009-04-10 20:39:37 +00001597/// \brief Parse the record that corresponds to a LangOptions data
1598/// structure.
1599///
1600/// This routine compares the language options used to generate the
1601/// PCH file against the language options set for the current
1602/// compilation. For each option, we classify differences between the
1603/// two compiler states as either "benign" or "important". Benign
1604/// differences don't matter, and we accept them without complaint
1605/// (and without modifying the language options). Differences between
1606/// the states for important options cause the PCH file to be
1607/// unusable, so we emit a warning and return true to indicate that
1608/// there was an error.
1609///
1610/// \returns true if the PCH file is unacceptable, false otherwise.
1611bool PCHReader::ParseLanguageOptions(
1612 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001613 if (Listener) {
1614 LangOptions LangOpts;
1615
1616 #define PARSE_LANGOPT(Option) \
1617 LangOpts.Option = Record[Idx]; \
1618 ++Idx
1619
1620 unsigned Idx = 0;
1621 PARSE_LANGOPT(Trigraphs);
1622 PARSE_LANGOPT(BCPLComment);
1623 PARSE_LANGOPT(DollarIdents);
1624 PARSE_LANGOPT(AsmPreprocessor);
1625 PARSE_LANGOPT(GNUMode);
1626 PARSE_LANGOPT(ImplicitInt);
1627 PARSE_LANGOPT(Digraphs);
1628 PARSE_LANGOPT(HexFloats);
1629 PARSE_LANGOPT(C99);
1630 PARSE_LANGOPT(Microsoft);
1631 PARSE_LANGOPT(CPlusPlus);
1632 PARSE_LANGOPT(CPlusPlus0x);
1633 PARSE_LANGOPT(CXXOperatorNames);
1634 PARSE_LANGOPT(ObjC1);
1635 PARSE_LANGOPT(ObjC2);
1636 PARSE_LANGOPT(ObjCNonFragileABI);
1637 PARSE_LANGOPT(PascalStrings);
1638 PARSE_LANGOPT(WritableStrings);
1639 PARSE_LANGOPT(LaxVectorConversions);
Nate Begeman909e06e2009-06-25 23:01:11 +00001640 PARSE_LANGOPT(AltiVec);
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001641 PARSE_LANGOPT(Exceptions);
1642 PARSE_LANGOPT(NeXTRuntime);
1643 PARSE_LANGOPT(Freestanding);
1644 PARSE_LANGOPT(NoBuiltin);
1645 PARSE_LANGOPT(ThreadsafeStatics);
1646 PARSE_LANGOPT(Blocks);
1647 PARSE_LANGOPT(EmitAllDecls);
1648 PARSE_LANGOPT(MathErrno);
1649 PARSE_LANGOPT(OverflowChecking);
1650 PARSE_LANGOPT(HeinousExtensions);
1651 PARSE_LANGOPT(Optimize);
1652 PARSE_LANGOPT(OptimizeSize);
1653 PARSE_LANGOPT(Static);
1654 PARSE_LANGOPT(PICLevel);
1655 PARSE_LANGOPT(GNUInline);
1656 PARSE_LANGOPT(NoInline);
1657 PARSE_LANGOPT(AccessControl);
1658 PARSE_LANGOPT(CharIsSigned);
1659 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1660 ++Idx;
1661 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1662 ++Idx;
1663 PARSE_LANGOPT(InstantiationDepth);
Nate Begeman909e06e2009-06-25 23:01:11 +00001664 PARSE_LANGOPT(OpenCL);
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001665 #undef PARSE_LANGOPT
Douglas Gregor179cfb12009-04-10 20:39:37 +00001666
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00001667 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001668 }
Douglas Gregor179cfb12009-04-10 20:39:37 +00001669
1670 return false;
1671}
1672
Douglas Gregora252b232009-07-02 17:08:52 +00001673void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1674 Comments.resize(NumComments);
1675 std::copy(this->Comments, this->Comments + NumComments,
1676 Comments.begin());
1677}
1678
Douglas Gregorc34897d2009-04-09 22:27:44 +00001679/// \brief Read and return the type at the given offset.
1680///
1681/// This routine actually reads the record corresponding to the type
1682/// at the given offset in the bitstream. It is a helper routine for
1683/// GetType, which deals with reading type IDs.
1684QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001685 // Keep track of where we are in the stream, then jump back there
1686 // after reading this type.
1687 SavedStreamPosition SavedPosition(Stream);
1688
Douglas Gregorc34897d2009-04-09 22:27:44 +00001689 Stream.JumpToBit(Offset);
1690 RecordData Record;
1691 unsigned Code = Stream.ReadCode();
1692 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001693 case pch::TYPE_EXT_QUAL: {
1694 assert(Record.size() == 3 &&
1695 "Incorrect encoding of extended qualifier type");
1696 QualType Base = GetType(Record[0]);
1697 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1698 unsigned AddressSpace = Record[2];
1699
1700 QualType T = Base;
1701 if (GCAttr != QualType::GCNone)
Chris Lattner270d29a2009-04-27 21:45:14 +00001702 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001703 if (AddressSpace)
Chris Lattner270d29a2009-04-27 21:45:14 +00001704 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001705 return T;
1706 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001707
Douglas Gregorc34897d2009-04-09 22:27:44 +00001708 case pch::TYPE_FIXED_WIDTH_INT: {
1709 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001710 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001711 }
1712
1713 case pch::TYPE_COMPLEX: {
1714 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1715 QualType ElemType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001716 return Context->getComplexType(ElemType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001717 }
1718
1719 case pch::TYPE_POINTER: {
1720 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1721 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001722 return Context->getPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001723 }
1724
1725 case pch::TYPE_BLOCK_POINTER: {
1726 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1727 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001728 return Context->getBlockPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001729 }
1730
1731 case pch::TYPE_LVALUE_REFERENCE: {
1732 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1733 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001734 return Context->getLValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001735 }
1736
1737 case pch::TYPE_RVALUE_REFERENCE: {
1738 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1739 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001740 return Context->getRValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001741 }
1742
1743 case pch::TYPE_MEMBER_POINTER: {
1744 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1745 QualType PointeeType = GetType(Record[0]);
1746 QualType ClassType = GetType(Record[1]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001747 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001748 }
1749
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001750 case pch::TYPE_CONSTANT_ARRAY: {
1751 QualType ElementType = GetType(Record[0]);
1752 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1753 unsigned IndexTypeQuals = Record[2];
1754 unsigned Idx = 3;
1755 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor1d381132009-07-06 15:59:29 +00001756 return Context->getConstantArrayType(ElementType, Size,
1757 ASM, IndexTypeQuals);
1758 }
1759
1760 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1761 QualType ElementType = GetType(Record[0]);
1762 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1763 unsigned IndexTypeQuals = Record[2];
1764 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1765 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1766 unsigned Idx = 5;
1767 llvm::APInt Size = ReadAPInt(Record, Idx);
1768 return Context->getConstantArrayWithExprType(ElementType,
1769 Size, ReadTypeExpr(),
1770 ASM, IndexTypeQuals,
1771 SourceRange(LBLoc, RBLoc));
1772 }
1773
1774 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1775 QualType ElementType = GetType(Record[0]);
1776 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1777 unsigned IndexTypeQuals = Record[2];
1778 unsigned Idx = 3;
1779 llvm::APInt Size = ReadAPInt(Record, Idx);
1780 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1781 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001782 }
1783
1784 case pch::TYPE_INCOMPLETE_ARRAY: {
1785 QualType ElementType = GetType(Record[0]);
1786 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1787 unsigned IndexTypeQuals = Record[2];
Chris Lattner270d29a2009-04-27 21:45:14 +00001788 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001789 }
1790
1791 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001792 QualType ElementType = GetType(Record[0]);
1793 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1794 unsigned IndexTypeQuals = Record[2];
Douglas Gregor1d381132009-07-06 15:59:29 +00001795 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1796 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001797 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor1d381132009-07-06 15:59:29 +00001798 ASM, IndexTypeQuals,
1799 SourceRange(LBLoc, RBLoc));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001800 }
1801
1802 case pch::TYPE_VECTOR: {
1803 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001804 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001805 return QualType();
1806 }
1807
1808 QualType ElementType = GetType(Record[0]);
1809 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001810 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001811 }
1812
1813 case pch::TYPE_EXT_VECTOR: {
1814 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001815 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001816 return QualType();
1817 }
1818
1819 QualType ElementType = GetType(Record[0]);
1820 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001821 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001822 }
1823
1824 case pch::TYPE_FUNCTION_NO_PROTO: {
1825 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001826 Error("incorrect encoding of no-proto function type");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001827 return QualType();
1828 }
1829 QualType ResultType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001830 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001831 }
1832
1833 case pch::TYPE_FUNCTION_PROTO: {
1834 QualType ResultType = GetType(Record[0]);
1835 unsigned Idx = 1;
1836 unsigned NumParams = Record[Idx++];
1837 llvm::SmallVector<QualType, 16> ParamTypes;
1838 for (unsigned I = 0; I != NumParams; ++I)
1839 ParamTypes.push_back(GetType(Record[Idx++]));
1840 bool isVariadic = Record[Idx++];
1841 unsigned Quals = Record[Idx++];
Sebastian Redl2767d882009-05-27 22:11:52 +00001842 bool hasExceptionSpec = Record[Idx++];
1843 bool hasAnyExceptionSpec = Record[Idx++];
1844 unsigned NumExceptions = Record[Idx++];
1845 llvm::SmallVector<QualType, 2> Exceptions;
1846 for (unsigned I = 0; I != NumExceptions; ++I)
1847 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad9e6bef42009-05-21 09:52:38 +00001848 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl2767d882009-05-27 22:11:52 +00001849 isVariadic, Quals, hasExceptionSpec,
1850 hasAnyExceptionSpec, NumExceptions,
1851 Exceptions.data());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001852 }
1853
1854 case pch::TYPE_TYPEDEF:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001855 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001856 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001857
1858 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner270d29a2009-04-27 21:45:14 +00001859 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001860
1861 case pch::TYPE_TYPEOF: {
1862 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001863 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001864 return QualType();
1865 }
1866 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001867 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001868 }
Anders Carlsson93ab5332009-06-24 19:06:50 +00001869
1870 case pch::TYPE_DECLTYPE:
1871 return Context->getDecltypeType(ReadTypeExpr());
1872
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001873 case pch::TYPE_RECORD:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001874 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001875 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001876
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001877 case pch::TYPE_ENUM:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001878 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001879 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001880
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001881 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001882 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001883 return Context->getObjCInterfaceType(
Chris Lattner80f83c62009-04-22 05:57:30 +00001884 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001885
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001886 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1887 unsigned Idx = 0;
1888 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1889 unsigned NumProtos = Record[Idx++];
1890 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1891 for (unsigned I = 0; I != NumProtos; ++I)
1892 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Douglas Gregor4e284192009-05-22 22:45:36 +00001893 return Context->getObjCQualifiedInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001894 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001895
Steve Naroffc75c1a82009-06-17 22:40:22 +00001896 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner9b9f2352009-04-22 06:40:03 +00001897 unsigned Idx = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001898 ObjCInterfaceDecl *ItfD =
1899 cast_or_null<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
Chris Lattner9b9f2352009-04-22 06:40:03 +00001900 unsigned NumProtos = Record[Idx++];
1901 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1902 for (unsigned I = 0; I != NumProtos; ++I)
1903 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc75c1a82009-06-17 22:40:22 +00001904 return Context->getObjCObjectPointerType(ItfD, Protos.data(), NumProtos);
Chris Lattner9b9f2352009-04-22 06:40:03 +00001905 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001906 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001907 // Suppress a GCC warning
1908 return QualType();
1909}
1910
Douglas Gregorc34897d2009-04-09 22:27:44 +00001911
Douglas Gregorac8f2802009-04-10 17:25:41 +00001912QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001913 unsigned Quals = ID & 0x07;
1914 unsigned Index = ID >> 3;
1915
1916 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1917 QualType T;
1918 switch ((pch::PredefinedTypeIDs)Index) {
1919 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner270d29a2009-04-27 21:45:14 +00001920 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1921 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001922
1923 case pch::PREDEF_TYPE_CHAR_U_ID:
1924 case pch::PREDEF_TYPE_CHAR_S_ID:
1925 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner270d29a2009-04-27 21:45:14 +00001926 T = Context->CharTy;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001927 break;
1928
Chris Lattner270d29a2009-04-27 21:45:14 +00001929 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1930 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1931 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1932 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1933 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001934 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001935 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1936 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1937 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1938 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1939 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1940 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001941 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001942 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1943 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1944 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1945 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1946 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001947 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001948 }
1949
1950 assert(!T.isNull() && "Unknown predefined type");
1951 return T.getQualifiedType(Quals);
1952 }
1953
1954 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregore43f0972009-04-26 03:49:13 +00001955 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001956 if (!TypesLoaded[Index])
1957 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001958
Douglas Gregor24a224c2009-04-25 18:35:21 +00001959 return QualType(TypesLoaded[Index], Quals);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001960}
1961
Douglas Gregorac8f2802009-04-10 17:25:41 +00001962Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001963 if (ID == 0)
1964 return 0;
1965
Douglas Gregor24a224c2009-04-25 18:35:21 +00001966 if (ID > DeclsLoaded.size()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001967 Error("declaration ID out-of-range for PCH file");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001968 return 0;
1969 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001970
Douglas Gregor24a224c2009-04-25 18:35:21 +00001971 unsigned Index = ID - 1;
1972 if (!DeclsLoaded[Index])
1973 ReadDeclRecord(DeclOffsets[Index], Index);
1974
1975 return DeclsLoaded[Index];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001976}
1977
Chris Lattner77055f62009-04-27 05:46:25 +00001978/// \brief Resolve the offset of a statement into a statement.
1979///
1980/// This operation will read a new statement from the external
1981/// source each time it is called, and is meant to be used via a
1982/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1983Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner3ef21962009-04-27 05:58:23 +00001984 // Since we know tha this statement is part of a decl, make sure to use the
1985 // decl cursor to read it.
1986 DeclsCursor.JumpToBit(Offset);
1987 return ReadStmt(DeclsCursor);
Douglas Gregor3b9a7c82009-04-18 00:07:54 +00001988}
1989
Douglas Gregorc34897d2009-04-09 22:27:44 +00001990bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001991 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001992 assert(DC->hasExternalLexicalStorage() &&
1993 "DeclContext has no lexical decls in storage");
1994 uint64_t Offset = DeclContextOffsets[DC].first;
1995 assert(Offset && "DeclContext has no lexical decls in storage");
1996
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001997 // Keep track of where we are in the stream, then jump back there
1998 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001999 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002000
Douglas Gregorc34897d2009-04-09 22:27:44 +00002001 // Load the record containing all of the declarations lexically in
2002 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00002003 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00002004 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00002005 unsigned Code = DeclsCursor.ReadCode();
2006 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00002007 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002008 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2009
2010 // Load all of the declaration IDs
2011 Decls.clear();
2012 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregoraf136d92009-04-22 22:34:57 +00002013 ++NumLexicalDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002014 return false;
2015}
2016
2017bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner85e3f642009-04-27 07:35:40 +00002018 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00002019 assert(DC->hasExternalVisibleStorage() &&
2020 "DeclContext has no visible decls in storage");
2021 uint64_t Offset = DeclContextOffsets[DC].second;
2022 assert(Offset && "DeclContext has no visible decls in storage");
2023
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002024 // Keep track of where we are in the stream, then jump back there
2025 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00002026 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002027
Douglas Gregorc34897d2009-04-09 22:27:44 +00002028 // Load the record containing all of the declarations visible in
2029 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00002030 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00002031 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00002032 unsigned Code = DeclsCursor.ReadCode();
2033 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00002034 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002035 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2036 if (Record.size() == 0)
2037 return false;
2038
2039 Decls.clear();
2040
2041 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002042 while (Idx < Record.size()) {
2043 Decls.push_back(VisibleDeclaration());
2044 Decls.back().Name = ReadDeclarationName(Record, Idx);
2045
Douglas Gregorc34897d2009-04-09 22:27:44 +00002046 unsigned Size = Record[Idx++];
Chris Lattner85e3f642009-04-27 07:35:40 +00002047 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002048 LoadedDecls.reserve(Size);
2049 for (unsigned I = 0; I < Size; ++I)
2050 LoadedDecls.push_back(Record[Idx++]);
2051 }
2052
Douglas Gregoraf136d92009-04-22 22:34:57 +00002053 ++NumVisibleDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002054 return false;
2055}
2056
Douglas Gregor631f6c62009-04-14 00:24:19 +00002057void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor405b6432009-04-22 19:09:20 +00002058 this->Consumer = Consumer;
2059
Douglas Gregor631f6c62009-04-14 00:24:19 +00002060 if (!Consumer)
2061 return;
2062
2063 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2064 Decl *D = GetDecl(ExternalDefinitions[I]);
2065 DeclGroupRef DG(D);
2066 Consumer->HandleTopLevelDecl(DG);
2067 }
Douglas Gregorf93cfee2009-04-25 00:41:30 +00002068
2069 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2070 DeclGroupRef DG(InterestingDecls[I]);
2071 Consumer->HandleTopLevelDecl(DG);
2072 }
Douglas Gregor631f6c62009-04-14 00:24:19 +00002073}
2074
Douglas Gregorc34897d2009-04-09 22:27:44 +00002075void PCHReader::PrintStats() {
2076 std::fprintf(stderr, "*** PCH Statistics:\n");
2077
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002078 unsigned NumTypesLoaded
2079 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2080 (Type *)0);
2081 unsigned NumDeclsLoaded
2082 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2083 (Decl *)0);
2084 unsigned NumIdentifiersLoaded
2085 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2086 IdentifiersLoaded.end(),
2087 (IdentifierInfo *)0);
2088 unsigned NumSelectorsLoaded
2089 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2090 SelectorsLoaded.end(),
2091 Selector());
Douglas Gregor9cf47422009-04-13 20:50:16 +00002092
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002093 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2094 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor32e231c2009-04-27 06:38:32 +00002095 if (TotalNumSLocEntries)
2096 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2097 NumSLocEntriesRead, TotalNumSLocEntries,
2098 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor24a224c2009-04-25 18:35:21 +00002099 if (!TypesLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002100 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002101 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2102 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2103 if (!DeclsLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002104 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002105 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2106 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002107 if (!IdentifiersLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002108 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002109 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2110 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor2d711832009-04-25 17:48:32 +00002111 if (TotalNumSelectors)
2112 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2113 NumSelectorsLoaded, TotalNumSelectors,
2114 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2115 if (TotalNumStatements)
2116 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2117 NumStatementsRead, TotalNumStatements,
2118 ((float)NumStatementsRead/TotalNumStatements * 100));
2119 if (TotalNumMacros)
2120 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2121 NumMacrosRead, TotalNumMacros,
2122 ((float)NumMacrosRead/TotalNumMacros * 100));
2123 if (TotalLexicalDeclContexts)
2124 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2125 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2126 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2127 * 100));
2128 if (TotalVisibleDeclContexts)
2129 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2130 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2131 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2132 * 100));
2133 if (TotalSelectorsInMethodPool) {
2134 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2135 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2136 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2137 * 100));
2138 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2139 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00002140 std::fprintf(stderr, "\n");
2141}
2142
Douglas Gregorc713da92009-04-21 22:25:48 +00002143void PCHReader::InitializeSema(Sema &S) {
2144 SemaObj = &S;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002145 S.ExternalSource = this;
2146
Douglas Gregor2554cf22009-04-22 21:15:06 +00002147 // Makes sure any declarations that were deserialized "too early"
2148 // still get added to the identifier's declaration chains.
2149 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2150 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2151 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregorc713da92009-04-21 22:25:48 +00002152 }
Douglas Gregor2554cf22009-04-22 21:15:06 +00002153 PreloadedDecls.clear();
Douglas Gregor77b2cd52009-04-22 22:02:47 +00002154
2155 // If there were any tentative definitions, deserialize them and add
2156 // them to Sema's table of tentative definitions.
2157 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2158 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2159 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2160 }
Douglas Gregor062d9482009-04-22 22:18:58 +00002161
2162 // If there were any locally-scoped external declarations,
2163 // deserialize them and add them to Sema's table of locally-scoped
2164 // external declarations.
2165 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2166 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2167 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2168 }
Douglas Gregorb36b20d2009-04-27 20:06:05 +00002169
2170 // If there were any ext_vector type declarations, deserialize them
2171 // and add them to Sema's vector of such declarations.
2172 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2173 SemaObj->ExtVectorDecls.push_back(
2174 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2175
2176 // If there were any Objective-C category implementations,
2177 // deserialize them and add them to Sema's vector of such
2178 // definitions.
2179 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
2180 SemaObj->ObjCCategoryImpls.push_back(
2181 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregorc713da92009-04-21 22:25:48 +00002182}
2183
2184IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2185 // Try to find this name within our on-disk hash table
2186 PCHIdentifierLookupTable *IdTable
2187 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2188 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2189 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2190 if (Pos == IdTable->end())
2191 return 0;
2192
2193 // Dereferencing the iterator has the effect of building the
2194 // IdentifierInfo node and populating it with the various
2195 // declarations it needs.
2196 return *Pos;
2197}
2198
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002199std::pair<ObjCMethodList, ObjCMethodList>
2200PCHReader::ReadMethodPool(Selector Sel) {
2201 if (!MethodPoolLookupTable)
2202 return std::pair<ObjCMethodList, ObjCMethodList>();
2203
2204 // Try to find this selector within our on-disk hash table.
2205 PCHMethodPoolLookupTable *PoolTable
2206 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2207 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor2d711832009-04-25 17:48:32 +00002208 if (Pos == PoolTable->end()) {
2209 ++NumMethodPoolMisses;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002210 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor2d711832009-04-25 17:48:32 +00002211 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002212
Douglas Gregor2d711832009-04-25 17:48:32 +00002213 ++NumMethodPoolSelectorsRead;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002214 return *Pos;
2215}
2216
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002217void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregorc713da92009-04-21 22:25:48 +00002218 assert(ID && "Non-zero identifier ID required");
Douglas Gregoreae710d2009-04-28 21:53:25 +00002219 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002220 IdentifiersLoaded[ID - 1] = II;
Douglas Gregorc713da92009-04-21 22:25:48 +00002221}
2222
Chris Lattner29241862009-04-11 21:15:38 +00002223IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002224 if (ID == 0)
2225 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00002226
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002227 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002228 Error("no identifier table in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002229 return 0;
2230 }
Chris Lattner29241862009-04-11 21:15:38 +00002231
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002232 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002233 if (!IdentifiersLoaded[ID - 1]) {
2234 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002235 const char *Str = IdentifierTableData + Offset;
Douglas Gregor85c4a872009-04-25 21:04:17 +00002236
Douglas Gregor68619772009-04-28 20:01:51 +00002237 // All of the strings in the PCH file are preceded by a 16-bit
2238 // length. Extract that 16-bit length to avoid having to execute
2239 // strlen().
2240 const char *StrLenPtr = Str - 2;
2241 unsigned StrLen = (((unsigned) StrLenPtr[0])
2242 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2243 IdentifiersLoaded[ID - 1]
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002244 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002245 }
Chris Lattner29241862009-04-11 21:15:38 +00002246
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002247 return IdentifiersLoaded[ID - 1];
Douglas Gregorc34897d2009-04-09 22:27:44 +00002248}
2249
Douglas Gregor32e231c2009-04-27 06:38:32 +00002250void PCHReader::ReadSLocEntry(unsigned ID) {
2251 ReadSLocEntryRecord(ID);
2252}
2253
Steve Naroff9e84d782009-04-23 10:39:46 +00002254Selector PCHReader::DecodeSelector(unsigned ID) {
2255 if (ID == 0)
2256 return Selector();
2257
Douglas Gregoreae710d2009-04-28 21:53:25 +00002258 if (!MethodPoolLookupTableData)
Steve Naroff9e84d782009-04-23 10:39:46 +00002259 return Selector();
Douglas Gregor2d711832009-04-25 17:48:32 +00002260
2261 if (ID > TotalNumSelectors) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002262 Error("selector ID out of range in PCH file");
Steve Naroff9e84d782009-04-23 10:39:46 +00002263 return Selector();
2264 }
Douglas Gregor2d711832009-04-25 17:48:32 +00002265
2266 unsigned Index = ID - 1;
2267 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2268 // Load this selector from the selector table.
2269 // FIXME: endianness portability issues with SelectorOffsets table
2270 PCHMethodPoolLookupTrait Trait(*this);
2271 SelectorsLoaded[Index]
2272 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2273 }
2274
2275 return SelectorsLoaded[Index];
Steve Naroff9e84d782009-04-23 10:39:46 +00002276}
2277
Douglas Gregorc34897d2009-04-09 22:27:44 +00002278DeclarationName
2279PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2280 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2281 switch (Kind) {
2282 case DeclarationName::Identifier:
2283 return DeclarationName(GetIdentifierInfo(Record, Idx));
2284
2285 case DeclarationName::ObjCZeroArgSelector:
2286 case DeclarationName::ObjCOneArgSelector:
2287 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff104956f2009-04-23 15:15:40 +00002288 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregorc34897d2009-04-09 22:27:44 +00002289
2290 case DeclarationName::CXXConstructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002291 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002292 GetType(Record[Idx++]));
2293
2294 case DeclarationName::CXXDestructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002295 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002296 GetType(Record[Idx++]));
2297
2298 case DeclarationName::CXXConversionFunctionName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002299 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002300 GetType(Record[Idx++]));
2301
2302 case DeclarationName::CXXOperatorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002303 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002304 (OverloadedOperatorKind)Record[Idx++]);
2305
2306 case DeclarationName::CXXUsingDirective:
2307 return DeclarationName::getUsingDirectiveName();
2308 }
2309
2310 // Required to silence GCC warning
2311 return DeclarationName();
2312}
Douglas Gregor179cfb12009-04-10 20:39:37 +00002313
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00002314/// \brief Read an integral value
2315llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2316 unsigned BitWidth = Record[Idx++];
2317 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2318 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2319 Idx += NumWords;
2320 return Result;
2321}
2322
2323/// \brief Read a signed integral value
2324llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2325 bool isUnsigned = Record[Idx++];
2326 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2327}
2328
Douglas Gregore2f37202009-04-14 21:55:33 +00002329/// \brief Read a floating-point value
2330llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00002331 return llvm::APFloat(ReadAPInt(Record, Idx));
2332}
2333
Douglas Gregor1c507882009-04-15 21:30:51 +00002334// \brief Read a string
2335std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2336 unsigned Len = Record[Idx++];
Jay Foad9e6bef42009-05-21 09:52:38 +00002337 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor1c507882009-04-15 21:30:51 +00002338 Idx += Len;
2339 return Result;
2340}
2341
Douglas Gregor179cfb12009-04-10 20:39:37 +00002342DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002343 return Diag(SourceLocation(), DiagID);
2344}
2345
2346DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002347 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor179cfb12009-04-10 20:39:37 +00002348}
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002349
Douglas Gregorc713da92009-04-21 22:25:48 +00002350/// \brief Retrieve the identifier table associated with the
2351/// preprocessor.
2352IdentifierTable &PCHReader::getIdentifierTable() {
Argiris Kirtzidise3f4bda2009-06-19 00:03:23 +00002353 assert(PP && "Forgot to set Preprocessor ?");
2354 return PP->getIdentifierTable();
Douglas Gregorc713da92009-04-21 22:25:48 +00002355}
2356
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002357/// \brief Record that the given ID maps to the given switch-case
2358/// statement.
2359void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2360 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2361 SwitchCaseStmts[ID] = SC;
2362}
2363
2364/// \brief Retrieve the switch-case statement with the given ID.
2365SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2366 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2367 return SwitchCaseStmts[ID];
2368}
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002369
2370/// \brief Record that the given label statement has been
2371/// deserialized and has the given ID.
2372void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2373 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2374 "Deserialized label twice");
2375 LabelStmts[ID] = S;
2376
2377 // If we've already seen any goto statements that point to this
2378 // label, resolve them now.
2379 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2380 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2381 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2382 Goto->second->setLabel(S);
2383 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002384
2385 // If we've already seen any address-label statements that point to
2386 // this label, resolve them now.
2387 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2388 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2389 = UnresolvedAddrLabelExprs.equal_range(ID);
2390 for (AddrLabelIter AddrLabel = AddrLabels.first;
2391 AddrLabel != AddrLabels.second; ++AddrLabel)
2392 AddrLabel->second->setLabel(S);
2393 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002394}
2395
2396/// \brief Set the label of the given statement to the label
2397/// identified by ID.
2398///
2399/// Depending on the order in which the label and other statements
2400/// referencing that label occur, this operation may complete
2401/// immediately (updating the statement) or it may queue the
2402/// statement to be back-patched later.
2403void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2404 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2405 if (Label != LabelStmts.end()) {
2406 // We've already seen this label, so set the label of the goto and
2407 // we're done.
2408 S->setLabel(Label->second);
2409 } else {
2410 // We haven't seen this label yet, so add this goto to the set of
2411 // unresolved goto statements.
2412 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2413 }
2414}
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002415
2416/// \brief Set the label of the given expression to the label
2417/// identified by ID.
2418///
2419/// Depending on the order in which the label and other statements
2420/// referencing that label occur, this operation may complete
2421/// immediately (updating the statement) or it may queue the
2422/// statement to be back-patched later.
2423void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2424 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2425 if (Label != LabelStmts.end()) {
2426 // We've already seen this label, so set the label of the
2427 // label-address expression and we're done.
2428 S->setLabel(Label->second);
2429 } else {
2430 // We haven't seen this label yet, so add this label-address
2431 // expression to the set of unresolved label-address expressions.
2432 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2433 }
2434}