blob: 067cce9b3092bf85b996af772f71e3eb25adfd03 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000039// PCH reader validator implementation
40//===----------------------------------------------------------------------===//
41
42PCHReaderListener::~PCHReaderListener() {}
43
44bool
45PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
46 const LangOptions &PPLangOpts = PP.getLangOptions();
47#define PARSE_LANGOPT_BENIGN(Option)
48#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
49 if (PPLangOpts.Option != LangOpts.Option) { \
50 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
51 return true; \
52 }
53
54 PARSE_LANGOPT_BENIGN(Trigraphs);
55 PARSE_LANGOPT_BENIGN(BCPLComment);
56 PARSE_LANGOPT_BENIGN(DollarIdents);
57 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
58 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
59 PARSE_LANGOPT_BENIGN(ImplicitInt);
60 PARSE_LANGOPT_BENIGN(Digraphs);
61 PARSE_LANGOPT_BENIGN(HexFloats);
62 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
63 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
64 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
66 PARSE_LANGOPT_BENIGN(CXXOperatorName);
67 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
68 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
69 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
70 PARSE_LANGOPT_BENIGN(PascalStrings);
71 PARSE_LANGOPT_BENIGN(WritableStrings);
72 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
73 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000075 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
76 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
77 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
78 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
79 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
80 diag::warn_pch_thread_safe_statics);
81 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
82 PARSE_LANGOPT_BENIGN(EmitAllDecls);
83 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
84 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
85 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
86 diag::warn_pch_heinous_extensions);
87 // FIXME: Most of the options below are benign if the macro wasn't
88 // used. Unfortunately, this means that a PCH compiled without
89 // optimization can't be used with optimization turned on, even
90 // though the only thing that changes is whether __OPTIMIZE__ was
91 // defined... but if __OPTIMIZE__ never showed up in the header, it
92 // doesn't matter. We could consider making this some special kind
93 // of check.
94 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
95 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
96 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
97 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
98 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
99 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
100 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
101 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
102 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
103 Reader.Diag(diag::warn_pch_gc_mode)
104 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
105 return true;
106 }
107 PARSE_LANGOPT_BENIGN(getVisibilityMode());
108 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000109 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000110#undef PARSE_LANGOPT_IRRELEVANT
111#undef PARSE_LANGOPT_BENIGN
112
113 return false;
114}
115
116bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
117 if (Triple != PP.getTargetInfo().getTargetTriple()) {
118 Reader.Diag(diag::warn_pch_target_triple)
119 << Triple << PP.getTargetInfo().getTargetTriple();
120 return true;
121 }
122 return false;
123}
124
125/// \brief Split the given string into a vector of lines, eliminating
126/// any empty lines in the process.
127///
128/// \param Str the string to split.
129/// \param Len the length of Str.
130/// \param KeepEmptyLines true if empty lines should be included
131/// \returns a vector of lines, with the line endings removed
132static std::vector<std::string> splitLines(const char *Str, unsigned Len,
133 bool KeepEmptyLines = false) {
134 std::vector<std::string> Lines;
135 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
136 unsigned LineEnd = LineStart;
137 while (LineEnd < Len && Str[LineEnd] != '\n')
138 ++LineEnd;
139 if (LineStart != LineEnd || KeepEmptyLines)
140 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
141 LineStart = LineEnd;
142 }
143 return Lines;
144}
145
146/// \brief Determine whether the string Haystack starts with the
147/// substring Needle.
148static bool startsWith(const std::string &Haystack, const char *Needle) {
149 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
150 if (I == N)
151 return false;
152 if (Haystack[I] != Needle[I])
153 return false;
154 }
155
156 return true;
157}
158
159/// \brief Determine whether the string Haystack starts with the
160/// substring Needle.
161static inline bool startsWith(const std::string &Haystack,
162 const std::string &Needle) {
163 return startsWith(Haystack, Needle.c_str());
164}
165
166bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
167 unsigned PCHPredefLen,
168 FileID PCHBufferID,
169 std::string &SuggestedPredefines) {
170 const char *Predef = PP.getPredefines().c_str();
171 unsigned PredefLen = PP.getPredefines().size();
172
173 // If the two predefines buffers compare equal, we're done!
174 if (PredefLen == PCHPredefLen &&
175 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
176 return false;
177
178 SourceManager &SourceMgr = PP.getSourceManager();
179
180 // The predefines buffers are different. Determine what the
181 // differences are, and whether they require us to reject the PCH
182 // file.
183 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
184 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
185
186 // Sort both sets of predefined buffer lines, since
187 std::sort(CmdLineLines.begin(), CmdLineLines.end());
188 std::sort(PCHLines.begin(), PCHLines.end());
189
190 // Determine which predefines that where used to build the PCH file
191 // are missing from the command line.
192 std::vector<std::string> MissingPredefines;
193 std::set_difference(PCHLines.begin(), PCHLines.end(),
194 CmdLineLines.begin(), CmdLineLines.end(),
195 std::back_inserter(MissingPredefines));
196
197 bool MissingDefines = false;
198 bool ConflictingDefines = false;
199 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
200 const std::string &Missing = MissingPredefines[I];
201 if (!startsWith(Missing, "#define ") != 0) {
202 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
203 return true;
204 }
205
206 // This is a macro definition. Determine the name of the macro
207 // we're defining.
208 std::string::size_type StartOfMacroName = strlen("#define ");
209 std::string::size_type EndOfMacroName
210 = Missing.find_first_of("( \n\r", StartOfMacroName);
211 assert(EndOfMacroName != std::string::npos &&
212 "Couldn't find the end of the macro name");
213 std::string MacroName = Missing.substr(StartOfMacroName,
214 EndOfMacroName - StartOfMacroName);
215
216 // Determine whether this macro was given a different definition
217 // on the command line.
218 std::string MacroDefStart = "#define " + MacroName;
219 std::string::size_type MacroDefLen = MacroDefStart.size();
220 std::vector<std::string>::iterator ConflictPos
221 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
222 MacroDefStart);
223 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
224 if (!startsWith(*ConflictPos, MacroDefStart)) {
225 // Different macro; we're done.
226 ConflictPos = CmdLineLines.end();
227 break;
228 }
229
230 assert(ConflictPos->size() > MacroDefLen &&
231 "Invalid #define in predefines buffer?");
232 if ((*ConflictPos)[MacroDefLen] != ' ' &&
233 (*ConflictPos)[MacroDefLen] != '(')
234 continue; // Longer macro name; keep trying.
235
236 // We found a conflicting macro definition.
237 break;
238 }
239
240 if (ConflictPos != CmdLineLines.end()) {
241 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
242 << MacroName;
243
244 // Show the definition of this macro within the PCH file.
245 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
246 unsigned Offset = MissingDef - PCHPredef;
247 SourceLocation PCHMissingLoc
248 = SourceMgr.getLocForStartOfFile(PCHBufferID)
249 .getFileLocWithOffset(Offset);
250 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
251 << MacroName;
252
253 ConflictingDefines = true;
254 continue;
255 }
256
257 // If the macro doesn't conflict, then we'll just pick up the
258 // macro definition from the PCH file. Warn the user that they
259 // made a mistake.
260 if (ConflictingDefines)
261 continue; // Don't complain if there are already conflicting defs
262
263 if (!MissingDefines) {
264 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
265 MissingDefines = true;
266 }
267
268 // Show the definition of this macro within the PCH file.
269 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
270 unsigned Offset = MissingDef - PCHPredef;
271 SourceLocation PCHMissingLoc
272 = SourceMgr.getLocForStartOfFile(PCHBufferID)
273 .getFileLocWithOffset(Offset);
274 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
275 }
276
277 if (ConflictingDefines)
278 return true;
279
280 // Determine what predefines were introduced based on command-line
281 // parameters that were not present when building the PCH
282 // file. Extra #defines are okay, so long as the identifiers being
283 // defined were not used within the precompiled header.
284 std::vector<std::string> ExtraPredefines;
285 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
286 PCHLines.begin(), PCHLines.end(),
287 std::back_inserter(ExtraPredefines));
288 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
289 const std::string &Extra = ExtraPredefines[I];
290 if (!startsWith(Extra, "#define ") != 0) {
291 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
292 return true;
293 }
294
295 // This is an extra macro definition. Determine the name of the
296 // macro we're defining.
297 std::string::size_type StartOfMacroName = strlen("#define ");
298 std::string::size_type EndOfMacroName
299 = Extra.find_first_of("( \n\r", StartOfMacroName);
300 assert(EndOfMacroName != std::string::npos &&
301 "Couldn't find the end of the macro name");
302 std::string MacroName = Extra.substr(StartOfMacroName,
303 EndOfMacroName - StartOfMacroName);
304
305 // Check whether this name was used somewhere in the PCH file. If
306 // so, defining it as a macro could change behavior, so we reject
307 // the PCH file.
308 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
309 MacroName.c_str() + MacroName.size())) {
310 Reader.Diag(diag::warn_macro_name_used_in_pch)
311 << II;
312 return true;
313 }
314
315 // Add this definition to the suggested predefines buffer.
316 SuggestedPredefines += Extra;
317 SuggestedPredefines += '\n';
318 }
319
320 // If we get here, it's because the predefines buffer had compatible
321 // contents. Accept the PCH file.
322 return false;
323}
324
325void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
326 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
327}
328
329void PCHValidator::ReadCounter(unsigned Value) {
330 PP.setCounterValue(Value);
331}
332
333
334
335//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000336// PCH reader implementation
337//===----------------------------------------------------------------------===//
338
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000339PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
341 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
342 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
343 IdentifierTableData(0), IdentifierLookupTable(0),
344 IdentifierOffsets(0),
345 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
346 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor2e222532009-07-02 17:08:52 +0000347 TotalNumSelectors(0), Comments(0), NumComments(0),
348 NumStatHits(0), NumStatMisses(0),
Argyrios Kyrtzidis11e51102009-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),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000356 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000357 IdentifierTableData(0), IdentifierLookupTable(0),
358 IdentifierOffsets(0),
359 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
360 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000361 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
362 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000363 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000364 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
365 CurrentlyLoadingTypeOrDecl(0) { }
Chris Lattner4c6f9522009-04-27 05:14:47 +0000366
367PCHReader::~PCHReader() {}
368
Chris Lattnerda930612009-04-27 05:58:23 +0000369Expr *PCHReader::ReadDeclExpr() {
370 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
371}
372
373Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000374 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000375}
376
377
Douglas Gregor668c1a42009-04-21 22:25:48 +0000378namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000379class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
380 PCHReader &Reader;
381
382public:
383 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
384
385 typedef Selector external_key_type;
386 typedef external_key_type internal_key_type;
387
388 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
389
390 static bool EqualKey(const internal_key_type& a,
391 const internal_key_type& b) {
392 return a == b;
393 }
394
395 static unsigned ComputeHash(Selector Sel) {
396 unsigned N = Sel.getNumArgs();
397 if (N == 0)
398 ++N;
399 unsigned R = 5381;
400 for (unsigned I = 0; I != N; ++I)
401 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
402 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
403 return R;
404 }
405
406 // This hopefully will just get inlined and removed by the optimizer.
407 static const internal_key_type&
408 GetInternalKey(const external_key_type& x) { return x; }
409
410 static std::pair<unsigned, unsigned>
411 ReadKeyDataLength(const unsigned char*& d) {
412 using namespace clang::io;
413 unsigned KeyLen = ReadUnalignedLE16(d);
414 unsigned DataLen = ReadUnalignedLE16(d);
415 return std::make_pair(KeyLen, DataLen);
416 }
417
Douglas Gregor83941df2009-04-25 17:48:32 +0000418 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000419 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000420 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000421 unsigned N = ReadUnalignedLE16(d);
422 IdentifierInfo *FirstII
423 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
424 if (N == 0)
425 return SelTable.getNullarySelector(FirstII);
426 else if (N == 1)
427 return SelTable.getUnarySelector(FirstII);
428
429 llvm::SmallVector<IdentifierInfo *, 16> Args;
430 Args.push_back(FirstII);
431 for (unsigned I = 1; I != N; ++I)
432 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
433
Douglas Gregor75fdb232009-05-22 22:45:36 +0000434 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000435 }
436
437 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
438 using namespace clang::io;
439 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
440 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
441
442 data_type Result;
443
444 // Load instance methods
445 ObjCMethodList *Prev = 0;
446 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
447 ObjCMethodDecl *Method
448 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
449 if (!Result.first.Method) {
450 // This is the first method, which is the easy case.
451 Result.first.Method = Method;
452 Prev = &Result.first;
453 continue;
454 }
455
456 Prev->Next = new ObjCMethodList(Method, 0);
457 Prev = Prev->Next;
458 }
459
460 // Load factory methods
461 Prev = 0;
462 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
463 ObjCMethodDecl *Method
464 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
465 if (!Result.second.Method) {
466 // This is the first method, which is the easy case.
467 Result.second.Method = Method;
468 Prev = &Result.second;
469 continue;
470 }
471
472 Prev->Next = new ObjCMethodList(Method, 0);
473 Prev = Prev->Next;
474 }
475
476 return Result;
477 }
478};
479
480} // end anonymous namespace
481
482/// \brief The on-disk hash table used for the global method pool.
483typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
484 PCHMethodPoolLookupTable;
485
486namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000487class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
488 PCHReader &Reader;
489
490 // If we know the IdentifierInfo in advance, it is here and we will
491 // not build a new one. Used when deserializing information about an
492 // identifier that was constructed before the PCH file was read.
493 IdentifierInfo *KnownII;
494
495public:
496 typedef IdentifierInfo * data_type;
497
498 typedef const std::pair<const char*, unsigned> external_key_type;
499
500 typedef external_key_type internal_key_type;
501
502 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
503 : Reader(Reader), KnownII(II) { }
504
505 static bool EqualKey(const internal_key_type& a,
506 const internal_key_type& b) {
507 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
508 : false;
509 }
510
511 static unsigned ComputeHash(const internal_key_type& a) {
512 return BernsteinHash(a.first, a.second);
513 }
514
515 // This hopefully will just get inlined and removed by the optimizer.
516 static const internal_key_type&
517 GetInternalKey(const external_key_type& x) { return x; }
518
519 static std::pair<unsigned, unsigned>
520 ReadKeyDataLength(const unsigned char*& d) {
521 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000522 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000523 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000524 return std::make_pair(KeyLen, DataLen);
525 }
526
527 static std::pair<const char*, unsigned>
528 ReadKey(const unsigned char* d, unsigned n) {
529 assert(n >= 2 && d[n-1] == '\0');
530 return std::make_pair((const char*) d, n-1);
531 }
532
533 IdentifierInfo *ReadData(const internal_key_type& k,
534 const unsigned char* d,
535 unsigned DataLen) {
536 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000537 pch::IdentID ID = ReadUnalignedLE32(d);
538 bool IsInteresting = ID & 0x01;
539
540 // Wipe out the "is interesting" bit.
541 ID = ID >> 1;
542
543 if (!IsInteresting) {
544 // For unintersting identifiers, just build the IdentifierInfo
545 // and associate it with the persistent ID.
546 IdentifierInfo *II = KnownII;
547 if (!II)
548 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
549 k.first, k.first + k.second);
550 Reader.SetIdentifierInfo(ID, II);
551 return II;
552 }
553
Douglas Gregor5998da52009-04-28 21:32:13 +0000554 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000555 bool CPlusPlusOperatorKeyword = Bits & 0x01;
556 Bits >>= 1;
557 bool Poisoned = Bits & 0x01;
558 Bits >>= 1;
559 bool ExtensionToken = Bits & 0x01;
560 Bits >>= 1;
561 bool hasMacroDefinition = Bits & 0x01;
562 Bits >>= 1;
563 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
564 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000565
Douglas Gregor2deaea32009-04-22 18:49:13 +0000566 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000567 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000568
569 // Build the IdentifierInfo itself and link the identifier ID with
570 // the new IdentifierInfo.
571 IdentifierInfo *II = KnownII;
572 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000573 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
574 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000575 Reader.SetIdentifierInfo(ID, II);
576
Douglas Gregor2deaea32009-04-22 18:49:13 +0000577 // Set or check the various bits in the IdentifierInfo structure.
578 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000579 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
580 assert(II->isExtensionToken() == ExtensionToken &&
581 "Incorrect extension token flag");
582 (void)ExtensionToken;
583 II->setIsPoisoned(Poisoned);
584 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
585 "Incorrect C++ operator keyword flag");
586 (void)CPlusPlusOperatorKeyword;
587
Douglas Gregor37e26842009-04-21 23:56:24 +0000588 // If this identifier is a macro, deserialize the macro
589 // definition.
590 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000591 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000592 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000593 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000594 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000595
596 // Read all of the declarations visible at global scope with this
597 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000598 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000599 if (DataLen > 0) {
600 llvm::SmallVector<uint32_t, 4> DeclIDs;
601 for (; DataLen > 0; DataLen -= 4)
602 DeclIDs.push_back(ReadUnalignedLE32(d));
603 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604 }
Douglas Gregord89275b2009-07-06 18:54:52 +0000605
Douglas Gregor668c1a42009-04-21 22:25:48 +0000606 return II;
607 }
608};
609
610} // end anonymous namespace
611
612/// \brief The on-disk hash table used to contain information about
613/// all of the identifiers in the program.
614typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
615 PCHIdentifierLookupTable;
616
Douglas Gregora02b1472009-04-28 21:53:25 +0000617bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000618 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
619 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000620 return true;
621}
622
Douglas Gregore1d918e2009-04-10 23:10:45 +0000623/// \brief Check the contents of the predefines buffer against the
624/// contents of the predefines buffer used to build the PCH file.
625///
626/// The contents of the two predefines buffers should be the same. If
627/// not, then some command-line option changed the preprocessor state
628/// and we must reject the PCH file.
629///
630/// \param PCHPredef The start of the predefines buffer in the PCH
631/// file.
632///
633/// \param PCHPredefLen The length of the predefines buffer in the PCH
634/// file.
635///
636/// \param PCHBufferID The FileID for the PCH predefines buffer.
637///
638/// \returns true if there was a mismatch (in which case the PCH file
639/// should be ignored), or false otherwise.
640bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
641 unsigned PCHPredefLen,
642 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000643 if (Listener)
644 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
645 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000646 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000647}
648
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000649//===----------------------------------------------------------------------===//
650// Source Manager Deserialization
651//===----------------------------------------------------------------------===//
652
Douglas Gregorbd945002009-04-13 16:31:14 +0000653/// \brief Read the line table in the source manager block.
654/// \returns true if ther was an error.
655static bool ParseLineTable(SourceManager &SourceMgr,
656 llvm::SmallVectorImpl<uint64_t> &Record) {
657 unsigned Idx = 0;
658 LineTableInfo &LineTable = SourceMgr.getLineTable();
659
660 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000661 std::map<int, int> FileIDs;
662 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000663 // Extract the file name
664 unsigned FilenameLen = Record[Idx++];
665 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
666 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000667 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
668 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000669 }
670
671 // Parse the line entries
672 std::vector<LineEntry> Entries;
673 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000674 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000675
676 // Extract the line entries
677 unsigned NumEntries = Record[Idx++];
678 Entries.clear();
679 Entries.reserve(NumEntries);
680 for (unsigned I = 0; I != NumEntries; ++I) {
681 unsigned FileOffset = Record[Idx++];
682 unsigned LineNo = Record[Idx++];
683 int FilenameID = Record[Idx++];
684 SrcMgr::CharacteristicKind FileKind
685 = (SrcMgr::CharacteristicKind)Record[Idx++];
686 unsigned IncludeOffset = Record[Idx++];
687 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
688 FileKind, IncludeOffset));
689 }
690 LineTable.AddEntry(FID, Entries);
691 }
692
693 return false;
694}
695
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000696namespace {
697
698class VISIBILITY_HIDDEN PCHStatData {
699public:
700 const bool hasStat;
701 const ino_t ino;
702 const dev_t dev;
703 const mode_t mode;
704 const time_t mtime;
705 const off_t size;
706
707 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
708 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
709
710 PCHStatData()
711 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
712};
713
714class VISIBILITY_HIDDEN PCHStatLookupTrait {
715 public:
716 typedef const char *external_key_type;
717 typedef const char *internal_key_type;
718
719 typedef PCHStatData data_type;
720
721 static unsigned ComputeHash(const char *path) {
722 return BernsteinHash(path);
723 }
724
725 static internal_key_type GetInternalKey(const char *path) { return path; }
726
727 static bool EqualKey(internal_key_type a, internal_key_type b) {
728 return strcmp(a, b) == 0;
729 }
730
731 static std::pair<unsigned, unsigned>
732 ReadKeyDataLength(const unsigned char*& d) {
733 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
734 unsigned DataLen = (unsigned) *d++;
735 return std::make_pair(KeyLen + 1, DataLen);
736 }
737
738 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
739 return (const char *)d;
740 }
741
742 static data_type ReadData(const internal_key_type, const unsigned char *d,
743 unsigned /*DataLen*/) {
744 using namespace clang::io;
745
746 if (*d++ == 1)
747 return data_type();
748
749 ino_t ino = (ino_t) ReadUnalignedLE32(d);
750 dev_t dev = (dev_t) ReadUnalignedLE32(d);
751 mode_t mode = (mode_t) ReadUnalignedLE16(d);
752 time_t mtime = (time_t) ReadUnalignedLE64(d);
753 off_t size = (off_t) ReadUnalignedLE64(d);
754 return data_type(ino, dev, mode, mtime, size);
755 }
756};
757
758/// \brief stat() cache for precompiled headers.
759///
760/// This cache is very similar to the stat cache used by pretokenized
761/// headers.
762class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
763 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
764 CacheTy *Cache;
765
766 unsigned &NumStatHits, &NumStatMisses;
767public:
768 PCHStatCache(const unsigned char *Buckets,
769 const unsigned char *Base,
770 unsigned &NumStatHits,
771 unsigned &NumStatMisses)
772 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
773 Cache = CacheTy::Create(Buckets, Base);
774 }
775
776 ~PCHStatCache() { delete Cache; }
777
778 int stat(const char *path, struct stat *buf) {
779 // Do the lookup for the file's data in the PCH file.
780 CacheTy::iterator I = Cache->find(path);
781
782 // If we don't get a hit in the PCH file just forward to 'stat'.
783 if (I == Cache->end()) {
784 ++NumStatMisses;
785 return ::stat(path, buf);
786 }
787
788 ++NumStatHits;
789 PCHStatData Data = *I;
790
791 if (!Data.hasStat)
792 return 1;
793
794 buf->st_ino = Data.ino;
795 buf->st_dev = Data.dev;
796 buf->st_mtime = Data.mtime;
797 buf->st_mode = Data.mode;
798 buf->st_size = Data.size;
799 return 0;
800 }
801};
802} // end anonymous namespace
803
804
Douglas Gregor14f79002009-04-10 03:52:48 +0000805/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000806PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000807 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000808
809 // Set the source-location entry cursor to the current position in
810 // the stream. This cursor will be used to read the contents of the
811 // source manager block initially, and then lazily read
812 // source-location entries as needed.
813 SLocEntryCursor = Stream;
814
815 // The stream itself is going to skip over the source manager block.
816 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000817 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000818 return Failure;
819 }
820
821 // Enter the source manager block.
822 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000823 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000824 return Failure;
825 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000826
Douglas Gregor14f79002009-04-10 03:52:48 +0000827 RecordData Record;
828 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000829 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000830 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000831 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000832 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000833 return Failure;
834 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000835 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000836 }
837
838 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
839 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000840 SLocEntryCursor.ReadSubBlockID();
841 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000842 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000843 return Failure;
844 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000845 continue;
846 }
847
848 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000849 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000850 continue;
851 }
852
853 // Read a record.
854 const char *BlobStart;
855 unsigned BlobLen;
856 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000857 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000858 default: // Default behavior: ignore.
859 break;
860
Chris Lattner2c78b872009-04-14 23:22:57 +0000861 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000862 if (ParseLineTable(SourceMgr, Record))
863 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000864 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000865
866 case pch::SM_HEADER_FILE_INFO: {
867 HeaderFileInfo HFI;
868 HFI.isImport = Record[0];
869 HFI.DirInfo = Record[1];
870 HFI.NumIncludes = Record[2];
871 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000872 if (Listener)
873 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000874 break;
875 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000876
877 case pch::SM_SLOC_FILE_ENTRY:
878 case pch::SM_SLOC_BUFFER_ENTRY:
879 case pch::SM_SLOC_INSTANTIATION_ENTRY:
880 // Once we hit one of the source location entries, we're done.
881 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000882 }
883 }
884}
885
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000886/// \brief Read in the source location entry with the given ID.
887PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
888 if (ID == 0)
889 return Success;
890
891 if (ID > TotalNumSLocEntries) {
892 Error("source location entry ID out-of-range for PCH file");
893 return Failure;
894 }
895
896 ++NumSLocEntriesRead;
897 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
898 unsigned Code = SLocEntryCursor.ReadCode();
899 if (Code == llvm::bitc::END_BLOCK ||
900 Code == llvm::bitc::ENTER_SUBBLOCK ||
901 Code == llvm::bitc::DEFINE_ABBREV) {
902 Error("incorrectly-formatted source location entry in PCH file");
903 return Failure;
904 }
905
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000906 RecordData Record;
907 const char *BlobStart;
908 unsigned BlobLen;
909 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
910 default:
911 Error("incorrectly-formatted source location entry in PCH file");
912 return Failure;
913
914 case pch::SM_SLOC_FILE_ENTRY: {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000915 const FileEntry *File = FileMgr.getFile(BlobStart, BlobStart + BlobLen);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000916 if (File == 0) {
917 std::string ErrorStr = "could not find file '";
918 ErrorStr.append(BlobStart, BlobLen);
919 ErrorStr += "' referenced by PCH file";
920 Error(ErrorStr.c_str());
921 return Failure;
922 }
923
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000924 FileID FID = SourceMgr.createFileID(File,
925 SourceLocation::getFromRawEncoding(Record[1]),
926 (SrcMgr::CharacteristicKind)Record[2],
927 ID, Record[0]);
928 if (Record[3])
929 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
930 .setHasLineDirectives();
931
932 break;
933 }
934
935 case pch::SM_SLOC_BUFFER_ENTRY: {
936 const char *Name = BlobStart;
937 unsigned Offset = Record[0];
938 unsigned Code = SLocEntryCursor.ReadCode();
939 Record.clear();
940 unsigned RecCode
941 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
942 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
943 (void)RecCode;
944 llvm::MemoryBuffer *Buffer
945 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
946 BlobStart + BlobLen - 1,
947 Name);
948 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
949
Douglas Gregor92b059e2009-04-28 20:33:11 +0000950 if (strcmp(Name, "<built-in>") == 0) {
951 PCHPredefinesBufferID = BufferID;
952 PCHPredefines = BlobStart;
953 PCHPredefinesLen = BlobLen - 1;
954 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000955
956 break;
957 }
958
959 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
960 SourceLocation SpellingLoc
961 = SourceLocation::getFromRawEncoding(Record[1]);
962 SourceMgr.createInstantiationLoc(SpellingLoc,
963 SourceLocation::getFromRawEncoding(Record[2]),
964 SourceLocation::getFromRawEncoding(Record[3]),
965 Record[4],
966 ID,
967 Record[0]);
968 break;
969 }
970 }
971
972 return Success;
973}
974
Chris Lattner6367f6d2009-04-27 01:05:14 +0000975/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
976/// specified cursor. Read the abbreviations that are at the top of the block
977/// and then leave the cursor pointing into the block.
978bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
979 unsigned BlockID) {
980 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000981 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000982 return Failure;
983 }
984
Chris Lattner6367f6d2009-04-27 01:05:14 +0000985 while (true) {
986 unsigned Code = Cursor.ReadCode();
987
988 // We expect all abbrevs to be at the start of the block.
989 if (Code != llvm::bitc::DEFINE_ABBREV)
990 return false;
991 Cursor.ReadAbbrevRecord();
992 }
993}
994
Douglas Gregor37e26842009-04-21 23:56:24 +0000995void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000996 assert(PP && "Forgot to set Preprocessor ?");
997
Douglas Gregor37e26842009-04-21 23:56:24 +0000998 // Keep track of where we are in the stream, then jump back there
999 // after reading this macro.
1000 SavedStreamPosition SavedPosition(Stream);
1001
1002 Stream.JumpToBit(Offset);
1003 RecordData Record;
1004 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1005 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +00001006
Douglas Gregor37e26842009-04-21 23:56:24 +00001007 while (true) {
1008 unsigned Code = Stream.ReadCode();
1009 switch (Code) {
1010 case llvm::bitc::END_BLOCK:
1011 return;
1012
1013 case llvm::bitc::ENTER_SUBBLOCK:
1014 // No known subblocks, always skip them.
1015 Stream.ReadSubBlockID();
1016 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001017 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001018 return;
1019 }
1020 continue;
1021
1022 case llvm::bitc::DEFINE_ABBREV:
1023 Stream.ReadAbbrevRecord();
1024 continue;
1025 default: break;
1026 }
1027
1028 // Read a record.
1029 Record.clear();
1030 pch::PreprocessorRecordTypes RecType =
1031 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1032 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001033 case pch::PP_MACRO_OBJECT_LIKE:
1034 case pch::PP_MACRO_FUNCTION_LIKE: {
1035 // If we already have a macro, that means that we've hit the end
1036 // of the definition of the macro we were looking for. We're
1037 // done.
1038 if (Macro)
1039 return;
1040
1041 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1042 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001043 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001044 return;
1045 }
1046 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1047 bool isUsed = Record[2];
1048
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001049 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001050 MI->setIsUsed(isUsed);
1051
1052 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1053 // Decode function-like macro info.
1054 bool isC99VarArgs = Record[3];
1055 bool isGNUVarArgs = Record[4];
1056 MacroArgs.clear();
1057 unsigned NumArgs = Record[5];
1058 for (unsigned i = 0; i != NumArgs; ++i)
1059 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1060
1061 // Install function-like macro info.
1062 MI->setIsFunctionLike();
1063 if (isC99VarArgs) MI->setIsC99Varargs();
1064 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001065 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001066 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001067 }
1068
1069 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001070 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001071
1072 // Remember that we saw this macro last so that we add the tokens that
1073 // form its body to it.
1074 Macro = MI;
1075 ++NumMacrosRead;
1076 break;
1077 }
1078
1079 case pch::PP_TOKEN: {
1080 // If we see a TOKEN before a PP_MACRO_*, then the file is
1081 // erroneous, just pretend we didn't see this.
1082 if (Macro == 0) break;
1083
1084 Token Tok;
1085 Tok.startToken();
1086 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1087 Tok.setLength(Record[1]);
1088 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1089 Tok.setIdentifierInfo(II);
1090 Tok.setKind((tok::TokenKind)Record[3]);
1091 Tok.setFlag((Token::TokenFlags)Record[4]);
1092 Macro->AddTokenToBody(Tok);
1093 break;
1094 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001095 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001096 }
1097}
1098
Douglas Gregor668c1a42009-04-21 22:25:48 +00001099PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001100PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001101 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001102 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001103 return Failure;
1104 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001105
1106 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001107 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001108 while (!Stream.AtEndOfStream()) {
1109 unsigned Code = Stream.ReadCode();
1110 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001111 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001112 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001113 return Failure;
1114 }
Chris Lattner7356a312009-04-11 21:15:38 +00001115
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001116 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001117 }
1118
1119 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1120 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001121 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1122 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001123 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001124 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001125 return Failure;
1126 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001127 break;
1128
Chris Lattner6367f6d2009-04-27 01:05:14 +00001129 case pch::DECLS_BLOCK_ID:
1130 // We lazily load the decls block, but we want to set up the
1131 // DeclsCursor cursor to point into it. Clone our current bitcode
1132 // cursor to it, enter the block and read the abbrevs in that block.
1133 // With the main cursor, we just skip over it.
1134 DeclsCursor = Stream;
1135 if (Stream.SkipBlock() || // Skip with the main cursor.
1136 // Read the abbrevs.
1137 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001138 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001139 return Failure;
1140 }
1141 break;
1142
Chris Lattner7356a312009-04-11 21:15:38 +00001143 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001144 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001145 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001146 return Failure;
1147 }
1148 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001149
Douglas Gregor14f79002009-04-10 03:52:48 +00001150 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001151 switch (ReadSourceManagerBlock()) {
1152 case Success:
1153 break;
1154
1155 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001156 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001157 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001158
1159 case IgnorePCH:
1160 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001161 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001162 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001163 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001164 continue;
1165 }
1166
1167 if (Code == llvm::bitc::DEFINE_ABBREV) {
1168 Stream.ReadAbbrevRecord();
1169 continue;
1170 }
1171
1172 // Read and process a record.
1173 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001174 const char *BlobStart = 0;
1175 unsigned BlobLen = 0;
1176 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1177 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001178 default: // Default behavior: ignore.
1179 break;
1180
1181 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001182 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001183 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001184 return Failure;
1185 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001186 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001187 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001188 break;
1189
1190 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001191 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001192 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001193 return Failure;
1194 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001195 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001196 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001197 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001198
1199 case pch::LANGUAGE_OPTIONS:
1200 if (ParseLanguageOptions(Record))
1201 return IgnorePCH;
1202 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001203
Douglas Gregorab41e632009-04-27 22:23:34 +00001204 case pch::METADATA: {
1205 if (Record[0] != pch::VERSION_MAJOR) {
1206 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1207 : diag::warn_pch_version_too_new);
1208 return IgnorePCH;
1209 }
1210
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001211 if (Listener) {
1212 std::string TargetTriple(BlobStart, BlobLen);
1213 if (Listener->ReadTargetTriple(TargetTriple))
1214 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001215 }
1216 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001217 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001218
1219 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001220 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001221 if (Record[0]) {
1222 IdentifierLookupTable
1223 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001224 (const unsigned char *)IdentifierTableData + Record[0],
1225 (const unsigned char *)IdentifierTableData,
1226 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001227 if (PP)
1228 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001229 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001230 break;
1231
1232 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001233 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001234 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001235 return Failure;
1236 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001237 IdentifierOffsets = (const uint32_t *)BlobStart;
1238 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001239 if (PP)
1240 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001241 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001242
1243 case pch::EXTERNAL_DEFINITIONS:
1244 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001245 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001246 return Failure;
1247 }
1248 ExternalDefinitions.swap(Record);
1249 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001250
Douglas Gregorad1de002009-04-18 05:55:16 +00001251 case pch::SPECIAL_TYPES:
1252 SpecialTypes.swap(Record);
1253 break;
1254
Douglas Gregor3e1af842009-04-17 22:13:46 +00001255 case pch::STATISTICS:
1256 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001257 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001258 TotalLexicalDeclContexts = Record[2];
1259 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001260 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001261
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001262 case pch::TENTATIVE_DEFINITIONS:
1263 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001264 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001265 return Failure;
1266 }
1267 TentativeDefinitions.swap(Record);
1268 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001269
1270 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1271 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001272 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001273 return Failure;
1274 }
1275 LocallyScopedExternalDecls.swap(Record);
1276 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001277
Douglas Gregor83941df2009-04-25 17:48:32 +00001278 case pch::SELECTOR_OFFSETS:
1279 SelectorOffsets = (const uint32_t *)BlobStart;
1280 TotalNumSelectors = Record[0];
1281 SelectorsLoaded.resize(TotalNumSelectors);
1282 break;
1283
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001284 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001285 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1286 if (Record[0])
1287 MethodPoolLookupTable
1288 = PCHMethodPoolLookupTable::Create(
1289 MethodPoolLookupTableData + Record[0],
1290 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001291 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001292 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001293 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001294
1295 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001296 if (!Record.empty() && Listener)
1297 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001298 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001299
1300 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001301 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001302 TotalNumSLocEntries = Record[0];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001303 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001304 TotalNumSLocEntries,
1305 Record[1]);
1306 break;
1307
1308 case pch::SOURCE_LOCATION_PRELOADS:
1309 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1310 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1311 if (Result != Success)
1312 return Result;
1313 }
1314 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001315
1316 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001317 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001318 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1319 (const unsigned char *)BlobStart,
1320 NumStatHits, NumStatMisses));
1321 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001322
1323 case pch::EXT_VECTOR_DECLS:
1324 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001325 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001326 return Failure;
1327 }
1328 ExtVectorDecls.swap(Record);
1329 break;
1330
1331 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1332 if (!ObjCCategoryImpls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001333 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001334 return Failure;
1335 }
1336 ObjCCategoryImpls.swap(Record);
1337 break;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001338
1339 case pch::ORIGINAL_FILE_NAME:
1340 OriginalFileName.assign(BlobStart, BlobLen);
1341 break;
Douglas Gregor2e222532009-07-02 17:08:52 +00001342
1343 case pch::COMMENT_RANGES:
1344 Comments = (SourceRange *)BlobStart;
1345 NumComments = BlobLen / sizeof(SourceRange);
1346 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001347 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001348 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001349 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001350 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001351}
1352
Douglas Gregore1d918e2009-04-10 23:10:45 +00001353PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001354 // Set the PCH file name.
1355 this->FileName = FileName;
1356
Douglas Gregor2cf26342009-04-09 22:27:44 +00001357 // Open the PCH file.
1358 std::string ErrStr;
1359 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001360 if (!Buffer) {
1361 Error(ErrStr.c_str());
1362 return IgnorePCH;
1363 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001364
1365 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001366 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1367 (const unsigned char *)Buffer->getBufferEnd());
1368 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001369
1370 // Sniff for the signature.
1371 if (Stream.Read(8) != 'C' ||
1372 Stream.Read(8) != 'P' ||
1373 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001374 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001375 Diag(diag::err_not_a_pch_file) << FileName;
1376 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001377 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001378
Douglas Gregor2cf26342009-04-09 22:27:44 +00001379 while (!Stream.AtEndOfStream()) {
1380 unsigned Code = Stream.ReadCode();
1381
Douglas Gregore1d918e2009-04-10 23:10:45 +00001382 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001383 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001384 return Failure;
1385 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001386
1387 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001388
Douglas Gregor2cf26342009-04-09 22:27:44 +00001389 // We only know the PCH subblock ID.
1390 switch (BlockID) {
1391 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001392 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001393 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001394 return Failure;
1395 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001396 break;
1397 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001398 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001399 case Success:
1400 break;
1401
1402 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001403 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001404
1405 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001406 // FIXME: We could consider reading through to the end of this
1407 // PCH block, skipping subblocks, to see if there are other
1408 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001409
1410 // Clear out any preallocated source location entries, so that
1411 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001412 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001413
1414 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001415 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001416
Douglas Gregore1d918e2009-04-10 23:10:45 +00001417 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001418 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001419 break;
1420 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001421 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001422 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001423 return Failure;
1424 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425 break;
1426 }
1427 }
Douglas Gregor92b059e2009-04-28 20:33:11 +00001428
1429 // Check the predefines buffer.
1430 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1431 PCHPredefinesBufferID))
1432 return IgnorePCH;
1433
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001434 if (PP) {
1435 // Initialization of builtins and library builtins occurs before the
1436 // PCH file is read, so there may be some identifiers that were
1437 // loaded into the IdentifierTable before we intercepted the
1438 // creation of identifiers. Iterate through the list of known
1439 // identifiers and determine whether we have to establish
1440 // preprocessor definitions or top-level identifier declaration
1441 // chains for those identifiers.
1442 //
1443 // We copy the IdentifierInfo pointers to a small vector first,
1444 // since de-serializing declarations or macro definitions can add
1445 // new entries into the identifier table, invalidating the
1446 // iterators.
1447 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1448 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1449 IdEnd = PP->getIdentifierTable().end();
1450 Id != IdEnd; ++Id)
1451 Identifiers.push_back(Id->second);
1452 PCHIdentifierLookupTable *IdTable
1453 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1454 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1455 IdentifierInfo *II = Identifiers[I];
1456 // Look in the on-disk hash table for an entry for
1457 PCHIdentifierLookupTrait Info(*this, II);
1458 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1459 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1460 if (Pos == IdTable->end())
1461 continue;
1462
1463 // Dereferencing the iterator has the effect of populating the
1464 // IdentifierInfo node with the various declarations it needs.
1465 (void)*Pos;
1466 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001467 }
1468
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001469 if (Context)
1470 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001471
Douglas Gregor668c1a42009-04-21 22:25:48 +00001472 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001473}
1474
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001475void PCHReader::InitializeContext(ASTContext &Ctx) {
1476 Context = &Ctx;
1477 assert(Context && "Passed null context!");
1478
1479 assert(PP && "Forgot to set Preprocessor ?");
1480 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1481 PP->getHeaderSearchInfo().SetExternalLookup(this);
1482
1483 // Load the translation unit declaration
1484 ReadDeclRecord(DeclOffsets[0], 0);
1485
1486 // Load the special types.
1487 Context->setBuiltinVaListType(
1488 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1489 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1490 Context->setObjCIdType(GetType(Id));
1491 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1492 Context->setObjCSelType(GetType(Sel));
1493 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1494 Context->setObjCProtoType(GetType(Proto));
1495 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1496 Context->setObjCClassType(GetType(Class));
1497 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1498 Context->setCFConstantStringType(GetType(String));
1499 if (unsigned FastEnum
1500 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1501 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1502}
1503
Douglas Gregorb64c1932009-05-12 01:31:05 +00001504/// \brief Retrieve the name of the original source file name
1505/// directly from the PCH file, without actually loading the PCH
1506/// file.
1507std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1508 // Open the PCH file.
1509 std::string ErrStr;
1510 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1511 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1512 if (!Buffer) {
1513 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1514 return std::string();
1515 }
1516
1517 // Initialize the stream
1518 llvm::BitstreamReader StreamFile;
1519 llvm::BitstreamCursor Stream;
1520 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1521 (const unsigned char *)Buffer->getBufferEnd());
1522 Stream.init(StreamFile);
1523
1524 // Sniff for the signature.
1525 if (Stream.Read(8) != 'C' ||
1526 Stream.Read(8) != 'P' ||
1527 Stream.Read(8) != 'C' ||
1528 Stream.Read(8) != 'H') {
1529 fprintf(stderr,
1530 "error: '%s' does not appear to be a precompiled header file\n",
1531 PCHFileName.c_str());
1532 return std::string();
1533 }
1534
1535 RecordData Record;
1536 while (!Stream.AtEndOfStream()) {
1537 unsigned Code = Stream.ReadCode();
1538
1539 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1540 unsigned BlockID = Stream.ReadSubBlockID();
1541
1542 // We only know the PCH subblock ID.
1543 switch (BlockID) {
1544 case pch::PCH_BLOCK_ID:
1545 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1546 fprintf(stderr, "error: malformed block record in PCH file\n");
1547 return std::string();
1548 }
1549 break;
1550
1551 default:
1552 if (Stream.SkipBlock()) {
1553 fprintf(stderr, "error: malformed block record in PCH file\n");
1554 return std::string();
1555 }
1556 break;
1557 }
1558 continue;
1559 }
1560
1561 if (Code == llvm::bitc::END_BLOCK) {
1562 if (Stream.ReadBlockEnd()) {
1563 fprintf(stderr, "error: error at end of module block in PCH file\n");
1564 return std::string();
1565 }
1566 continue;
1567 }
1568
1569 if (Code == llvm::bitc::DEFINE_ABBREV) {
1570 Stream.ReadAbbrevRecord();
1571 continue;
1572 }
1573
1574 Record.clear();
1575 const char *BlobStart = 0;
1576 unsigned BlobLen = 0;
1577 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1578 == pch::ORIGINAL_FILE_NAME)
1579 return std::string(BlobStart, BlobLen);
1580 }
1581
1582 return std::string();
1583}
1584
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001585/// \brief Parse the record that corresponds to a LangOptions data
1586/// structure.
1587///
1588/// This routine compares the language options used to generate the
1589/// PCH file against the language options set for the current
1590/// compilation. For each option, we classify differences between the
1591/// two compiler states as either "benign" or "important". Benign
1592/// differences don't matter, and we accept them without complaint
1593/// (and without modifying the language options). Differences between
1594/// the states for important options cause the PCH file to be
1595/// unusable, so we emit a warning and return true to indicate that
1596/// there was an error.
1597///
1598/// \returns true if the PCH file is unacceptable, false otherwise.
1599bool PCHReader::ParseLanguageOptions(
1600 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001601 if (Listener) {
1602 LangOptions LangOpts;
1603
1604 #define PARSE_LANGOPT(Option) \
1605 LangOpts.Option = Record[Idx]; \
1606 ++Idx
1607
1608 unsigned Idx = 0;
1609 PARSE_LANGOPT(Trigraphs);
1610 PARSE_LANGOPT(BCPLComment);
1611 PARSE_LANGOPT(DollarIdents);
1612 PARSE_LANGOPT(AsmPreprocessor);
1613 PARSE_LANGOPT(GNUMode);
1614 PARSE_LANGOPT(ImplicitInt);
1615 PARSE_LANGOPT(Digraphs);
1616 PARSE_LANGOPT(HexFloats);
1617 PARSE_LANGOPT(C99);
1618 PARSE_LANGOPT(Microsoft);
1619 PARSE_LANGOPT(CPlusPlus);
1620 PARSE_LANGOPT(CPlusPlus0x);
1621 PARSE_LANGOPT(CXXOperatorNames);
1622 PARSE_LANGOPT(ObjC1);
1623 PARSE_LANGOPT(ObjC2);
1624 PARSE_LANGOPT(ObjCNonFragileABI);
1625 PARSE_LANGOPT(PascalStrings);
1626 PARSE_LANGOPT(WritableStrings);
1627 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001628 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001629 PARSE_LANGOPT(Exceptions);
1630 PARSE_LANGOPT(NeXTRuntime);
1631 PARSE_LANGOPT(Freestanding);
1632 PARSE_LANGOPT(NoBuiltin);
1633 PARSE_LANGOPT(ThreadsafeStatics);
1634 PARSE_LANGOPT(Blocks);
1635 PARSE_LANGOPT(EmitAllDecls);
1636 PARSE_LANGOPT(MathErrno);
1637 PARSE_LANGOPT(OverflowChecking);
1638 PARSE_LANGOPT(HeinousExtensions);
1639 PARSE_LANGOPT(Optimize);
1640 PARSE_LANGOPT(OptimizeSize);
1641 PARSE_LANGOPT(Static);
1642 PARSE_LANGOPT(PICLevel);
1643 PARSE_LANGOPT(GNUInline);
1644 PARSE_LANGOPT(NoInline);
1645 PARSE_LANGOPT(AccessControl);
1646 PARSE_LANGOPT(CharIsSigned);
1647 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1648 ++Idx;
1649 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1650 ++Idx;
1651 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001652 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001653 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001654
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001655 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001656 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001657
1658 return false;
1659}
1660
Douglas Gregor2e222532009-07-02 17:08:52 +00001661void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1662 Comments.resize(NumComments);
1663 std::copy(this->Comments, this->Comments + NumComments,
1664 Comments.begin());
1665}
1666
Douglas Gregor2cf26342009-04-09 22:27:44 +00001667/// \brief Read and return the type at the given offset.
1668///
1669/// This routine actually reads the record corresponding to the type
1670/// at the given offset in the bitstream. It is a helper routine for
1671/// GetType, which deals with reading type IDs.
1672QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001673 // Keep track of where we are in the stream, then jump back there
1674 // after reading this type.
1675 SavedStreamPosition SavedPosition(Stream);
1676
Douglas Gregord89275b2009-07-06 18:54:52 +00001677 // Note that we are loading a type record.
1678 LoadingTypeOrDecl Loading(*this);
1679
Douglas Gregor2cf26342009-04-09 22:27:44 +00001680 Stream.JumpToBit(Offset);
1681 RecordData Record;
1682 unsigned Code = Stream.ReadCode();
1683 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001684 case pch::TYPE_EXT_QUAL: {
1685 assert(Record.size() == 3 &&
1686 "Incorrect encoding of extended qualifier type");
1687 QualType Base = GetType(Record[0]);
1688 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1689 unsigned AddressSpace = Record[2];
1690
1691 QualType T = Base;
1692 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001693 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001694 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001695 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001696 return T;
1697 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001698
Douglas Gregor2cf26342009-04-09 22:27:44 +00001699 case pch::TYPE_FIXED_WIDTH_INT: {
1700 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001701 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001702 }
1703
1704 case pch::TYPE_COMPLEX: {
1705 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1706 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001707 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001708 }
1709
1710 case pch::TYPE_POINTER: {
1711 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1712 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001713 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001714 }
1715
1716 case pch::TYPE_BLOCK_POINTER: {
1717 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1718 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001719 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001720 }
1721
1722 case pch::TYPE_LVALUE_REFERENCE: {
1723 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1724 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001725 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001726 }
1727
1728 case pch::TYPE_RVALUE_REFERENCE: {
1729 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1730 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001731 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001732 }
1733
1734 case pch::TYPE_MEMBER_POINTER: {
1735 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1736 QualType PointeeType = GetType(Record[0]);
1737 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001738 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739 }
1740
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001741 case pch::TYPE_CONSTANT_ARRAY: {
1742 QualType ElementType = GetType(Record[0]);
1743 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1744 unsigned IndexTypeQuals = Record[2];
1745 unsigned Idx = 3;
1746 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001747 return Context->getConstantArrayType(ElementType, Size,
1748 ASM, IndexTypeQuals);
1749 }
1750
1751 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1752 QualType ElementType = GetType(Record[0]);
1753 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1754 unsigned IndexTypeQuals = Record[2];
1755 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1756 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1757 unsigned Idx = 5;
1758 llvm::APInt Size = ReadAPInt(Record, Idx);
1759 return Context->getConstantArrayWithExprType(ElementType,
1760 Size, ReadTypeExpr(),
1761 ASM, IndexTypeQuals,
1762 SourceRange(LBLoc, RBLoc));
1763 }
1764
1765 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1766 QualType ElementType = GetType(Record[0]);
1767 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1768 unsigned IndexTypeQuals = Record[2];
1769 unsigned Idx = 3;
1770 llvm::APInt Size = ReadAPInt(Record, Idx);
1771 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1772 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001773 }
1774
1775 case pch::TYPE_INCOMPLETE_ARRAY: {
1776 QualType ElementType = GetType(Record[0]);
1777 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1778 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001779 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001780 }
1781
1782 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001783 QualType ElementType = GetType(Record[0]);
1784 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1785 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001786 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1787 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001788 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001789 ASM, IndexTypeQuals,
1790 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001791 }
1792
1793 case pch::TYPE_VECTOR: {
1794 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001795 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001796 return QualType();
1797 }
1798
1799 QualType ElementType = GetType(Record[0]);
1800 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001801 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001802 }
1803
1804 case pch::TYPE_EXT_VECTOR: {
1805 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001806 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001807 return QualType();
1808 }
1809
1810 QualType ElementType = GetType(Record[0]);
1811 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001812 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001813 }
1814
1815 case pch::TYPE_FUNCTION_NO_PROTO: {
1816 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001817 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001818 return QualType();
1819 }
1820 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001821 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001822 }
1823
1824 case pch::TYPE_FUNCTION_PROTO: {
1825 QualType ResultType = GetType(Record[0]);
1826 unsigned Idx = 1;
1827 unsigned NumParams = Record[Idx++];
1828 llvm::SmallVector<QualType, 16> ParamTypes;
1829 for (unsigned I = 0; I != NumParams; ++I)
1830 ParamTypes.push_back(GetType(Record[Idx++]));
1831 bool isVariadic = Record[Idx++];
1832 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001833 bool hasExceptionSpec = Record[Idx++];
1834 bool hasAnyExceptionSpec = Record[Idx++];
1835 unsigned NumExceptions = Record[Idx++];
1836 llvm::SmallVector<QualType, 2> Exceptions;
1837 for (unsigned I = 0; I != NumExceptions; ++I)
1838 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001839 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001840 isVariadic, Quals, hasExceptionSpec,
1841 hasAnyExceptionSpec, NumExceptions,
1842 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001843 }
1844
1845 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001846 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001847 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001848
1849 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001850 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001851
1852 case pch::TYPE_TYPEOF: {
1853 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001854 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001855 return QualType();
1856 }
1857 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001858 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001859 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001860
1861 case pch::TYPE_DECLTYPE:
1862 return Context->getDecltypeType(ReadTypeExpr());
1863
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001864 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001865 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001866 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001867
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001868 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001869 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001870 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001871
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001872 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregora02b1472009-04-28 21:53:25 +00001873 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001874 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001875 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001876
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001877 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1878 unsigned Idx = 0;
1879 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1880 unsigned NumProtos = Record[Idx++];
1881 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1882 for (unsigned I = 0; I != NumProtos; ++I)
1883 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Douglas Gregor75fdb232009-05-22 22:45:36 +00001884 return Context->getObjCQualifiedInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001885 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001886
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001887 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001888 unsigned Idx = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001889 ObjCInterfaceDecl *ItfD =
1890 cast_or_null<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001891 unsigned NumProtos = Record[Idx++];
1892 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1893 for (unsigned I = 0; I != NumProtos; ++I)
1894 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001895 return Context->getObjCObjectPointerType(ItfD, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001896 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001897 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001898 // Suppress a GCC warning
1899 return QualType();
1900}
1901
Douglas Gregor2cf26342009-04-09 22:27:44 +00001902
Douglas Gregor8038d512009-04-10 17:25:41 +00001903QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001904 unsigned Quals = ID & 0x07;
1905 unsigned Index = ID >> 3;
1906
1907 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1908 QualType T;
1909 switch ((pch::PredefinedTypeIDs)Index) {
1910 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001911 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1912 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001913
1914 case pch::PREDEF_TYPE_CHAR_U_ID:
1915 case pch::PREDEF_TYPE_CHAR_S_ID:
1916 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001917 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001918 break;
1919
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001920 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1921 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1922 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1923 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1924 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001925 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001926 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1927 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1928 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1929 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1930 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1931 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001932 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001933 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1934 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1935 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1936 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1937 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001938 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001939 }
1940
1941 assert(!T.isNull() && "Unknown predefined type");
1942 return T.getQualifiedType(Quals);
1943 }
1944
1945 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001946 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001947 if (!TypesLoaded[Index])
1948 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001949
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001950 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001951}
1952
Douglas Gregor8038d512009-04-10 17:25:41 +00001953Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001954 if (ID == 0)
1955 return 0;
1956
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001957 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001958 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001959 return 0;
1960 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001962 unsigned Index = ID - 1;
1963 if (!DeclsLoaded[Index])
1964 ReadDeclRecord(DeclOffsets[Index], Index);
1965
1966 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001967}
1968
Chris Lattner887e2b32009-04-27 05:46:25 +00001969/// \brief Resolve the offset of a statement into a statement.
1970///
1971/// This operation will read a new statement from the external
1972/// source each time it is called, and is meant to be used via a
1973/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1974Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001975 // Since we know tha this statement is part of a decl, make sure to use the
1976 // decl cursor to read it.
1977 DeclsCursor.JumpToBit(Offset);
1978 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001979}
1980
Douglas Gregor2cf26342009-04-09 22:27:44 +00001981bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001982 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001983 assert(DC->hasExternalLexicalStorage() &&
1984 "DeclContext has no lexical decls in storage");
1985 uint64_t Offset = DeclContextOffsets[DC].first;
1986 assert(Offset && "DeclContext has no lexical decls in storage");
1987
Douglas Gregor0b748912009-04-14 21:18:50 +00001988 // Keep track of where we are in the stream, then jump back there
1989 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001990 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001991
Douglas Gregor2cf26342009-04-09 22:27:44 +00001992 // Load the record containing all of the declarations lexically in
1993 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001994 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001995 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001996 unsigned Code = DeclsCursor.ReadCode();
1997 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001998 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001999 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2000
2001 // Load all of the declaration IDs
2002 Decls.clear();
2003 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002004 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002005 return false;
2006}
2007
2008bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002009 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002010 assert(DC->hasExternalVisibleStorage() &&
2011 "DeclContext has no visible decls in storage");
2012 uint64_t Offset = DeclContextOffsets[DC].second;
2013 assert(Offset && "DeclContext has no visible decls in storage");
2014
Douglas Gregor0b748912009-04-14 21:18:50 +00002015 // Keep track of where we are in the stream, then jump back there
2016 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002017 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002018
Douglas Gregor2cf26342009-04-09 22:27:44 +00002019 // Load the record containing all of the declarations visible in
2020 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002021 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002023 unsigned Code = DeclsCursor.ReadCode();
2024 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002025 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002026 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2027 if (Record.size() == 0)
2028 return false;
2029
2030 Decls.clear();
2031
2032 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002033 while (Idx < Record.size()) {
2034 Decls.push_back(VisibleDeclaration());
2035 Decls.back().Name = ReadDeclarationName(Record, Idx);
2036
Douglas Gregor2cf26342009-04-09 22:27:44 +00002037 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002038 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002039 LoadedDecls.reserve(Size);
2040 for (unsigned I = 0; I < Size; ++I)
2041 LoadedDecls.push_back(Record[Idx++]);
2042 }
2043
Douglas Gregor25123082009-04-22 22:34:57 +00002044 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002045 return false;
2046}
2047
Douglas Gregorfdd01722009-04-14 00:24:19 +00002048void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002049 this->Consumer = Consumer;
2050
Douglas Gregorfdd01722009-04-14 00:24:19 +00002051 if (!Consumer)
2052 return;
2053
2054 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2055 Decl *D = GetDecl(ExternalDefinitions[I]);
2056 DeclGroupRef DG(D);
2057 Consumer->HandleTopLevelDecl(DG);
2058 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002059
2060 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2061 DeclGroupRef DG(InterestingDecls[I]);
2062 Consumer->HandleTopLevelDecl(DG);
2063 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002064}
2065
Douglas Gregor2cf26342009-04-09 22:27:44 +00002066void PCHReader::PrintStats() {
2067 std::fprintf(stderr, "*** PCH Statistics:\n");
2068
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002069 unsigned NumTypesLoaded
2070 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2071 (Type *)0);
2072 unsigned NumDeclsLoaded
2073 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2074 (Decl *)0);
2075 unsigned NumIdentifiersLoaded
2076 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2077 IdentifiersLoaded.end(),
2078 (IdentifierInfo *)0);
2079 unsigned NumSelectorsLoaded
2080 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2081 SelectorsLoaded.end(),
2082 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002083
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002084 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2085 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002086 if (TotalNumSLocEntries)
2087 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2088 NumSLocEntriesRead, TotalNumSLocEntries,
2089 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002090 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002091 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002092 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2093 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2094 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002095 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002096 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2097 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002098 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002099 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002100 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2101 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002102 if (TotalNumSelectors)
2103 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2104 NumSelectorsLoaded, TotalNumSelectors,
2105 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2106 if (TotalNumStatements)
2107 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2108 NumStatementsRead, TotalNumStatements,
2109 ((float)NumStatementsRead/TotalNumStatements * 100));
2110 if (TotalNumMacros)
2111 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2112 NumMacrosRead, TotalNumMacros,
2113 ((float)NumMacrosRead/TotalNumMacros * 100));
2114 if (TotalLexicalDeclContexts)
2115 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2116 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2117 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2118 * 100));
2119 if (TotalVisibleDeclContexts)
2120 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2121 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2122 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2123 * 100));
2124 if (TotalSelectorsInMethodPool) {
2125 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2126 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2127 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2128 * 100));
2129 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2130 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002131 std::fprintf(stderr, "\n");
2132}
2133
Douglas Gregor668c1a42009-04-21 22:25:48 +00002134void PCHReader::InitializeSema(Sema &S) {
2135 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002136 S.ExternalSource = this;
2137
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002138 // Makes sure any declarations that were deserialized "too early"
2139 // still get added to the identifier's declaration chains.
2140 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2141 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2142 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002143 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002144 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002145
2146 // If there were any tentative definitions, deserialize them and add
2147 // them to Sema's table of tentative definitions.
2148 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2149 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2150 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2151 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002152
2153 // If there were any locally-scoped external declarations,
2154 // deserialize them and add them to Sema's table of locally-scoped
2155 // external declarations.
2156 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2157 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2158 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2159 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002160
2161 // If there were any ext_vector type declarations, deserialize them
2162 // and add them to Sema's vector of such declarations.
2163 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2164 SemaObj->ExtVectorDecls.push_back(
2165 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2166
2167 // If there were any Objective-C category implementations,
2168 // deserialize them and add them to Sema's vector of such
2169 // definitions.
2170 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
2171 SemaObj->ObjCCategoryImpls.push_back(
2172 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002173}
2174
2175IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2176 // Try to find this name within our on-disk hash table
2177 PCHIdentifierLookupTable *IdTable
2178 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2179 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2180 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2181 if (Pos == IdTable->end())
2182 return 0;
2183
2184 // Dereferencing the iterator has the effect of building the
2185 // IdentifierInfo node and populating it with the various
2186 // declarations it needs.
2187 return *Pos;
2188}
2189
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002190std::pair<ObjCMethodList, ObjCMethodList>
2191PCHReader::ReadMethodPool(Selector Sel) {
2192 if (!MethodPoolLookupTable)
2193 return std::pair<ObjCMethodList, ObjCMethodList>();
2194
2195 // Try to find this selector within our on-disk hash table.
2196 PCHMethodPoolLookupTable *PoolTable
2197 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2198 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002199 if (Pos == PoolTable->end()) {
2200 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002201 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002202 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002203
Douglas Gregor83941df2009-04-25 17:48:32 +00002204 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002205 return *Pos;
2206}
2207
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002208void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002209 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002210 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002211 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002212}
2213
Douglas Gregord89275b2009-07-06 18:54:52 +00002214/// \brief Set the globally-visible declarations associated with the given
2215/// identifier.
2216///
2217/// If the PCH reader is currently in a state where the given declaration IDs
2218/// cannot safely be resolved, they are queued until it is safe to resolve
2219/// them.
2220///
2221/// \param II an IdentifierInfo that refers to one or more globally-visible
2222/// declarations.
2223///
2224/// \param DeclIDs the set of declaration IDs with the name @p II that are
2225/// visible at global scope.
2226///
2227/// \param Nonrecursive should be true to indicate that the caller knows that
2228/// this call is non-recursive, and therefore the globally-visible declarations
2229/// will not be placed onto the pending queue.
2230void
2231PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2232 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2233 bool Nonrecursive) {
2234 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2235 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2236 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2237 PII.II = II;
2238 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2239 PII.DeclIDs.push_back(DeclIDs[I]);
2240 return;
2241 }
2242
2243 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2244 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2245 if (SemaObj) {
2246 // Introduce this declaration into the translation-unit scope
2247 // and add it to the declaration chain for this identifier, so
2248 // that (unqualified) name lookup will find it.
2249 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2250 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2251 } else {
2252 // Queue this declaration so that it will be added to the
2253 // translation unit scope and identifier's declaration chain
2254 // once a Sema object is known.
2255 PreloadedDecls.push_back(D);
2256 }
2257 }
2258}
2259
Chris Lattner7356a312009-04-11 21:15:38 +00002260IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002261 if (ID == 0)
2262 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002263
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002264 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002265 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002266 return 0;
2267 }
Chris Lattner7356a312009-04-11 21:15:38 +00002268
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002269 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002270 if (!IdentifiersLoaded[ID - 1]) {
2271 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002272 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002273
Douglas Gregor02fc7512009-04-28 20:01:51 +00002274 // All of the strings in the PCH file are preceded by a 16-bit
2275 // length. Extract that 16-bit length to avoid having to execute
2276 // strlen().
2277 const char *StrLenPtr = Str - 2;
2278 unsigned StrLen = (((unsigned) StrLenPtr[0])
2279 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2280 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002281 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002282 }
Chris Lattner7356a312009-04-11 21:15:38 +00002283
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002284 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002285}
2286
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002287void PCHReader::ReadSLocEntry(unsigned ID) {
2288 ReadSLocEntryRecord(ID);
2289}
2290
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002291Selector PCHReader::DecodeSelector(unsigned ID) {
2292 if (ID == 0)
2293 return Selector();
2294
Douglas Gregora02b1472009-04-28 21:53:25 +00002295 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002296 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002297
2298 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002299 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002300 return Selector();
2301 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002302
2303 unsigned Index = ID - 1;
2304 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2305 // Load this selector from the selector table.
2306 // FIXME: endianness portability issues with SelectorOffsets table
2307 PCHMethodPoolLookupTrait Trait(*this);
2308 SelectorsLoaded[Index]
2309 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2310 }
2311
2312 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002313}
2314
Douglas Gregor2cf26342009-04-09 22:27:44 +00002315DeclarationName
2316PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2317 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2318 switch (Kind) {
2319 case DeclarationName::Identifier:
2320 return DeclarationName(GetIdentifierInfo(Record, Idx));
2321
2322 case DeclarationName::ObjCZeroArgSelector:
2323 case DeclarationName::ObjCOneArgSelector:
2324 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002325 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002326
2327 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002328 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002329 GetType(Record[Idx++]));
2330
2331 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002332 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002333 GetType(Record[Idx++]));
2334
2335 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002336 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002337 GetType(Record[Idx++]));
2338
2339 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002340 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002341 (OverloadedOperatorKind)Record[Idx++]);
2342
2343 case DeclarationName::CXXUsingDirective:
2344 return DeclarationName::getUsingDirectiveName();
2345 }
2346
2347 // Required to silence GCC warning
2348 return DeclarationName();
2349}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002350
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002351/// \brief Read an integral value
2352llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2353 unsigned BitWidth = Record[Idx++];
2354 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2355 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2356 Idx += NumWords;
2357 return Result;
2358}
2359
2360/// \brief Read a signed integral value
2361llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2362 bool isUnsigned = Record[Idx++];
2363 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2364}
2365
Douglas Gregor17fc2232009-04-14 21:55:33 +00002366/// \brief Read a floating-point value
2367llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002368 return llvm::APFloat(ReadAPInt(Record, Idx));
2369}
2370
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002371// \brief Read a string
2372std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2373 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002374 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002375 Idx += Len;
2376 return Result;
2377}
2378
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002379DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002380 return Diag(SourceLocation(), DiagID);
2381}
2382
2383DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002384 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002385}
Douglas Gregor025452f2009-04-17 00:04:06 +00002386
Douglas Gregor668c1a42009-04-21 22:25:48 +00002387/// \brief Retrieve the identifier table associated with the
2388/// preprocessor.
2389IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002390 assert(PP && "Forgot to set Preprocessor ?");
2391 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002392}
2393
Douglas Gregor025452f2009-04-17 00:04:06 +00002394/// \brief Record that the given ID maps to the given switch-case
2395/// statement.
2396void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2397 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2398 SwitchCaseStmts[ID] = SC;
2399}
2400
2401/// \brief Retrieve the switch-case statement with the given ID.
2402SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2403 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2404 return SwitchCaseStmts[ID];
2405}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002406
2407/// \brief Record that the given label statement has been
2408/// deserialized and has the given ID.
2409void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2410 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2411 "Deserialized label twice");
2412 LabelStmts[ID] = S;
2413
2414 // If we've already seen any goto statements that point to this
2415 // label, resolve them now.
2416 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2417 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2418 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2419 Goto->second->setLabel(S);
2420 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002421
2422 // If we've already seen any address-label statements that point to
2423 // this label, resolve them now.
2424 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2425 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2426 = UnresolvedAddrLabelExprs.equal_range(ID);
2427 for (AddrLabelIter AddrLabel = AddrLabels.first;
2428 AddrLabel != AddrLabels.second; ++AddrLabel)
2429 AddrLabel->second->setLabel(S);
2430 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002431}
2432
2433/// \brief Set the label of the given statement to the label
2434/// identified by ID.
2435///
2436/// Depending on the order in which the label and other statements
2437/// referencing that label occur, this operation may complete
2438/// immediately (updating the statement) or it may queue the
2439/// statement to be back-patched later.
2440void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2441 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2442 if (Label != LabelStmts.end()) {
2443 // We've already seen this label, so set the label of the goto and
2444 // we're done.
2445 S->setLabel(Label->second);
2446 } else {
2447 // We haven't seen this label yet, so add this goto to the set of
2448 // unresolved goto statements.
2449 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2450 }
2451}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002452
2453/// \brief Set the label of the given expression to the label
2454/// identified by ID.
2455///
2456/// Depending on the order in which the label and other statements
2457/// referencing that label occur, this operation may complete
2458/// immediately (updating the statement) or it may queue the
2459/// statement to be back-patched later.
2460void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2461 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2462 if (Label != LabelStmts.end()) {
2463 // We've already seen this label, so set the label of the
2464 // label-address expression and we're done.
2465 S->setLabel(Label->second);
2466 } else {
2467 // We haven't seen this label yet, so add this label-address
2468 // expression to the set of unresolved label-address expressions.
2469 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2470 }
2471}
Douglas Gregord89275b2009-07-06 18:54:52 +00002472
2473
2474PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2475 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2476 Reader.CurrentlyLoadingTypeOrDecl = this;
2477}
2478
2479PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2480 if (!Parent) {
2481 // If any identifiers with corresponding top-level declarations have
2482 // been loaded, load those declarations now.
2483 while (!Reader.PendingIdentifierInfos.empty()) {
2484 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2485 Reader.PendingIdentifierInfos.front().DeclIDs,
2486 true);
2487 Reader.PendingIdentifierInfos.pop_front();
2488 }
2489 }
2490
2491 Reader.CurrentlyLoadingTypeOrDecl = Parent;
2492}