blob: 345e673b47193b981498bc34cb7b5d4bf2b47dca [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000018#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000022#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000023#include "llvm/Bitcode/BitstreamReader.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include <algorithm>
27#include <cstdio>
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Declaration deserialization
33//===----------------------------------------------------------------------===//
34namespace {
35 class VISIBILITY_HIDDEN PCHDeclReader {
36 PCHReader &Reader;
37 const PCHReader::RecordData &Record;
38 unsigned &Idx;
39
40 public:
41 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
42 unsigned &Idx)
43 : Reader(Reader), Record(Record), Idx(Idx) { }
44
45 void VisitDecl(Decl *D);
46 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
47 void VisitNamedDecl(NamedDecl *ND);
48 void VisitTypeDecl(TypeDecl *TD);
49 void VisitTypedefDecl(TypedefDecl *TD);
50 void VisitValueDecl(ValueDecl *VD);
51 void VisitVarDecl(VarDecl *VD);
52
53 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
54 };
55}
56
57void PCHDeclReader::VisitDecl(Decl *D) {
58 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
59 D->setLexicalDeclContext(
60 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
61 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
62 D->setInvalidDecl(Record[Idx++]);
63 // FIXME: hasAttrs
64 D->setImplicit(Record[Idx++]);
65 D->setAccess((AccessSpecifier)Record[Idx++]);
66}
67
68void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
69 VisitDecl(TU);
70}
71
72void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
73 VisitDecl(ND);
74 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
75}
76
77void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
78 VisitNamedDecl(TD);
79 // FIXME: circular dependencies here?
80 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
81}
82
83void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
84 VisitTypeDecl(TD);
85 TD->setUnderlyingType(Reader.GetType(Record[Idx++]));
86}
87
88void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
89 VisitNamedDecl(VD);
90 VD->setType(Reader.GetType(Record[Idx++]));
91}
92
93void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
94 VisitValueDecl(VD);
95 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
96 VD->setThreadSpecified(Record[Idx++]);
97 VD->setCXXDirectInitializer(Record[Idx++]);
98 VD->setDeclaredInCondition(Record[Idx++]);
99 VD->setPreviousDeclaration(
100 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
101 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
102}
103
104std::pair<uint64_t, uint64_t>
105PCHDeclReader::VisitDeclContext(DeclContext *DC) {
106 uint64_t LexicalOffset = Record[Idx++];
107 uint64_t VisibleOffset = 0;
108 if (DC->getPrimaryContext() == DC)
109 VisibleOffset = Record[Idx++];
110 return std::make_pair(LexicalOffset, VisibleOffset);
111}
112
113// FIXME: use the diagnostics machinery
114static bool Error(const char *Str) {
115 std::fprintf(stderr, "%s\n", Str);
116 return true;
117}
118
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000119/// \brief Check the contents of the predefines buffer against the
120/// contents of the predefines buffer used to build the PCH file.
121///
122/// The contents of the two predefines buffers should be the same. If
123/// not, then some command-line option changed the preprocessor state
124/// and we must reject the PCH file.
125///
126/// \param PCHPredef The start of the predefines buffer in the PCH
127/// file.
128///
129/// \param PCHPredefLen The length of the predefines buffer in the PCH
130/// file.
131///
132/// \param PCHBufferID The FileID for the PCH predefines buffer.
133///
134/// \returns true if there was a mismatch (in which case the PCH file
135/// should be ignored), or false otherwise.
136bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
137 unsigned PCHPredefLen,
138 FileID PCHBufferID) {
139 const char *Predef = PP.getPredefines().c_str();
140 unsigned PredefLen = PP.getPredefines().size();
141
142 // If the two predefines buffers compare equal, we're done!.
143 if (PredefLen == PCHPredefLen &&
144 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
145 return false;
146
147 // The predefines buffers are different. Produce a reasonable
148 // diagnostic showing where they are different.
149
150 // The source locations (potentially in the two different predefines
151 // buffers)
152 SourceLocation Loc1, Loc2;
153 SourceManager &SourceMgr = PP.getSourceManager();
154
155 // Create a source buffer for our predefines string, so
156 // that we can build a diagnostic that points into that
157 // source buffer.
158 FileID BufferID;
159 if (Predef && Predef[0]) {
160 llvm::MemoryBuffer *Buffer
161 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
162 "<built-in>");
163 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
164 }
165
166 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
167 std::pair<const char *, const char *> Locations
168 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
169
170 if (Locations.first != Predef + MinLen) {
171 // We found the location in the two buffers where there is a
172 // difference. Form source locations to point there (in both
173 // buffers).
174 unsigned Offset = Locations.first - Predef;
175 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
176 .getFileLocWithOffset(Offset);
177 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
178 .getFileLocWithOffset(Offset);
179 } else if (PredefLen > PCHPredefLen) {
180 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
181 .getFileLocWithOffset(MinLen);
182 } else {
183 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
184 .getFileLocWithOffset(MinLen);
185 }
186
187 Diag(Loc1, diag::warn_pch_preprocessor);
188 if (Loc2.isValid())
189 Diag(Loc2, diag::note_predef_in_pch);
190 Diag(diag::note_ignoring_pch) << FileName;
191 return true;
192}
193
Douglas Gregorab1cef72009-04-10 03:52:48 +0000194/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000195PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000196 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000197 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
198 Error("Malformed source manager block record");
199 return Failure;
200 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000201
202 SourceManager &SourceMgr = Context.getSourceManager();
203 RecordData Record;
204 while (true) {
205 unsigned Code = Stream.ReadCode();
206 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000207 if (Stream.ReadBlockEnd()) {
208 Error("Error at end of Source Manager block");
209 return Failure;
210 }
211
212 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000213 }
214
215 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
216 // No known subblocks, always skip them.
217 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000218 if (Stream.SkipBlock()) {
219 Error("Malformed block record");
220 return Failure;
221 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000222 continue;
223 }
224
225 if (Code == llvm::bitc::DEFINE_ABBREV) {
226 Stream.ReadAbbrevRecord();
227 continue;
228 }
229
230 // Read a record.
231 const char *BlobStart;
232 unsigned BlobLen;
233 Record.clear();
234 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
235 default: // Default behavior: ignore.
236 break;
237
238 case pch::SM_SLOC_FILE_ENTRY: {
239 // FIXME: We would really like to delay the creation of this
240 // FileEntry until it is actually required, e.g., when producing
241 // a diagnostic with a source location in this file.
242 const FileEntry *File
243 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
244 // FIXME: Error recovery if file cannot be found.
245 SourceMgr.createFileID(File,
246 SourceLocation::getFromRawEncoding(Record[1]),
247 (CharacteristicKind)Record[2]);
248 break;
249 }
250
251 case pch::SM_SLOC_BUFFER_ENTRY: {
252 const char *Name = BlobStart;
253 unsigned Code = Stream.ReadCode();
254 Record.clear();
255 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
256 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000257 llvm::MemoryBuffer *Buffer
258 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
259 BlobStart + BlobLen - 1,
260 Name);
261 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
262
263 if (strcmp(Name, "<built-in>") == 0
264 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
265 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000266 break;
267 }
268
269 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
270 SourceLocation SpellingLoc
271 = SourceLocation::getFromRawEncoding(Record[1]);
272 SourceMgr.createInstantiationLoc(
273 SpellingLoc,
274 SourceLocation::getFromRawEncoding(Record[2]),
275 SourceLocation::getFromRawEncoding(Record[3]),
276 Lexer::MeasureTokenLength(SpellingLoc,
277 SourceMgr));
278 break;
279 }
280
281 }
282 }
283}
284
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000285bool PCHReader::ReadPreprocessorBlock() {
286 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
287 return Error("Malformed preprocessor block record");
288
289 std::string CurName; // FIXME: HACK.
290 RecordData Record;
291 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
292 MacroInfo *LastMacro = 0;
293
294 while (true) {
295 unsigned Code = Stream.ReadCode();
296 switch (Code) {
297 case llvm::bitc::END_BLOCK:
298 if (Stream.ReadBlockEnd())
299 return Error("Error at end of preprocessor block");
300 return false;
301
302 case llvm::bitc::ENTER_SUBBLOCK:
303 // No known subblocks, always skip them.
304 Stream.ReadSubBlockID();
305 if (Stream.SkipBlock())
306 return Error("Malformed block record");
307 continue;
308
309 case llvm::bitc::DEFINE_ABBREV:
310 Stream.ReadAbbrevRecord();
311 continue;
312 default: break;
313 }
314
315 // Read a record.
316 Record.clear();
317 pch::PreprocessorRecordTypes RecType =
318 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
319 switch (RecType) {
320 default: // Default behavior: ignore unknown records.
321 break;
322
323 case pch::PP_MACRO_NAME:
324 // Set CurName. FIXME: This is a hack and should be removed when we have
325 // identifier id's.
326 CurName.clear();
327 for (unsigned i = 0, e = Record.size(); i != e; ++i)
328 CurName += (char)Record[i];
329 break;
330
331 case pch::PP_MACRO_OBJECT_LIKE:
332 case pch::PP_MACRO_FUNCTION_LIKE: {
333 unsigned IdentInfo = Record[0];
334 IdentInfo = IdentInfo; // FIXME: Decode into identifier info*.
335 assert(!CurName.empty());
336 IdentifierInfo *II = PP.getIdentifierInfo(CurName.c_str());
337
338 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
339 bool isUsed = Record[2];
340
341 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
342 MI->setIsUsed(isUsed);
343
344 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
345 // Decode function-like macro info.
346 bool isC99VarArgs = Record[3];
347 bool isGNUVarArgs = Record[4];
348 MacroArgs.clear();
349 unsigned NumArgs = Record[5];
350 for (unsigned i = 0; i != NumArgs; ++i)
351 ; // FIXME: Decode macro arg names: MacroArgs.push_back(Record[6+i]);
352
353 // Install function-like macro info.
354 MI->setIsFunctionLike();
355 if (isC99VarArgs) MI->setIsC99Varargs();
356 if (isGNUVarArgs) MI->setIsGNUVarargs();
357 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
358 PP.getPreprocessorAllocator());
359 }
360
361 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000362 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000363
364 // Remember that we saw this macro last so that we add the tokens that
365 // form its body to it.
366 LastMacro = MI;
367 break;
368 }
369
370 case pch::PP_TOKEN: {
371 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
372 // pretend we didn't see this.
373 if (LastMacro == 0) break;
374
375 Token Tok;
376 Tok.startToken();
377 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
378 Tok.setLength(Record[1]);
379 unsigned IdentInfo = Record[2];
380 IdentInfo = IdentInfo; // FIXME: Handle this right.
381 Tok.setKind((tok::TokenKind)Record[3]);
382 Tok.setFlag((Token::TokenFlags)Record[4]);
383 LastMacro->AddTokenToBody(Tok);
384 break;
385 }
386 }
387 }
388}
389
Douglas Gregor179cfb12009-04-10 20:39:37 +0000390PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
391 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
392 Error("Malformed block record");
393 return Failure;
394 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000395
396 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000397 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000398 while (!Stream.AtEndOfStream()) {
399 unsigned Code = Stream.ReadCode();
400 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000401 if (Stream.ReadBlockEnd()) {
402 Error("Error at end of module block");
403 return Failure;
404 }
405 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000406 }
407
408 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
409 switch (Stream.ReadSubBlockID()) {
410 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
411 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
412 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000413 if (Stream.SkipBlock()) {
414 Error("Malformed block record");
415 return Failure;
416 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000417 break;
418
Douglas Gregorab1cef72009-04-10 03:52:48 +0000419 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000420 switch (ReadSourceManagerBlock()) {
421 case Success:
422 break;
423
424 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000425 Error("Malformed source manager block");
426 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000427
428 case IgnorePCH:
429 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000430 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000431 break;
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000432
433 case pch::PREPROCESSOR_BLOCK_ID:
434 if (ReadPreprocessorBlock()) {
435 Error("Malformed preprocessor block");
436 return Failure;
437 }
438 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000439 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000440 continue;
441 }
442
443 if (Code == llvm::bitc::DEFINE_ABBREV) {
444 Stream.ReadAbbrevRecord();
445 continue;
446 }
447
448 // Read and process a record.
449 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000450 const char *BlobStart = 0;
451 unsigned BlobLen = 0;
452 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
453 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000454 default: // Default behavior: ignore.
455 break;
456
457 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000458 if (!TypeOffsets.empty()) {
459 Error("Duplicate TYPE_OFFSET record in PCH file");
460 return Failure;
461 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000462 TypeOffsets.swap(Record);
463 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
464 break;
465
466 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000467 if (!DeclOffsets.empty()) {
468 Error("Duplicate DECL_OFFSET record in PCH file");
469 return Failure;
470 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000471 DeclOffsets.swap(Record);
472 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
473 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000474
475 case pch::LANGUAGE_OPTIONS:
476 if (ParseLanguageOptions(Record))
477 return IgnorePCH;
478 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000479
480 case pch::TARGET_TRIPLE:
481 std::string TargetTriple(BlobStart, BlobLen);
482 if (TargetTriple != Context.Target.getTargetTriple()) {
483 Diag(diag::warn_pch_target_triple)
484 << TargetTriple << Context.Target.getTargetTriple();
485 Diag(diag::note_ignoring_pch) << FileName;
486 return IgnorePCH;
487 }
488 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000489 }
490 }
491
Douglas Gregor179cfb12009-04-10 20:39:37 +0000492 Error("Premature end of bitstream");
493 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000494}
495
496PCHReader::~PCHReader() { }
497
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000498PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000499 // Set the PCH file name.
500 this->FileName = FileName;
501
Douglas Gregorc34897d2009-04-09 22:27:44 +0000502 // Open the PCH file.
503 std::string ErrStr;
504 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000505 if (!Buffer) {
506 Error(ErrStr.c_str());
507 return IgnorePCH;
508 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000509
510 // Initialize the stream
511 Stream.init((const unsigned char *)Buffer->getBufferStart(),
512 (const unsigned char *)Buffer->getBufferEnd());
513
514 // Sniff for the signature.
515 if (Stream.Read(8) != 'C' ||
516 Stream.Read(8) != 'P' ||
517 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000518 Stream.Read(8) != 'H') {
519 Error("Not a PCH file");
520 return IgnorePCH;
521 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000522
523 // We expect a number of well-defined blocks, though we don't necessarily
524 // need to understand them all.
525 while (!Stream.AtEndOfStream()) {
526 unsigned Code = Stream.ReadCode();
527
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000528 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
529 Error("Invalid record at top-level");
530 return Failure;
531 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000532
533 unsigned BlockID = Stream.ReadSubBlockID();
534
535 // We only know the PCH subblock ID.
536 switch (BlockID) {
537 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000538 if (Stream.ReadBlockInfoBlock()) {
539 Error("Malformed BlockInfoBlock");
540 return Failure;
541 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000542 break;
543 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000544 switch (ReadPCHBlock()) {
545 case Success:
546 break;
547
548 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000549 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000550
551 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000552 // FIXME: We could consider reading through to the end of this
553 // PCH block, skipping subblocks, to see if there are other
554 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000555 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000556 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000557 break;
558 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000559 if (Stream.SkipBlock()) {
560 Error("Malformed block record");
561 return Failure;
562 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000563 break;
564 }
565 }
566
567 // Load the translation unit declaration
568 ReadDeclRecord(DeclOffsets[0], 0);
569
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000570 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000571}
572
Douglas Gregor179cfb12009-04-10 20:39:37 +0000573/// \brief Parse the record that corresponds to a LangOptions data
574/// structure.
575///
576/// This routine compares the language options used to generate the
577/// PCH file against the language options set for the current
578/// compilation. For each option, we classify differences between the
579/// two compiler states as either "benign" or "important". Benign
580/// differences don't matter, and we accept them without complaint
581/// (and without modifying the language options). Differences between
582/// the states for important options cause the PCH file to be
583/// unusable, so we emit a warning and return true to indicate that
584/// there was an error.
585///
586/// \returns true if the PCH file is unacceptable, false otherwise.
587bool PCHReader::ParseLanguageOptions(
588 const llvm::SmallVectorImpl<uint64_t> &Record) {
589 const LangOptions &LangOpts = Context.getLangOptions();
590#define PARSE_LANGOPT_BENIGN(Option) ++Idx
591#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
592 if (Record[Idx] != LangOpts.Option) { \
593 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
594 Diag(diag::note_ignoring_pch) << FileName; \
595 return true; \
596 } \
597 ++Idx
598
599 unsigned Idx = 0;
600 PARSE_LANGOPT_BENIGN(Trigraphs);
601 PARSE_LANGOPT_BENIGN(BCPLComment);
602 PARSE_LANGOPT_BENIGN(DollarIdents);
603 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
604 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
605 PARSE_LANGOPT_BENIGN(ImplicitInt);
606 PARSE_LANGOPT_BENIGN(Digraphs);
607 PARSE_LANGOPT_BENIGN(HexFloats);
608 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
609 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
610 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
611 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
612 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
613 PARSE_LANGOPT_BENIGN(CXXOperatorName);
614 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
615 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
616 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
617 PARSE_LANGOPT_BENIGN(PascalStrings);
618 PARSE_LANGOPT_BENIGN(Boolean);
619 PARSE_LANGOPT_BENIGN(WritableStrings);
620 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
621 diag::warn_pch_lax_vector_conversions);
622 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
623 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
624 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
625 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
626 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
627 diag::warn_pch_thread_safe_statics);
628 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
629 PARSE_LANGOPT_BENIGN(EmitAllDecls);
630 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
631 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
632 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
633 diag::warn_pch_heinous_extensions);
634 // FIXME: Most of the options below are benign if the macro wasn't
635 // used. Unfortunately, this means that a PCH compiled without
636 // optimization can't be used with optimization turned on, even
637 // though the only thing that changes is whether __OPTIMIZE__ was
638 // defined... but if __OPTIMIZE__ never showed up in the header, it
639 // doesn't matter. We could consider making this some special kind
640 // of check.
641 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
642 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
643 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
644 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
645 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
646 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
647 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
648 Diag(diag::warn_pch_gc_mode)
649 << (unsigned)Record[Idx] << LangOpts.getGCMode();
650 Diag(diag::note_ignoring_pch) << FileName;
651 return true;
652 }
653 ++Idx;
654 PARSE_LANGOPT_BENIGN(getVisibilityMode());
655 PARSE_LANGOPT_BENIGN(InstantiationDepth);
656#undef PARSE_LANGOPT_IRRELEVANT
657#undef PARSE_LANGOPT_BENIGN
658
659 return false;
660}
661
Douglas Gregorc34897d2009-04-09 22:27:44 +0000662/// \brief Read and return the type at the given offset.
663///
664/// This routine actually reads the record corresponding to the type
665/// at the given offset in the bitstream. It is a helper routine for
666/// GetType, which deals with reading type IDs.
667QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
668 Stream.JumpToBit(Offset);
669 RecordData Record;
670 unsigned Code = Stream.ReadCode();
671 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
672 case pch::TYPE_FIXED_WIDTH_INT: {
673 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
674 return Context.getFixedWidthIntType(Record[0], Record[1]);
675 }
676
677 case pch::TYPE_COMPLEX: {
678 assert(Record.size() == 1 && "Incorrect encoding of complex type");
679 QualType ElemType = GetType(Record[0]);
680 return Context.getComplexType(ElemType);
681 }
682
683 case pch::TYPE_POINTER: {
684 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
685 QualType PointeeType = GetType(Record[0]);
686 return Context.getPointerType(PointeeType);
687 }
688
689 case pch::TYPE_BLOCK_POINTER: {
690 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
691 QualType PointeeType = GetType(Record[0]);
692 return Context.getBlockPointerType(PointeeType);
693 }
694
695 case pch::TYPE_LVALUE_REFERENCE: {
696 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
697 QualType PointeeType = GetType(Record[0]);
698 return Context.getLValueReferenceType(PointeeType);
699 }
700
701 case pch::TYPE_RVALUE_REFERENCE: {
702 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
703 QualType PointeeType = GetType(Record[0]);
704 return Context.getRValueReferenceType(PointeeType);
705 }
706
707 case pch::TYPE_MEMBER_POINTER: {
708 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
709 QualType PointeeType = GetType(Record[0]);
710 QualType ClassType = GetType(Record[1]);
711 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
712 }
713
714 // FIXME: Several other kinds of types to deserialize here!
715 default:
Douglas Gregorac8f2802009-04-10 17:25:41 +0000716 assert(false && "Unable to deserialize this type");
Douglas Gregorc34897d2009-04-09 22:27:44 +0000717 break;
718 }
719
720 // Suppress a GCC warning
721 return QualType();
722}
723
724/// \brief Note that we have loaded the declaration with the given
725/// Index.
726///
727/// This routine notes that this declaration has already been loaded,
728/// so that future GetDecl calls will return this declaration rather
729/// than trying to load a new declaration.
730inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
731 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
732 DeclAlreadyLoaded[Index] = true;
733 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
734}
735
736/// \brief Read the declaration at the given offset from the PCH file.
737Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
738 Decl *D = 0;
739 Stream.JumpToBit(Offset);
740 RecordData Record;
741 unsigned Code = Stream.ReadCode();
742 unsigned Idx = 0;
743 PCHDeclReader Reader(*this, Record, Idx);
744 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
745 case pch::DECL_TRANSLATION_UNIT:
746 assert(Index == 0 && "Translation unit must be at index 0");
747 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
748 D = Context.getTranslationUnitDecl();
749 LoadedDecl(Index, D);
750 break;
751
752 case pch::DECL_TYPEDEF: {
753 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
754 0, QualType());
755 LoadedDecl(Index, Typedef);
756 Reader.VisitTypedefDecl(Typedef);
757 D = Typedef;
758 break;
759 }
760
761 case pch::DECL_VAR: {
762 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
763 VarDecl::None, SourceLocation());
764 LoadedDecl(Index, Var);
765 Reader.VisitVarDecl(Var);
766 D = Var;
767 break;
768 }
769
770 default:
771 assert(false && "Cannot de-serialize this kind of declaration");
772 break;
773 }
774
775 // If this declaration is also a declaration context, get the
776 // offsets for its tables of lexical and visible declarations.
777 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
778 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
779 if (Offsets.first || Offsets.second) {
780 DC->setHasExternalLexicalStorage(Offsets.first != 0);
781 DC->setHasExternalVisibleStorage(Offsets.second != 0);
782 DeclContextOffsets[DC] = Offsets;
783 }
784 }
785 assert(Idx == Record.size());
786
787 return D;
788}
789
Douglas Gregorac8f2802009-04-10 17:25:41 +0000790QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000791 unsigned Quals = ID & 0x07;
792 unsigned Index = ID >> 3;
793
794 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
795 QualType T;
796 switch ((pch::PredefinedTypeIDs)Index) {
797 case pch::PREDEF_TYPE_NULL_ID: return QualType();
798 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
799 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
800
801 case pch::PREDEF_TYPE_CHAR_U_ID:
802 case pch::PREDEF_TYPE_CHAR_S_ID:
803 // FIXME: Check that the signedness of CharTy is correct!
804 T = Context.CharTy;
805 break;
806
807 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
808 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
809 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
810 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
811 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
812 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
813 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
814 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
815 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
816 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
817 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
818 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
819 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
820 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
821 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
822 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
823 }
824
825 assert(!T.isNull() && "Unknown predefined type");
826 return T.getQualifiedType(Quals);
827 }
828
829 Index -= pch::NUM_PREDEF_TYPE_IDS;
830 if (!TypeAlreadyLoaded[Index]) {
831 // Load the type from the PCH file.
832 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
833 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
834 TypeAlreadyLoaded[Index] = true;
835 }
836
837 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
838}
839
Douglas Gregorac8f2802009-04-10 17:25:41 +0000840Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000841 if (ID == 0)
842 return 0;
843
844 unsigned Index = ID - 1;
845 if (DeclAlreadyLoaded[Index])
846 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
847
848 // Load the declaration from the PCH file.
849 return ReadDeclRecord(DeclOffsets[Index], Index);
850}
851
852bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +0000853 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000854 assert(DC->hasExternalLexicalStorage() &&
855 "DeclContext has no lexical decls in storage");
856 uint64_t Offset = DeclContextOffsets[DC].first;
857 assert(Offset && "DeclContext has no lexical decls in storage");
858
859 // Load the record containing all of the declarations lexically in
860 // this context.
861 Stream.JumpToBit(Offset);
862 RecordData Record;
863 unsigned Code = Stream.ReadCode();
864 unsigned RecCode = Stream.ReadRecord(Code, Record);
865 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
866
867 // Load all of the declaration IDs
868 Decls.clear();
869 Decls.insert(Decls.end(), Record.begin(), Record.end());
870 return false;
871}
872
873bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
874 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
875 assert(DC->hasExternalVisibleStorage() &&
876 "DeclContext has no visible decls in storage");
877 uint64_t Offset = DeclContextOffsets[DC].second;
878 assert(Offset && "DeclContext has no visible decls in storage");
879
880 // Load the record containing all of the declarations visible in
881 // this context.
882 Stream.JumpToBit(Offset);
883 RecordData Record;
884 unsigned Code = Stream.ReadCode();
885 unsigned RecCode = Stream.ReadRecord(Code, Record);
886 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
887 if (Record.size() == 0)
888 return false;
889
890 Decls.clear();
891
892 unsigned Idx = 0;
893 // llvm::SmallVector<uintptr_t, 16> DeclIDs;
894 while (Idx < Record.size()) {
895 Decls.push_back(VisibleDeclaration());
896 Decls.back().Name = ReadDeclarationName(Record, Idx);
897
898 // FIXME: Don't actually read anything here!
899 unsigned Size = Record[Idx++];
900 llvm::SmallVector<unsigned, 4> & LoadedDecls
901 = Decls.back().Declarations;
902 LoadedDecls.reserve(Size);
903 for (unsigned I = 0; I < Size; ++I)
904 LoadedDecls.push_back(Record[Idx++]);
905 }
906
907 return false;
908}
909
910void PCHReader::PrintStats() {
911 std::fprintf(stderr, "*** PCH Statistics:\n");
912
913 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
914 TypeAlreadyLoaded.end(),
915 true);
916 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
917 DeclAlreadyLoaded.end(),
918 true);
919 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
920 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
921 ((float)NumTypesLoaded/(float)TypeAlreadyLoaded.size() * 100));
922 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
923 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
924 ((float)NumDeclsLoaded/(float)DeclAlreadyLoaded.size() * 100));
925 std::fprintf(stderr, "\n");
926}
927
928const IdentifierInfo *PCHReader::GetIdentifierInfo(const RecordData &Record,
929 unsigned &Idx) {
930 // FIXME: we need unique IDs for identifiers.
931 std::string Str;
932 unsigned Length = Record[Idx++];
933 Str.resize(Length);
934 for (unsigned I = 0; I != Length; ++I)
935 Str[I] = Record[Idx++];
936 return &Context.Idents.get(Str);
937}
938
939DeclarationName
940PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
941 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
942 switch (Kind) {
943 case DeclarationName::Identifier:
944 return DeclarationName(GetIdentifierInfo(Record, Idx));
945
946 case DeclarationName::ObjCZeroArgSelector:
947 case DeclarationName::ObjCOneArgSelector:
948 case DeclarationName::ObjCMultiArgSelector:
949 assert(false && "Unable to de-serialize Objective-C selectors");
950 break;
951
952 case DeclarationName::CXXConstructorName:
953 return Context.DeclarationNames.getCXXConstructorName(
954 GetType(Record[Idx++]));
955
956 case DeclarationName::CXXDestructorName:
957 return Context.DeclarationNames.getCXXDestructorName(
958 GetType(Record[Idx++]));
959
960 case DeclarationName::CXXConversionFunctionName:
961 return Context.DeclarationNames.getCXXConversionFunctionName(
962 GetType(Record[Idx++]));
963
964 case DeclarationName::CXXOperatorName:
965 return Context.DeclarationNames.getCXXOperatorName(
966 (OverloadedOperatorKind)Record[Idx++]);
967
968 case DeclarationName::CXXUsingDirective:
969 return DeclarationName::getUsingDirectiveName();
970 }
971
972 // Required to silence GCC warning
973 return DeclarationName();
974}
Douglas Gregor179cfb12009-04-10 20:39:37 +0000975
976DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000977 return Diag(SourceLocation(), DiagID);
978}
979
980DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
981 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +0000982 Context.getSourceManager()),
983 DiagID);
984}