blob: adb4e5f6d7731f451cb209d1fabac56502251dcc [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"
Douglas Gregor635f97f2009-04-13 16:31:14 +000021#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000022#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000023#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000024#include "llvm/Bitcode/BitstreamReader.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include <algorithm>
28#include <cstdio>
29
30using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Declaration deserialization
34//===----------------------------------------------------------------------===//
35namespace {
36 class VISIBILITY_HIDDEN PCHDeclReader {
37 PCHReader &Reader;
38 const PCHReader::RecordData &Record;
39 unsigned &Idx;
40
41 public:
42 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
43 unsigned &Idx)
44 : Reader(Reader), Record(Record), Idx(Idx) { }
45
46 void VisitDecl(Decl *D);
47 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
48 void VisitNamedDecl(NamedDecl *ND);
49 void VisitTypeDecl(TypeDecl *TD);
50 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000051 void VisitTagDecl(TagDecl *TD);
52 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000053 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000054 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000055 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor982365e2009-04-13 21:20:57 +000056 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000057 void VisitVarDecl(VarDecl *VD);
58
59 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
60 };
61}
62
63void PCHDeclReader::VisitDecl(Decl *D) {
64 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
65 D->setLexicalDeclContext(
66 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
67 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
68 D->setInvalidDecl(Record[Idx++]);
69 // FIXME: hasAttrs
70 D->setImplicit(Record[Idx++]);
71 D->setAccess((AccessSpecifier)Record[Idx++]);
72}
73
74void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
75 VisitDecl(TU);
76}
77
78void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
79 VisitDecl(ND);
80 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
81}
82
83void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
84 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000085 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
86}
87
88void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000089 // Note that we cannot use VisitTypeDecl here, because we need to
90 // set the underlying type of the typedef *before* we try to read
91 // the type associated with the TypedefDecl.
92 VisitNamedDecl(TD);
93 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
94 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
95 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +000096}
97
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000098void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
99 VisitTypeDecl(TD);
100 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
101 TD->setDefinition(Record[Idx++]);
102 TD->setTypedefForAnonDecl(
103 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
104}
105
106void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
107 VisitTagDecl(ED);
108 ED->setIntegerType(Reader.GetType(Record[Idx++]));
109}
110
Douglas Gregor982365e2009-04-13 21:20:57 +0000111void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
112 VisitTagDecl(RD);
113 RD->setHasFlexibleArrayMember(Record[Idx++]);
114 RD->setAnonymousStructOrUnion(Record[Idx++]);
115}
116
Douglas Gregorc34897d2009-04-09 22:27:44 +0000117void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
118 VisitNamedDecl(VD);
119 VD->setType(Reader.GetType(Record[Idx++]));
120}
121
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000122void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
123 VisitValueDecl(ECD);
Douglas Gregor982365e2009-04-13 21:20:57 +0000124 // FIXME: read the initialization expression
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000125 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
126}
127
Douglas Gregor982365e2009-04-13 21:20:57 +0000128void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
129 VisitValueDecl(FD);
130 FD->setMutable(Record[Idx++]);
131 // FIXME: Read the bit width.
132}
133
Douglas Gregorc34897d2009-04-09 22:27:44 +0000134void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
135 VisitValueDecl(VD);
136 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
137 VD->setThreadSpecified(Record[Idx++]);
138 VD->setCXXDirectInitializer(Record[Idx++]);
139 VD->setDeclaredInCondition(Record[Idx++]);
140 VD->setPreviousDeclaration(
141 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
142 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
143}
144
145std::pair<uint64_t, uint64_t>
146PCHDeclReader::VisitDeclContext(DeclContext *DC) {
147 uint64_t LexicalOffset = Record[Idx++];
148 uint64_t VisibleOffset = 0;
149 if (DC->getPrimaryContext() == DC)
150 VisibleOffset = Record[Idx++];
151 return std::make_pair(LexicalOffset, VisibleOffset);
152}
153
154// FIXME: use the diagnostics machinery
155static bool Error(const char *Str) {
156 std::fprintf(stderr, "%s\n", Str);
157 return true;
158}
159
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000160/// \brief Check the contents of the predefines buffer against the
161/// contents of the predefines buffer used to build the PCH file.
162///
163/// The contents of the two predefines buffers should be the same. If
164/// not, then some command-line option changed the preprocessor state
165/// and we must reject the PCH file.
166///
167/// \param PCHPredef The start of the predefines buffer in the PCH
168/// file.
169///
170/// \param PCHPredefLen The length of the predefines buffer in the PCH
171/// file.
172///
173/// \param PCHBufferID The FileID for the PCH predefines buffer.
174///
175/// \returns true if there was a mismatch (in which case the PCH file
176/// should be ignored), or false otherwise.
177bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
178 unsigned PCHPredefLen,
179 FileID PCHBufferID) {
180 const char *Predef = PP.getPredefines().c_str();
181 unsigned PredefLen = PP.getPredefines().size();
182
183 // If the two predefines buffers compare equal, we're done!.
184 if (PredefLen == PCHPredefLen &&
185 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
186 return false;
187
188 // The predefines buffers are different. Produce a reasonable
189 // diagnostic showing where they are different.
190
191 // The source locations (potentially in the two different predefines
192 // buffers)
193 SourceLocation Loc1, Loc2;
194 SourceManager &SourceMgr = PP.getSourceManager();
195
196 // Create a source buffer for our predefines string, so
197 // that we can build a diagnostic that points into that
198 // source buffer.
199 FileID BufferID;
200 if (Predef && Predef[0]) {
201 llvm::MemoryBuffer *Buffer
202 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
203 "<built-in>");
204 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
205 }
206
207 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
208 std::pair<const char *, const char *> Locations
209 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
210
211 if (Locations.first != Predef + MinLen) {
212 // We found the location in the two buffers where there is a
213 // difference. Form source locations to point there (in both
214 // buffers).
215 unsigned Offset = Locations.first - Predef;
216 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
217 .getFileLocWithOffset(Offset);
218 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
219 .getFileLocWithOffset(Offset);
220 } else if (PredefLen > PCHPredefLen) {
221 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
222 .getFileLocWithOffset(MinLen);
223 } else {
224 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
225 .getFileLocWithOffset(MinLen);
226 }
227
228 Diag(Loc1, diag::warn_pch_preprocessor);
229 if (Loc2.isValid())
230 Diag(Loc2, diag::note_predef_in_pch);
231 Diag(diag::note_ignoring_pch) << FileName;
232 return true;
233}
234
Douglas Gregor635f97f2009-04-13 16:31:14 +0000235/// \brief Read the line table in the source manager block.
236/// \returns true if ther was an error.
237static bool ParseLineTable(SourceManager &SourceMgr,
238 llvm::SmallVectorImpl<uint64_t> &Record) {
239 unsigned Idx = 0;
240 LineTableInfo &LineTable = SourceMgr.getLineTable();
241
242 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000243 std::map<int, int> FileIDs;
244 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000245 // Extract the file name
246 unsigned FilenameLen = Record[Idx++];
247 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
248 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000249 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
250 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000251 }
252
253 // Parse the line entries
254 std::vector<LineEntry> Entries;
255 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000256 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000257
258 // Extract the line entries
259 unsigned NumEntries = Record[Idx++];
260 Entries.clear();
261 Entries.reserve(NumEntries);
262 for (unsigned I = 0; I != NumEntries; ++I) {
263 unsigned FileOffset = Record[Idx++];
264 unsigned LineNo = Record[Idx++];
265 int FilenameID = Record[Idx++];
266 SrcMgr::CharacteristicKind FileKind
267 = (SrcMgr::CharacteristicKind)Record[Idx++];
268 unsigned IncludeOffset = Record[Idx++];
269 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
270 FileKind, IncludeOffset));
271 }
272 LineTable.AddEntry(FID, Entries);
273 }
274
275 return false;
276}
277
Douglas Gregorab1cef72009-04-10 03:52:48 +0000278/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000279PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000280 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000281 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
282 Error("Malformed source manager block record");
283 return Failure;
284 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000285
286 SourceManager &SourceMgr = Context.getSourceManager();
287 RecordData Record;
288 while (true) {
289 unsigned Code = Stream.ReadCode();
290 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000291 if (Stream.ReadBlockEnd()) {
292 Error("Error at end of Source Manager block");
293 return Failure;
294 }
295
296 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000297 }
298
299 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
300 // No known subblocks, always skip them.
301 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000302 if (Stream.SkipBlock()) {
303 Error("Malformed block record");
304 return Failure;
305 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000306 continue;
307 }
308
309 if (Code == llvm::bitc::DEFINE_ABBREV) {
310 Stream.ReadAbbrevRecord();
311 continue;
312 }
313
314 // Read a record.
315 const char *BlobStart;
316 unsigned BlobLen;
317 Record.clear();
318 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
319 default: // Default behavior: ignore.
320 break;
321
322 case pch::SM_SLOC_FILE_ENTRY: {
323 // FIXME: We would really like to delay the creation of this
324 // FileEntry until it is actually required, e.g., when producing
325 // a diagnostic with a source location in this file.
326 const FileEntry *File
327 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
328 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000329 FileID ID = SourceMgr.createFileID(File,
330 SourceLocation::getFromRawEncoding(Record[1]),
331 (CharacteristicKind)Record[2]);
332 if (Record[3])
333 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
334 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000335 break;
336 }
337
338 case pch::SM_SLOC_BUFFER_ENTRY: {
339 const char *Name = BlobStart;
340 unsigned Code = Stream.ReadCode();
341 Record.clear();
342 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
343 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000344 llvm::MemoryBuffer *Buffer
345 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
346 BlobStart + BlobLen - 1,
347 Name);
348 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
349
350 if (strcmp(Name, "<built-in>") == 0
351 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
352 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000353 break;
354 }
355
356 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
357 SourceLocation SpellingLoc
358 = SourceLocation::getFromRawEncoding(Record[1]);
359 SourceMgr.createInstantiationLoc(
360 SpellingLoc,
361 SourceLocation::getFromRawEncoding(Record[2]),
362 SourceLocation::getFromRawEncoding(Record[3]),
363 Lexer::MeasureTokenLength(SpellingLoc,
364 SourceMgr));
365 break;
366 }
367
Douglas Gregor635f97f2009-04-13 16:31:14 +0000368 case pch::SM_LINE_TABLE: {
369 if (ParseLineTable(SourceMgr, Record))
370 return Failure;
371 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000372 }
373 }
374}
375
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000376bool PCHReader::ReadPreprocessorBlock() {
377 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
378 return Error("Malformed preprocessor block record");
379
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000380 RecordData Record;
381 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
382 MacroInfo *LastMacro = 0;
383
384 while (true) {
385 unsigned Code = Stream.ReadCode();
386 switch (Code) {
387 case llvm::bitc::END_BLOCK:
388 if (Stream.ReadBlockEnd())
389 return Error("Error at end of preprocessor block");
390 return false;
391
392 case llvm::bitc::ENTER_SUBBLOCK:
393 // No known subblocks, always skip them.
394 Stream.ReadSubBlockID();
395 if (Stream.SkipBlock())
396 return Error("Malformed block record");
397 continue;
398
399 case llvm::bitc::DEFINE_ABBREV:
400 Stream.ReadAbbrevRecord();
401 continue;
402 default: break;
403 }
404
405 // Read a record.
406 Record.clear();
407 pch::PreprocessorRecordTypes RecType =
408 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
409 switch (RecType) {
410 default: // Default behavior: ignore unknown records.
411 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000412 case pch::PP_COUNTER_VALUE:
413 if (!Record.empty())
414 PP.setCounterValue(Record[0]);
415 break;
416
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000417 case pch::PP_MACRO_OBJECT_LIKE:
418 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000419 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
420 if (II == 0)
421 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000422 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
423 bool isUsed = Record[2];
424
425 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
426 MI->setIsUsed(isUsed);
427
428 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
429 // Decode function-like macro info.
430 bool isC99VarArgs = Record[3];
431 bool isGNUVarArgs = Record[4];
432 MacroArgs.clear();
433 unsigned NumArgs = Record[5];
434 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000435 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000436
437 // Install function-like macro info.
438 MI->setIsFunctionLike();
439 if (isC99VarArgs) MI->setIsC99Varargs();
440 if (isGNUVarArgs) MI->setIsGNUVarargs();
441 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
442 PP.getPreprocessorAllocator());
443 }
444
445 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000446 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000447
448 // Remember that we saw this macro last so that we add the tokens that
449 // form its body to it.
450 LastMacro = MI;
451 break;
452 }
453
454 case pch::PP_TOKEN: {
455 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
456 // pretend we didn't see this.
457 if (LastMacro == 0) break;
458
459 Token Tok;
460 Tok.startToken();
461 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
462 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000463 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
464 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000465 Tok.setKind((tok::TokenKind)Record[3]);
466 Tok.setFlag((Token::TokenFlags)Record[4]);
467 LastMacro->AddTokenToBody(Tok);
468 break;
469 }
470 }
471 }
472}
473
Douglas Gregor179cfb12009-04-10 20:39:37 +0000474PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
475 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
476 Error("Malformed block record");
477 return Failure;
478 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000479
Chris Lattner29241862009-04-11 21:15:38 +0000480 uint64_t PreprocessorBlockBit = 0;
481
Douglas Gregorc34897d2009-04-09 22:27:44 +0000482 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000483 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000484 while (!Stream.AtEndOfStream()) {
485 unsigned Code = Stream.ReadCode();
486 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000487 // If we saw the preprocessor block, read it now.
488 if (PreprocessorBlockBit) {
489 uint64_t SavedPos = Stream.GetCurrentBitNo();
490 Stream.JumpToBit(PreprocessorBlockBit);
491 if (ReadPreprocessorBlock()) {
492 Error("Malformed preprocessor block");
493 return Failure;
494 }
495 Stream.JumpToBit(SavedPos);
496 }
497
Douglas Gregor179cfb12009-04-10 20:39:37 +0000498 if (Stream.ReadBlockEnd()) {
499 Error("Error at end of module block");
500 return Failure;
501 }
Chris Lattner29241862009-04-11 21:15:38 +0000502
Douglas Gregor179cfb12009-04-10 20:39:37 +0000503 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000504 }
505
506 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
507 switch (Stream.ReadSubBlockID()) {
508 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
509 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
510 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000511 if (Stream.SkipBlock()) {
512 Error("Malformed block record");
513 return Failure;
514 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000515 break;
516
Chris Lattner29241862009-04-11 21:15:38 +0000517 case pch::PREPROCESSOR_BLOCK_ID:
518 // Skip the preprocessor block for now, but remember where it is. We
519 // want to read it in after the identifier table.
520 if (PreprocessorBlockBit) {
521 Error("Multiple preprocessor blocks found.");
522 return Failure;
523 }
524 PreprocessorBlockBit = Stream.GetCurrentBitNo();
525 if (Stream.SkipBlock()) {
526 Error("Malformed block record");
527 return Failure;
528 }
529 break;
530
Douglas Gregorab1cef72009-04-10 03:52:48 +0000531 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000532 switch (ReadSourceManagerBlock()) {
533 case Success:
534 break;
535
536 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000537 Error("Malformed source manager block");
538 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000539
540 case IgnorePCH:
541 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000542 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000543 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000544 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000545 continue;
546 }
547
548 if (Code == llvm::bitc::DEFINE_ABBREV) {
549 Stream.ReadAbbrevRecord();
550 continue;
551 }
552
553 // Read and process a record.
554 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000555 const char *BlobStart = 0;
556 unsigned BlobLen = 0;
557 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
558 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000559 default: // Default behavior: ignore.
560 break;
561
562 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000563 if (!TypeOffsets.empty()) {
564 Error("Duplicate TYPE_OFFSET record in PCH file");
565 return Failure;
566 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000567 TypeOffsets.swap(Record);
568 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
569 break;
570
571 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000572 if (!DeclOffsets.empty()) {
573 Error("Duplicate DECL_OFFSET record in PCH file");
574 return Failure;
575 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000576 DeclOffsets.swap(Record);
577 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
578 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000579
580 case pch::LANGUAGE_OPTIONS:
581 if (ParseLanguageOptions(Record))
582 return IgnorePCH;
583 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000584
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000585 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000586 std::string TargetTriple(BlobStart, BlobLen);
587 if (TargetTriple != Context.Target.getTargetTriple()) {
588 Diag(diag::warn_pch_target_triple)
589 << TargetTriple << Context.Target.getTargetTriple();
590 Diag(diag::note_ignoring_pch) << FileName;
591 return IgnorePCH;
592 }
593 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000594 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000595
596 case pch::IDENTIFIER_TABLE:
597 IdentifierTable = BlobStart;
598 break;
599
600 case pch::IDENTIFIER_OFFSET:
601 if (!IdentifierData.empty()) {
602 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
603 return Failure;
604 }
605 IdentifierData.swap(Record);
606#ifndef NDEBUG
607 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
608 if ((IdentifierData[I] & 0x01) == 0) {
609 Error("Malformed identifier table in the precompiled header");
610 return Failure;
611 }
612 }
613#endif
614 break;
615 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000616 }
617
Douglas Gregor179cfb12009-04-10 20:39:37 +0000618 Error("Premature end of bitstream");
619 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000620}
621
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000622PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000623 // Set the PCH file name.
624 this->FileName = FileName;
625
Douglas Gregorc34897d2009-04-09 22:27:44 +0000626 // Open the PCH file.
627 std::string ErrStr;
628 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000629 if (!Buffer) {
630 Error(ErrStr.c_str());
631 return IgnorePCH;
632 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000633
634 // Initialize the stream
635 Stream.init((const unsigned char *)Buffer->getBufferStart(),
636 (const unsigned char *)Buffer->getBufferEnd());
637
638 // Sniff for the signature.
639 if (Stream.Read(8) != 'C' ||
640 Stream.Read(8) != 'P' ||
641 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000642 Stream.Read(8) != 'H') {
643 Error("Not a PCH file");
644 return IgnorePCH;
645 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000646
647 // We expect a number of well-defined blocks, though we don't necessarily
648 // need to understand them all.
649 while (!Stream.AtEndOfStream()) {
650 unsigned Code = Stream.ReadCode();
651
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000652 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
653 Error("Invalid record at top-level");
654 return Failure;
655 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000656
657 unsigned BlockID = Stream.ReadSubBlockID();
658
659 // We only know the PCH subblock ID.
660 switch (BlockID) {
661 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000662 if (Stream.ReadBlockInfoBlock()) {
663 Error("Malformed BlockInfoBlock");
664 return Failure;
665 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000666 break;
667 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000668 switch (ReadPCHBlock()) {
669 case Success:
670 break;
671
672 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000673 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000674
675 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000676 // FIXME: We could consider reading through to the end of this
677 // PCH block, skipping subblocks, to see if there are other
678 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000679 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000680 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000681 break;
682 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000683 if (Stream.SkipBlock()) {
684 Error("Malformed block record");
685 return Failure;
686 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000687 break;
688 }
689 }
690
691 // Load the translation unit declaration
692 ReadDeclRecord(DeclOffsets[0], 0);
693
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000694 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000695}
696
Douglas Gregor179cfb12009-04-10 20:39:37 +0000697/// \brief Parse the record that corresponds to a LangOptions data
698/// structure.
699///
700/// This routine compares the language options used to generate the
701/// PCH file against the language options set for the current
702/// compilation. For each option, we classify differences between the
703/// two compiler states as either "benign" or "important". Benign
704/// differences don't matter, and we accept them without complaint
705/// (and without modifying the language options). Differences between
706/// the states for important options cause the PCH file to be
707/// unusable, so we emit a warning and return true to indicate that
708/// there was an error.
709///
710/// \returns true if the PCH file is unacceptable, false otherwise.
711bool PCHReader::ParseLanguageOptions(
712 const llvm::SmallVectorImpl<uint64_t> &Record) {
713 const LangOptions &LangOpts = Context.getLangOptions();
714#define PARSE_LANGOPT_BENIGN(Option) ++Idx
715#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
716 if (Record[Idx] != LangOpts.Option) { \
717 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
718 Diag(diag::note_ignoring_pch) << FileName; \
719 return true; \
720 } \
721 ++Idx
722
723 unsigned Idx = 0;
724 PARSE_LANGOPT_BENIGN(Trigraphs);
725 PARSE_LANGOPT_BENIGN(BCPLComment);
726 PARSE_LANGOPT_BENIGN(DollarIdents);
727 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
728 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
729 PARSE_LANGOPT_BENIGN(ImplicitInt);
730 PARSE_LANGOPT_BENIGN(Digraphs);
731 PARSE_LANGOPT_BENIGN(HexFloats);
732 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
733 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
734 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
735 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
736 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
737 PARSE_LANGOPT_BENIGN(CXXOperatorName);
738 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
739 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
740 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
741 PARSE_LANGOPT_BENIGN(PascalStrings);
742 PARSE_LANGOPT_BENIGN(Boolean);
743 PARSE_LANGOPT_BENIGN(WritableStrings);
744 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
745 diag::warn_pch_lax_vector_conversions);
746 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
747 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
748 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
749 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
750 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
751 diag::warn_pch_thread_safe_statics);
752 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
753 PARSE_LANGOPT_BENIGN(EmitAllDecls);
754 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
755 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
756 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
757 diag::warn_pch_heinous_extensions);
758 // FIXME: Most of the options below are benign if the macro wasn't
759 // used. Unfortunately, this means that a PCH compiled without
760 // optimization can't be used with optimization turned on, even
761 // though the only thing that changes is whether __OPTIMIZE__ was
762 // defined... but if __OPTIMIZE__ never showed up in the header, it
763 // doesn't matter. We could consider making this some special kind
764 // of check.
765 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
766 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
767 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
768 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
769 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
770 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
771 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
772 Diag(diag::warn_pch_gc_mode)
773 << (unsigned)Record[Idx] << LangOpts.getGCMode();
774 Diag(diag::note_ignoring_pch) << FileName;
775 return true;
776 }
777 ++Idx;
778 PARSE_LANGOPT_BENIGN(getVisibilityMode());
779 PARSE_LANGOPT_BENIGN(InstantiationDepth);
780#undef PARSE_LANGOPT_IRRELEVANT
781#undef PARSE_LANGOPT_BENIGN
782
783 return false;
784}
785
Douglas Gregorc34897d2009-04-09 22:27:44 +0000786/// \brief Read and return the type at the given offset.
787///
788/// This routine actually reads the record corresponding to the type
789/// at the given offset in the bitstream. It is a helper routine for
790/// GetType, which deals with reading type IDs.
791QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
792 Stream.JumpToBit(Offset);
793 RecordData Record;
794 unsigned Code = Stream.ReadCode();
795 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000796 case pch::TYPE_EXT_QUAL:
797 // FIXME: Deserialize ExtQualType
798 assert(false && "Cannot deserialize qualified types yet");
799 return QualType();
800
Douglas Gregorc34897d2009-04-09 22:27:44 +0000801 case pch::TYPE_FIXED_WIDTH_INT: {
802 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
803 return Context.getFixedWidthIntType(Record[0], Record[1]);
804 }
805
806 case pch::TYPE_COMPLEX: {
807 assert(Record.size() == 1 && "Incorrect encoding of complex type");
808 QualType ElemType = GetType(Record[0]);
809 return Context.getComplexType(ElemType);
810 }
811
812 case pch::TYPE_POINTER: {
813 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
814 QualType PointeeType = GetType(Record[0]);
815 return Context.getPointerType(PointeeType);
816 }
817
818 case pch::TYPE_BLOCK_POINTER: {
819 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
820 QualType PointeeType = GetType(Record[0]);
821 return Context.getBlockPointerType(PointeeType);
822 }
823
824 case pch::TYPE_LVALUE_REFERENCE: {
825 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
826 QualType PointeeType = GetType(Record[0]);
827 return Context.getLValueReferenceType(PointeeType);
828 }
829
830 case pch::TYPE_RVALUE_REFERENCE: {
831 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
832 QualType PointeeType = GetType(Record[0]);
833 return Context.getRValueReferenceType(PointeeType);
834 }
835
836 case pch::TYPE_MEMBER_POINTER: {
837 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
838 QualType PointeeType = GetType(Record[0]);
839 QualType ClassType = GetType(Record[1]);
840 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
841 }
842
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000843 case pch::TYPE_CONSTANT_ARRAY: {
844 QualType ElementType = GetType(Record[0]);
845 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
846 unsigned IndexTypeQuals = Record[2];
847 unsigned Idx = 3;
848 llvm::APInt Size = ReadAPInt(Record, Idx);
849 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
850 }
851
852 case pch::TYPE_INCOMPLETE_ARRAY: {
853 QualType ElementType = GetType(Record[0]);
854 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
855 unsigned IndexTypeQuals = Record[2];
856 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
857 }
858
859 case pch::TYPE_VARIABLE_ARRAY: {
860 // FIXME: implement this
861 assert(false && "Unable to de-serialize variable-length array type");
862 return QualType();
863 }
864
865 case pch::TYPE_VECTOR: {
866 if (Record.size() != 2) {
867 Error("Incorrect encoding of vector type in PCH file");
868 return QualType();
869 }
870
871 QualType ElementType = GetType(Record[0]);
872 unsigned NumElements = Record[1];
873 return Context.getVectorType(ElementType, NumElements);
874 }
875
876 case pch::TYPE_EXT_VECTOR: {
877 if (Record.size() != 2) {
878 Error("Incorrect encoding of extended vector type in PCH file");
879 return QualType();
880 }
881
882 QualType ElementType = GetType(Record[0]);
883 unsigned NumElements = Record[1];
884 return Context.getExtVectorType(ElementType, NumElements);
885 }
886
887 case pch::TYPE_FUNCTION_NO_PROTO: {
888 if (Record.size() != 1) {
889 Error("Incorrect encoding of no-proto function type");
890 return QualType();
891 }
892 QualType ResultType = GetType(Record[0]);
893 return Context.getFunctionNoProtoType(ResultType);
894 }
895
896 case pch::TYPE_FUNCTION_PROTO: {
897 QualType ResultType = GetType(Record[0]);
898 unsigned Idx = 1;
899 unsigned NumParams = Record[Idx++];
900 llvm::SmallVector<QualType, 16> ParamTypes;
901 for (unsigned I = 0; I != NumParams; ++I)
902 ParamTypes.push_back(GetType(Record[Idx++]));
903 bool isVariadic = Record[Idx++];
904 unsigned Quals = Record[Idx++];
905 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
906 isVariadic, Quals);
907 }
908
909 case pch::TYPE_TYPEDEF:
910 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
911 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
912
913 case pch::TYPE_TYPEOF_EXPR:
914 // FIXME: Deserialize TypeOfExprType
915 assert(false && "Cannot de-serialize typeof(expr) from a PCH file");
916 return QualType();
917
918 case pch::TYPE_TYPEOF: {
919 if (Record.size() != 1) {
920 Error("Incorrect encoding of typeof(type) in PCH file");
921 return QualType();
922 }
923 QualType UnderlyingType = GetType(Record[0]);
924 return Context.getTypeOfType(UnderlyingType);
925 }
926
927 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +0000928 assert(Record.size() == 1 && "Incorrect encoding of record type");
929 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000930
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000931 case pch::TYPE_ENUM:
932 assert(Record.size() == 1 && "Incorrect encoding of enum type");
933 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
934
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000935 case pch::TYPE_OBJC_INTERFACE:
936 // FIXME: Deserialize ObjCInterfaceType
937 assert(false && "Cannot de-serialize ObjC interface types yet");
938 return QualType();
939
940 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
941 // FIXME: Deserialize ObjCQualifiedInterfaceType
942 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
943 return QualType();
944
945 case pch::TYPE_OBJC_QUALIFIED_ID:
946 // FIXME: Deserialize ObjCQualifiedIdType
947 assert(false && "Cannot de-serialize ObjC qualified id types yet");
948 return QualType();
949
950 case pch::TYPE_OBJC_QUALIFIED_CLASS:
951 // FIXME: Deserialize ObjCQualifiedClassType
952 assert(false && "Cannot de-serialize ObjC qualified class types yet");
953 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000954 }
955
956 // Suppress a GCC warning
957 return QualType();
958}
959
960/// \brief Note that we have loaded the declaration with the given
961/// Index.
962///
963/// This routine notes that this declaration has already been loaded,
964/// so that future GetDecl calls will return this declaration rather
965/// than trying to load a new declaration.
966inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
967 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
968 DeclAlreadyLoaded[Index] = true;
969 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
970}
971
972/// \brief Read the declaration at the given offset from the PCH file.
973Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
974 Decl *D = 0;
975 Stream.JumpToBit(Offset);
976 RecordData Record;
977 unsigned Code = Stream.ReadCode();
978 unsigned Idx = 0;
979 PCHDeclReader Reader(*this, Record, Idx);
980 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
981 case pch::DECL_TRANSLATION_UNIT:
982 assert(Index == 0 && "Translation unit must be at index 0");
983 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
984 D = Context.getTranslationUnitDecl();
985 LoadedDecl(Index, D);
986 break;
987
988 case pch::DECL_TYPEDEF: {
989 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
990 0, QualType());
991 LoadedDecl(Index, Typedef);
992 Reader.VisitTypedefDecl(Typedef);
993 D = Typedef;
994 break;
995 }
996
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000997 case pch::DECL_ENUM: {
998 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
999 LoadedDecl(Index, Enum);
1000 Reader.VisitEnumDecl(Enum);
1001 D = Enum;
1002 break;
1003 }
1004
Douglas Gregor982365e2009-04-13 21:20:57 +00001005 case pch::DECL_RECORD: {
1006 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1007 0, SourceLocation(), 0, 0);
1008 LoadedDecl(Index, Record);
1009 Reader.VisitRecordDecl(Record);
1010 D = Record;
1011 break;
1012 }
1013
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001014 case pch::DECL_ENUM_CONSTANT: {
1015 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1016 SourceLocation(), 0,
1017 QualType(), 0,
1018 llvm::APSInt());
1019 LoadedDecl(Index, ECD);
1020 Reader.VisitEnumConstantDecl(ECD);
1021 D = ECD;
1022 break;
1023 }
1024
Douglas Gregor982365e2009-04-13 21:20:57 +00001025 case pch::DECL_FIELD: {
1026 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1027 QualType(), 0, false);
1028 LoadedDecl(Index, Field);
1029 Reader.VisitFieldDecl(Field);
1030 D = Field;
1031 break;
1032 }
1033
Douglas Gregorc34897d2009-04-09 22:27:44 +00001034 case pch::DECL_VAR: {
1035 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1036 VarDecl::None, SourceLocation());
1037 LoadedDecl(Index, Var);
1038 Reader.VisitVarDecl(Var);
1039 D = Var;
1040 break;
1041 }
1042
1043 default:
1044 assert(false && "Cannot de-serialize this kind of declaration");
1045 break;
1046 }
1047
1048 // If this declaration is also a declaration context, get the
1049 // offsets for its tables of lexical and visible declarations.
1050 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1051 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1052 if (Offsets.first || Offsets.second) {
1053 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1054 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1055 DeclContextOffsets[DC] = Offsets;
1056 }
1057 }
1058 assert(Idx == Record.size());
1059
1060 return D;
1061}
1062
Douglas Gregorac8f2802009-04-10 17:25:41 +00001063QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001064 unsigned Quals = ID & 0x07;
1065 unsigned Index = ID >> 3;
1066
1067 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1068 QualType T;
1069 switch ((pch::PredefinedTypeIDs)Index) {
1070 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1071 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1072 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1073
1074 case pch::PREDEF_TYPE_CHAR_U_ID:
1075 case pch::PREDEF_TYPE_CHAR_S_ID:
1076 // FIXME: Check that the signedness of CharTy is correct!
1077 T = Context.CharTy;
1078 break;
1079
1080 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1081 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1082 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1083 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1084 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1085 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1086 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1087 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1088 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1089 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1090 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1091 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1092 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1093 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1094 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1095 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1096 }
1097
1098 assert(!T.isNull() && "Unknown predefined type");
1099 return T.getQualifiedType(Quals);
1100 }
1101
1102 Index -= pch::NUM_PREDEF_TYPE_IDS;
1103 if (!TypeAlreadyLoaded[Index]) {
1104 // Load the type from the PCH file.
1105 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1106 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1107 TypeAlreadyLoaded[Index] = true;
1108 }
1109
1110 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1111}
1112
Douglas Gregorac8f2802009-04-10 17:25:41 +00001113Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001114 if (ID == 0)
1115 return 0;
1116
1117 unsigned Index = ID - 1;
1118 if (DeclAlreadyLoaded[Index])
1119 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1120
1121 // Load the declaration from the PCH file.
1122 return ReadDeclRecord(DeclOffsets[Index], Index);
1123}
1124
1125bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001126 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001127 assert(DC->hasExternalLexicalStorage() &&
1128 "DeclContext has no lexical decls in storage");
1129 uint64_t Offset = DeclContextOffsets[DC].first;
1130 assert(Offset && "DeclContext has no lexical decls in storage");
1131
1132 // Load the record containing all of the declarations lexically in
1133 // this context.
1134 Stream.JumpToBit(Offset);
1135 RecordData Record;
1136 unsigned Code = Stream.ReadCode();
1137 unsigned RecCode = Stream.ReadRecord(Code, Record);
1138 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1139
1140 // Load all of the declaration IDs
1141 Decls.clear();
1142 Decls.insert(Decls.end(), Record.begin(), Record.end());
1143 return false;
1144}
1145
1146bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1147 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1148 assert(DC->hasExternalVisibleStorage() &&
1149 "DeclContext has no visible decls in storage");
1150 uint64_t Offset = DeclContextOffsets[DC].second;
1151 assert(Offset && "DeclContext has no visible decls in storage");
1152
1153 // Load the record containing all of the declarations visible in
1154 // this context.
1155 Stream.JumpToBit(Offset);
1156 RecordData Record;
1157 unsigned Code = Stream.ReadCode();
1158 unsigned RecCode = Stream.ReadRecord(Code, Record);
1159 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1160 if (Record.size() == 0)
1161 return false;
1162
1163 Decls.clear();
1164
1165 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001166 while (Idx < Record.size()) {
1167 Decls.push_back(VisibleDeclaration());
1168 Decls.back().Name = ReadDeclarationName(Record, Idx);
1169
Douglas Gregorc34897d2009-04-09 22:27:44 +00001170 unsigned Size = Record[Idx++];
1171 llvm::SmallVector<unsigned, 4> & LoadedDecls
1172 = Decls.back().Declarations;
1173 LoadedDecls.reserve(Size);
1174 for (unsigned I = 0; I < Size; ++I)
1175 LoadedDecls.push_back(Record[Idx++]);
1176 }
1177
1178 return false;
1179}
1180
1181void PCHReader::PrintStats() {
1182 std::fprintf(stderr, "*** PCH Statistics:\n");
1183
1184 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1185 TypeAlreadyLoaded.end(),
1186 true);
1187 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1188 DeclAlreadyLoaded.end(),
1189 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001190 unsigned NumIdentifiersLoaded = 0;
1191 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1192 if ((IdentifierData[I] & 0x01) == 0)
1193 ++NumIdentifiersLoaded;
1194 }
1195
Douglas Gregorc34897d2009-04-09 22:27:44 +00001196 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1197 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001198 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001199 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1200 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001201 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1202 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1203 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1204 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001205 std::fprintf(stderr, "\n");
1206}
1207
Chris Lattner29241862009-04-11 21:15:38 +00001208IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001209 if (ID == 0)
1210 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001211
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001212 if (!IdentifierTable || IdentifierData.empty()) {
1213 Error("No identifier table in PCH file");
1214 return 0;
1215 }
Chris Lattner29241862009-04-11 21:15:38 +00001216
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001217 if (IdentifierData[ID - 1] & 0x01) {
1218 uint64_t Offset = IdentifierData[ID - 1];
1219 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001220 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001221 }
Chris Lattner29241862009-04-11 21:15:38 +00001222
1223 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001224}
1225
1226DeclarationName
1227PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1228 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1229 switch (Kind) {
1230 case DeclarationName::Identifier:
1231 return DeclarationName(GetIdentifierInfo(Record, Idx));
1232
1233 case DeclarationName::ObjCZeroArgSelector:
1234 case DeclarationName::ObjCOneArgSelector:
1235 case DeclarationName::ObjCMultiArgSelector:
1236 assert(false && "Unable to de-serialize Objective-C selectors");
1237 break;
1238
1239 case DeclarationName::CXXConstructorName:
1240 return Context.DeclarationNames.getCXXConstructorName(
1241 GetType(Record[Idx++]));
1242
1243 case DeclarationName::CXXDestructorName:
1244 return Context.DeclarationNames.getCXXDestructorName(
1245 GetType(Record[Idx++]));
1246
1247 case DeclarationName::CXXConversionFunctionName:
1248 return Context.DeclarationNames.getCXXConversionFunctionName(
1249 GetType(Record[Idx++]));
1250
1251 case DeclarationName::CXXOperatorName:
1252 return Context.DeclarationNames.getCXXOperatorName(
1253 (OverloadedOperatorKind)Record[Idx++]);
1254
1255 case DeclarationName::CXXUsingDirective:
1256 return DeclarationName::getUsingDirectiveName();
1257 }
1258
1259 // Required to silence GCC warning
1260 return DeclarationName();
1261}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001262
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001263/// \brief Read an integral value
1264llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1265 unsigned BitWidth = Record[Idx++];
1266 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1267 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1268 Idx += NumWords;
1269 return Result;
1270}
1271
1272/// \brief Read a signed integral value
1273llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1274 bool isUnsigned = Record[Idx++];
1275 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1276}
1277
Douglas Gregor179cfb12009-04-10 20:39:37 +00001278DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001279 return Diag(SourceLocation(), DiagID);
1280}
1281
1282DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1283 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001284 Context.getSourceManager()),
1285 DiagID);
1286}