blob: c843e81fec2f0a9807a0e2258e198b84ab88fa68 [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 Gregorc34897d2009-04-09 22:27:44 +000053 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000054 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000055 void VisitVarDecl(VarDecl *VD);
56
57 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
58 };
59}
60
61void PCHDeclReader::VisitDecl(Decl *D) {
62 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
63 D->setLexicalDeclContext(
64 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
65 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
66 D->setInvalidDecl(Record[Idx++]);
67 // FIXME: hasAttrs
68 D->setImplicit(Record[Idx++]);
69 D->setAccess((AccessSpecifier)Record[Idx++]);
70}
71
72void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
73 VisitDecl(TU);
74}
75
76void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
77 VisitDecl(ND);
78 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
79}
80
81void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
82 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000083 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
84}
85
86void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000087 // Note that we cannot use VisitTypeDecl here, because we need to
88 // set the underlying type of the typedef *before* we try to read
89 // the type associated with the TypedefDecl.
90 VisitNamedDecl(TD);
91 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
92 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
93 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +000094}
95
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000096void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
97 VisitTypeDecl(TD);
98 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
99 TD->setDefinition(Record[Idx++]);
100 TD->setTypedefForAnonDecl(
101 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
102}
103
104void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
105 VisitTagDecl(ED);
106 ED->setIntegerType(Reader.GetType(Record[Idx++]));
107}
108
Douglas Gregorc34897d2009-04-09 22:27:44 +0000109void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
110 VisitNamedDecl(VD);
111 VD->setType(Reader.GetType(Record[Idx++]));
112}
113
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000114void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
115 VisitValueDecl(ECD);
116 // FIXME: initialization expression
117 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
118}
119
Douglas Gregorc34897d2009-04-09 22:27:44 +0000120void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
121 VisitValueDecl(VD);
122 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
123 VD->setThreadSpecified(Record[Idx++]);
124 VD->setCXXDirectInitializer(Record[Idx++]);
125 VD->setDeclaredInCondition(Record[Idx++]);
126 VD->setPreviousDeclaration(
127 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
128 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
129}
130
131std::pair<uint64_t, uint64_t>
132PCHDeclReader::VisitDeclContext(DeclContext *DC) {
133 uint64_t LexicalOffset = Record[Idx++];
134 uint64_t VisibleOffset = 0;
135 if (DC->getPrimaryContext() == DC)
136 VisibleOffset = Record[Idx++];
137 return std::make_pair(LexicalOffset, VisibleOffset);
138}
139
140// FIXME: use the diagnostics machinery
141static bool Error(const char *Str) {
142 std::fprintf(stderr, "%s\n", Str);
143 return true;
144}
145
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000146/// \brief Check the contents of the predefines buffer against the
147/// contents of the predefines buffer used to build the PCH file.
148///
149/// The contents of the two predefines buffers should be the same. If
150/// not, then some command-line option changed the preprocessor state
151/// and we must reject the PCH file.
152///
153/// \param PCHPredef The start of the predefines buffer in the PCH
154/// file.
155///
156/// \param PCHPredefLen The length of the predefines buffer in the PCH
157/// file.
158///
159/// \param PCHBufferID The FileID for the PCH predefines buffer.
160///
161/// \returns true if there was a mismatch (in which case the PCH file
162/// should be ignored), or false otherwise.
163bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
164 unsigned PCHPredefLen,
165 FileID PCHBufferID) {
166 const char *Predef = PP.getPredefines().c_str();
167 unsigned PredefLen = PP.getPredefines().size();
168
169 // If the two predefines buffers compare equal, we're done!.
170 if (PredefLen == PCHPredefLen &&
171 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
172 return false;
173
174 // The predefines buffers are different. Produce a reasonable
175 // diagnostic showing where they are different.
176
177 // The source locations (potentially in the two different predefines
178 // buffers)
179 SourceLocation Loc1, Loc2;
180 SourceManager &SourceMgr = PP.getSourceManager();
181
182 // Create a source buffer for our predefines string, so
183 // that we can build a diagnostic that points into that
184 // source buffer.
185 FileID BufferID;
186 if (Predef && Predef[0]) {
187 llvm::MemoryBuffer *Buffer
188 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
189 "<built-in>");
190 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
191 }
192
193 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
194 std::pair<const char *, const char *> Locations
195 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
196
197 if (Locations.first != Predef + MinLen) {
198 // We found the location in the two buffers where there is a
199 // difference. Form source locations to point there (in both
200 // buffers).
201 unsigned Offset = Locations.first - Predef;
202 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
203 .getFileLocWithOffset(Offset);
204 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
205 .getFileLocWithOffset(Offset);
206 } else if (PredefLen > PCHPredefLen) {
207 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
208 .getFileLocWithOffset(MinLen);
209 } else {
210 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
211 .getFileLocWithOffset(MinLen);
212 }
213
214 Diag(Loc1, diag::warn_pch_preprocessor);
215 if (Loc2.isValid())
216 Diag(Loc2, diag::note_predef_in_pch);
217 Diag(diag::note_ignoring_pch) << FileName;
218 return true;
219}
220
Douglas Gregor635f97f2009-04-13 16:31:14 +0000221/// \brief Read the line table in the source manager block.
222/// \returns true if ther was an error.
223static bool ParseLineTable(SourceManager &SourceMgr,
224 llvm::SmallVectorImpl<uint64_t> &Record) {
225 unsigned Idx = 0;
226 LineTableInfo &LineTable = SourceMgr.getLineTable();
227
228 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000229 std::map<int, int> FileIDs;
230 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000231 // Extract the file name
232 unsigned FilenameLen = Record[Idx++];
233 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
234 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000235 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
236 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000237 }
238
239 // Parse the line entries
240 std::vector<LineEntry> Entries;
241 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000242 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000243
244 // Extract the line entries
245 unsigned NumEntries = Record[Idx++];
246 Entries.clear();
247 Entries.reserve(NumEntries);
248 for (unsigned I = 0; I != NumEntries; ++I) {
249 unsigned FileOffset = Record[Idx++];
250 unsigned LineNo = Record[Idx++];
251 int FilenameID = Record[Idx++];
252 SrcMgr::CharacteristicKind FileKind
253 = (SrcMgr::CharacteristicKind)Record[Idx++];
254 unsigned IncludeOffset = Record[Idx++];
255 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
256 FileKind, IncludeOffset));
257 }
258 LineTable.AddEntry(FID, Entries);
259 }
260
261 return false;
262}
263
Douglas Gregorab1cef72009-04-10 03:52:48 +0000264/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000265PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000266 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000267 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
268 Error("Malformed source manager block record");
269 return Failure;
270 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000271
272 SourceManager &SourceMgr = Context.getSourceManager();
273 RecordData Record;
274 while (true) {
275 unsigned Code = Stream.ReadCode();
276 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000277 if (Stream.ReadBlockEnd()) {
278 Error("Error at end of Source Manager block");
279 return Failure;
280 }
281
282 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000283 }
284
285 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
286 // No known subblocks, always skip them.
287 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000288 if (Stream.SkipBlock()) {
289 Error("Malformed block record");
290 return Failure;
291 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000292 continue;
293 }
294
295 if (Code == llvm::bitc::DEFINE_ABBREV) {
296 Stream.ReadAbbrevRecord();
297 continue;
298 }
299
300 // Read a record.
301 const char *BlobStart;
302 unsigned BlobLen;
303 Record.clear();
304 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
305 default: // Default behavior: ignore.
306 break;
307
308 case pch::SM_SLOC_FILE_ENTRY: {
309 // FIXME: We would really like to delay the creation of this
310 // FileEntry until it is actually required, e.g., when producing
311 // a diagnostic with a source location in this file.
312 const FileEntry *File
313 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
314 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000315 FileID ID = SourceMgr.createFileID(File,
316 SourceLocation::getFromRawEncoding(Record[1]),
317 (CharacteristicKind)Record[2]);
318 if (Record[3])
319 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
320 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000321 break;
322 }
323
324 case pch::SM_SLOC_BUFFER_ENTRY: {
325 const char *Name = BlobStart;
326 unsigned Code = Stream.ReadCode();
327 Record.clear();
328 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
329 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000330 llvm::MemoryBuffer *Buffer
331 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
332 BlobStart + BlobLen - 1,
333 Name);
334 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
335
336 if (strcmp(Name, "<built-in>") == 0
337 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
338 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000339 break;
340 }
341
342 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
343 SourceLocation SpellingLoc
344 = SourceLocation::getFromRawEncoding(Record[1]);
345 SourceMgr.createInstantiationLoc(
346 SpellingLoc,
347 SourceLocation::getFromRawEncoding(Record[2]),
348 SourceLocation::getFromRawEncoding(Record[3]),
349 Lexer::MeasureTokenLength(SpellingLoc,
350 SourceMgr));
351 break;
352 }
353
Douglas Gregor635f97f2009-04-13 16:31:14 +0000354 case pch::SM_LINE_TABLE: {
355 if (ParseLineTable(SourceMgr, Record))
356 return Failure;
357 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000358 }
359 }
360}
361
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000362bool PCHReader::ReadPreprocessorBlock() {
363 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
364 return Error("Malformed preprocessor block record");
365
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000366 RecordData Record;
367 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
368 MacroInfo *LastMacro = 0;
369
370 while (true) {
371 unsigned Code = Stream.ReadCode();
372 switch (Code) {
373 case llvm::bitc::END_BLOCK:
374 if (Stream.ReadBlockEnd())
375 return Error("Error at end of preprocessor block");
376 return false;
377
378 case llvm::bitc::ENTER_SUBBLOCK:
379 // No known subblocks, always skip them.
380 Stream.ReadSubBlockID();
381 if (Stream.SkipBlock())
382 return Error("Malformed block record");
383 continue;
384
385 case llvm::bitc::DEFINE_ABBREV:
386 Stream.ReadAbbrevRecord();
387 continue;
388 default: break;
389 }
390
391 // Read a record.
392 Record.clear();
393 pch::PreprocessorRecordTypes RecType =
394 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
395 switch (RecType) {
396 default: // Default behavior: ignore unknown records.
397 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000398 case pch::PP_COUNTER_VALUE:
399 if (!Record.empty())
400 PP.setCounterValue(Record[0]);
401 break;
402
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000403 case pch::PP_MACRO_OBJECT_LIKE:
404 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000405 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
406 if (II == 0)
407 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000408 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
409 bool isUsed = Record[2];
410
411 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
412 MI->setIsUsed(isUsed);
413
414 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
415 // Decode function-like macro info.
416 bool isC99VarArgs = Record[3];
417 bool isGNUVarArgs = Record[4];
418 MacroArgs.clear();
419 unsigned NumArgs = Record[5];
420 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000421 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000422
423 // Install function-like macro info.
424 MI->setIsFunctionLike();
425 if (isC99VarArgs) MI->setIsC99Varargs();
426 if (isGNUVarArgs) MI->setIsGNUVarargs();
427 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
428 PP.getPreprocessorAllocator());
429 }
430
431 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000432 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000433
434 // Remember that we saw this macro last so that we add the tokens that
435 // form its body to it.
436 LastMacro = MI;
437 break;
438 }
439
440 case pch::PP_TOKEN: {
441 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
442 // pretend we didn't see this.
443 if (LastMacro == 0) break;
444
445 Token Tok;
446 Tok.startToken();
447 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
448 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000449 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
450 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000451 Tok.setKind((tok::TokenKind)Record[3]);
452 Tok.setFlag((Token::TokenFlags)Record[4]);
453 LastMacro->AddTokenToBody(Tok);
454 break;
455 }
456 }
457 }
458}
459
Douglas Gregor179cfb12009-04-10 20:39:37 +0000460PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
461 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
462 Error("Malformed block record");
463 return Failure;
464 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000465
Chris Lattner29241862009-04-11 21:15:38 +0000466 uint64_t PreprocessorBlockBit = 0;
467
Douglas Gregorc34897d2009-04-09 22:27:44 +0000468 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000469 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000470 while (!Stream.AtEndOfStream()) {
471 unsigned Code = Stream.ReadCode();
472 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000473 // If we saw the preprocessor block, read it now.
474 if (PreprocessorBlockBit) {
475 uint64_t SavedPos = Stream.GetCurrentBitNo();
476 Stream.JumpToBit(PreprocessorBlockBit);
477 if (ReadPreprocessorBlock()) {
478 Error("Malformed preprocessor block");
479 return Failure;
480 }
481 Stream.JumpToBit(SavedPos);
482 }
483
Douglas Gregor179cfb12009-04-10 20:39:37 +0000484 if (Stream.ReadBlockEnd()) {
485 Error("Error at end of module block");
486 return Failure;
487 }
Chris Lattner29241862009-04-11 21:15:38 +0000488
Douglas Gregor179cfb12009-04-10 20:39:37 +0000489 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000490 }
491
492 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
493 switch (Stream.ReadSubBlockID()) {
494 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
495 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
496 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000497 if (Stream.SkipBlock()) {
498 Error("Malformed block record");
499 return Failure;
500 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000501 break;
502
Chris Lattner29241862009-04-11 21:15:38 +0000503 case pch::PREPROCESSOR_BLOCK_ID:
504 // Skip the preprocessor block for now, but remember where it is. We
505 // want to read it in after the identifier table.
506 if (PreprocessorBlockBit) {
507 Error("Multiple preprocessor blocks found.");
508 return Failure;
509 }
510 PreprocessorBlockBit = Stream.GetCurrentBitNo();
511 if (Stream.SkipBlock()) {
512 Error("Malformed block record");
513 return Failure;
514 }
515 break;
516
Douglas Gregorab1cef72009-04-10 03:52:48 +0000517 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000518 switch (ReadSourceManagerBlock()) {
519 case Success:
520 break;
521
522 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000523 Error("Malformed source manager block");
524 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000525
526 case IgnorePCH:
527 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000528 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000529 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000530 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000531 continue;
532 }
533
534 if (Code == llvm::bitc::DEFINE_ABBREV) {
535 Stream.ReadAbbrevRecord();
536 continue;
537 }
538
539 // Read and process a record.
540 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000541 const char *BlobStart = 0;
542 unsigned BlobLen = 0;
543 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
544 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000545 default: // Default behavior: ignore.
546 break;
547
548 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000549 if (!TypeOffsets.empty()) {
550 Error("Duplicate TYPE_OFFSET record in PCH file");
551 return Failure;
552 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000553 TypeOffsets.swap(Record);
554 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
555 break;
556
557 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000558 if (!DeclOffsets.empty()) {
559 Error("Duplicate DECL_OFFSET record in PCH file");
560 return Failure;
561 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000562 DeclOffsets.swap(Record);
563 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
564 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000565
566 case pch::LANGUAGE_OPTIONS:
567 if (ParseLanguageOptions(Record))
568 return IgnorePCH;
569 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000570
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000571 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000572 std::string TargetTriple(BlobStart, BlobLen);
573 if (TargetTriple != Context.Target.getTargetTriple()) {
574 Diag(diag::warn_pch_target_triple)
575 << TargetTriple << Context.Target.getTargetTriple();
576 Diag(diag::note_ignoring_pch) << FileName;
577 return IgnorePCH;
578 }
579 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000580 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000581
582 case pch::IDENTIFIER_TABLE:
583 IdentifierTable = BlobStart;
584 break;
585
586 case pch::IDENTIFIER_OFFSET:
587 if (!IdentifierData.empty()) {
588 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
589 return Failure;
590 }
591 IdentifierData.swap(Record);
592#ifndef NDEBUG
593 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
594 if ((IdentifierData[I] & 0x01) == 0) {
595 Error("Malformed identifier table in the precompiled header");
596 return Failure;
597 }
598 }
599#endif
600 break;
601 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000602 }
603
Douglas Gregor179cfb12009-04-10 20:39:37 +0000604 Error("Premature end of bitstream");
605 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000606}
607
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000608PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000609 // Set the PCH file name.
610 this->FileName = FileName;
611
Douglas Gregorc34897d2009-04-09 22:27:44 +0000612 // Open the PCH file.
613 std::string ErrStr;
614 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000615 if (!Buffer) {
616 Error(ErrStr.c_str());
617 return IgnorePCH;
618 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000619
620 // Initialize the stream
621 Stream.init((const unsigned char *)Buffer->getBufferStart(),
622 (const unsigned char *)Buffer->getBufferEnd());
623
624 // Sniff for the signature.
625 if (Stream.Read(8) != 'C' ||
626 Stream.Read(8) != 'P' ||
627 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000628 Stream.Read(8) != 'H') {
629 Error("Not a PCH file");
630 return IgnorePCH;
631 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000632
633 // We expect a number of well-defined blocks, though we don't necessarily
634 // need to understand them all.
635 while (!Stream.AtEndOfStream()) {
636 unsigned Code = Stream.ReadCode();
637
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000638 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
639 Error("Invalid record at top-level");
640 return Failure;
641 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000642
643 unsigned BlockID = Stream.ReadSubBlockID();
644
645 // We only know the PCH subblock ID.
646 switch (BlockID) {
647 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000648 if (Stream.ReadBlockInfoBlock()) {
649 Error("Malformed BlockInfoBlock");
650 return Failure;
651 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000652 break;
653 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000654 switch (ReadPCHBlock()) {
655 case Success:
656 break;
657
658 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000659 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000660
661 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000662 // FIXME: We could consider reading through to the end of this
663 // PCH block, skipping subblocks, to see if there are other
664 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000665 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000666 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000667 break;
668 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000669 if (Stream.SkipBlock()) {
670 Error("Malformed block record");
671 return Failure;
672 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000673 break;
674 }
675 }
676
677 // Load the translation unit declaration
678 ReadDeclRecord(DeclOffsets[0], 0);
679
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000680 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000681}
682
Douglas Gregor179cfb12009-04-10 20:39:37 +0000683/// \brief Parse the record that corresponds to a LangOptions data
684/// structure.
685///
686/// This routine compares the language options used to generate the
687/// PCH file against the language options set for the current
688/// compilation. For each option, we classify differences between the
689/// two compiler states as either "benign" or "important". Benign
690/// differences don't matter, and we accept them without complaint
691/// (and without modifying the language options). Differences between
692/// the states for important options cause the PCH file to be
693/// unusable, so we emit a warning and return true to indicate that
694/// there was an error.
695///
696/// \returns true if the PCH file is unacceptable, false otherwise.
697bool PCHReader::ParseLanguageOptions(
698 const llvm::SmallVectorImpl<uint64_t> &Record) {
699 const LangOptions &LangOpts = Context.getLangOptions();
700#define PARSE_LANGOPT_BENIGN(Option) ++Idx
701#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
702 if (Record[Idx] != LangOpts.Option) { \
703 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
704 Diag(diag::note_ignoring_pch) << FileName; \
705 return true; \
706 } \
707 ++Idx
708
709 unsigned Idx = 0;
710 PARSE_LANGOPT_BENIGN(Trigraphs);
711 PARSE_LANGOPT_BENIGN(BCPLComment);
712 PARSE_LANGOPT_BENIGN(DollarIdents);
713 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
714 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
715 PARSE_LANGOPT_BENIGN(ImplicitInt);
716 PARSE_LANGOPT_BENIGN(Digraphs);
717 PARSE_LANGOPT_BENIGN(HexFloats);
718 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
719 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
720 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
721 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
722 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
723 PARSE_LANGOPT_BENIGN(CXXOperatorName);
724 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
725 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
726 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
727 PARSE_LANGOPT_BENIGN(PascalStrings);
728 PARSE_LANGOPT_BENIGN(Boolean);
729 PARSE_LANGOPT_BENIGN(WritableStrings);
730 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
731 diag::warn_pch_lax_vector_conversions);
732 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
733 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
734 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
735 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
736 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
737 diag::warn_pch_thread_safe_statics);
738 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
739 PARSE_LANGOPT_BENIGN(EmitAllDecls);
740 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
741 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
742 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
743 diag::warn_pch_heinous_extensions);
744 // FIXME: Most of the options below are benign if the macro wasn't
745 // used. Unfortunately, this means that a PCH compiled without
746 // optimization can't be used with optimization turned on, even
747 // though the only thing that changes is whether __OPTIMIZE__ was
748 // defined... but if __OPTIMIZE__ never showed up in the header, it
749 // doesn't matter. We could consider making this some special kind
750 // of check.
751 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
752 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
753 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
754 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
755 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
756 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
757 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
758 Diag(diag::warn_pch_gc_mode)
759 << (unsigned)Record[Idx] << LangOpts.getGCMode();
760 Diag(diag::note_ignoring_pch) << FileName;
761 return true;
762 }
763 ++Idx;
764 PARSE_LANGOPT_BENIGN(getVisibilityMode());
765 PARSE_LANGOPT_BENIGN(InstantiationDepth);
766#undef PARSE_LANGOPT_IRRELEVANT
767#undef PARSE_LANGOPT_BENIGN
768
769 return false;
770}
771
Douglas Gregorc34897d2009-04-09 22:27:44 +0000772/// \brief Read and return the type at the given offset.
773///
774/// This routine actually reads the record corresponding to the type
775/// at the given offset in the bitstream. It is a helper routine for
776/// GetType, which deals with reading type IDs.
777QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
778 Stream.JumpToBit(Offset);
779 RecordData Record;
780 unsigned Code = Stream.ReadCode();
781 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000782 case pch::TYPE_EXT_QUAL:
783 // FIXME: Deserialize ExtQualType
784 assert(false && "Cannot deserialize qualified types yet");
785 return QualType();
786
Douglas Gregorc34897d2009-04-09 22:27:44 +0000787 case pch::TYPE_FIXED_WIDTH_INT: {
788 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
789 return Context.getFixedWidthIntType(Record[0], Record[1]);
790 }
791
792 case pch::TYPE_COMPLEX: {
793 assert(Record.size() == 1 && "Incorrect encoding of complex type");
794 QualType ElemType = GetType(Record[0]);
795 return Context.getComplexType(ElemType);
796 }
797
798 case pch::TYPE_POINTER: {
799 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
800 QualType PointeeType = GetType(Record[0]);
801 return Context.getPointerType(PointeeType);
802 }
803
804 case pch::TYPE_BLOCK_POINTER: {
805 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
806 QualType PointeeType = GetType(Record[0]);
807 return Context.getBlockPointerType(PointeeType);
808 }
809
810 case pch::TYPE_LVALUE_REFERENCE: {
811 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
812 QualType PointeeType = GetType(Record[0]);
813 return Context.getLValueReferenceType(PointeeType);
814 }
815
816 case pch::TYPE_RVALUE_REFERENCE: {
817 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
818 QualType PointeeType = GetType(Record[0]);
819 return Context.getRValueReferenceType(PointeeType);
820 }
821
822 case pch::TYPE_MEMBER_POINTER: {
823 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
824 QualType PointeeType = GetType(Record[0]);
825 QualType ClassType = GetType(Record[1]);
826 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
827 }
828
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000829 case pch::TYPE_CONSTANT_ARRAY: {
830 QualType ElementType = GetType(Record[0]);
831 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
832 unsigned IndexTypeQuals = Record[2];
833 unsigned Idx = 3;
834 llvm::APInt Size = ReadAPInt(Record, Idx);
835 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
836 }
837
838 case pch::TYPE_INCOMPLETE_ARRAY: {
839 QualType ElementType = GetType(Record[0]);
840 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
841 unsigned IndexTypeQuals = Record[2];
842 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
843 }
844
845 case pch::TYPE_VARIABLE_ARRAY: {
846 // FIXME: implement this
847 assert(false && "Unable to de-serialize variable-length array type");
848 return QualType();
849 }
850
851 case pch::TYPE_VECTOR: {
852 if (Record.size() != 2) {
853 Error("Incorrect encoding of vector type in PCH file");
854 return QualType();
855 }
856
857 QualType ElementType = GetType(Record[0]);
858 unsigned NumElements = Record[1];
859 return Context.getVectorType(ElementType, NumElements);
860 }
861
862 case pch::TYPE_EXT_VECTOR: {
863 if (Record.size() != 2) {
864 Error("Incorrect encoding of extended vector type in PCH file");
865 return QualType();
866 }
867
868 QualType ElementType = GetType(Record[0]);
869 unsigned NumElements = Record[1];
870 return Context.getExtVectorType(ElementType, NumElements);
871 }
872
873 case pch::TYPE_FUNCTION_NO_PROTO: {
874 if (Record.size() != 1) {
875 Error("Incorrect encoding of no-proto function type");
876 return QualType();
877 }
878 QualType ResultType = GetType(Record[0]);
879 return Context.getFunctionNoProtoType(ResultType);
880 }
881
882 case pch::TYPE_FUNCTION_PROTO: {
883 QualType ResultType = GetType(Record[0]);
884 unsigned Idx = 1;
885 unsigned NumParams = Record[Idx++];
886 llvm::SmallVector<QualType, 16> ParamTypes;
887 for (unsigned I = 0; I != NumParams; ++I)
888 ParamTypes.push_back(GetType(Record[Idx++]));
889 bool isVariadic = Record[Idx++];
890 unsigned Quals = Record[Idx++];
891 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
892 isVariadic, Quals);
893 }
894
895 case pch::TYPE_TYPEDEF:
896 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
897 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
898
899 case pch::TYPE_TYPEOF_EXPR:
900 // FIXME: Deserialize TypeOfExprType
901 assert(false && "Cannot de-serialize typeof(expr) from a PCH file");
902 return QualType();
903
904 case pch::TYPE_TYPEOF: {
905 if (Record.size() != 1) {
906 Error("Incorrect encoding of typeof(type) in PCH file");
907 return QualType();
908 }
909 QualType UnderlyingType = GetType(Record[0]);
910 return Context.getTypeOfType(UnderlyingType);
911 }
912
913 case pch::TYPE_RECORD:
914 // FIXME: Deserialize RecordType
915 assert(false && "Cannot de-serialize record types yet");
916 return QualType();
917
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000918 case pch::TYPE_ENUM:
919 assert(Record.size() == 1 && "Incorrect encoding of enum type");
920 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
921
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000922 case pch::TYPE_OBJC_INTERFACE:
923 // FIXME: Deserialize ObjCInterfaceType
924 assert(false && "Cannot de-serialize ObjC interface types yet");
925 return QualType();
926
927 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
928 // FIXME: Deserialize ObjCQualifiedInterfaceType
929 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
930 return QualType();
931
932 case pch::TYPE_OBJC_QUALIFIED_ID:
933 // FIXME: Deserialize ObjCQualifiedIdType
934 assert(false && "Cannot de-serialize ObjC qualified id types yet");
935 return QualType();
936
937 case pch::TYPE_OBJC_QUALIFIED_CLASS:
938 // FIXME: Deserialize ObjCQualifiedClassType
939 assert(false && "Cannot de-serialize ObjC qualified class types yet");
940 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000941 }
942
943 // Suppress a GCC warning
944 return QualType();
945}
946
947/// \brief Note that we have loaded the declaration with the given
948/// Index.
949///
950/// This routine notes that this declaration has already been loaded,
951/// so that future GetDecl calls will return this declaration rather
952/// than trying to load a new declaration.
953inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
954 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
955 DeclAlreadyLoaded[Index] = true;
956 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
957}
958
959/// \brief Read the declaration at the given offset from the PCH file.
960Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
961 Decl *D = 0;
962 Stream.JumpToBit(Offset);
963 RecordData Record;
964 unsigned Code = Stream.ReadCode();
965 unsigned Idx = 0;
966 PCHDeclReader Reader(*this, Record, Idx);
967 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
968 case pch::DECL_TRANSLATION_UNIT:
969 assert(Index == 0 && "Translation unit must be at index 0");
970 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
971 D = Context.getTranslationUnitDecl();
972 LoadedDecl(Index, D);
973 break;
974
975 case pch::DECL_TYPEDEF: {
976 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
977 0, QualType());
978 LoadedDecl(Index, Typedef);
979 Reader.VisitTypedefDecl(Typedef);
980 D = Typedef;
981 break;
982 }
983
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000984 case pch::DECL_ENUM: {
985 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
986 LoadedDecl(Index, Enum);
987 Reader.VisitEnumDecl(Enum);
988 D = Enum;
989 break;
990 }
991
992 case pch::DECL_ENUM_CONSTANT: {
993 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
994 SourceLocation(), 0,
995 QualType(), 0,
996 llvm::APSInt());
997 LoadedDecl(Index, ECD);
998 Reader.VisitEnumConstantDecl(ECD);
999 D = ECD;
1000 break;
1001 }
1002
Douglas Gregorc34897d2009-04-09 22:27:44 +00001003 case pch::DECL_VAR: {
1004 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1005 VarDecl::None, SourceLocation());
1006 LoadedDecl(Index, Var);
1007 Reader.VisitVarDecl(Var);
1008 D = Var;
1009 break;
1010 }
1011
1012 default:
1013 assert(false && "Cannot de-serialize this kind of declaration");
1014 break;
1015 }
1016
1017 // If this declaration is also a declaration context, get the
1018 // offsets for its tables of lexical and visible declarations.
1019 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1020 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1021 if (Offsets.first || Offsets.second) {
1022 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1023 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1024 DeclContextOffsets[DC] = Offsets;
1025 }
1026 }
1027 assert(Idx == Record.size());
1028
1029 return D;
1030}
1031
Douglas Gregorac8f2802009-04-10 17:25:41 +00001032QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001033 unsigned Quals = ID & 0x07;
1034 unsigned Index = ID >> 3;
1035
1036 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1037 QualType T;
1038 switch ((pch::PredefinedTypeIDs)Index) {
1039 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1040 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1041 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1042
1043 case pch::PREDEF_TYPE_CHAR_U_ID:
1044 case pch::PREDEF_TYPE_CHAR_S_ID:
1045 // FIXME: Check that the signedness of CharTy is correct!
1046 T = Context.CharTy;
1047 break;
1048
1049 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1050 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1051 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1052 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1053 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1054 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1055 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1056 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1057 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1058 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1059 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1060 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1061 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1062 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1063 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1064 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1065 }
1066
1067 assert(!T.isNull() && "Unknown predefined type");
1068 return T.getQualifiedType(Quals);
1069 }
1070
1071 Index -= pch::NUM_PREDEF_TYPE_IDS;
1072 if (!TypeAlreadyLoaded[Index]) {
1073 // Load the type from the PCH file.
1074 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1075 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1076 TypeAlreadyLoaded[Index] = true;
1077 }
1078
1079 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1080}
1081
Douglas Gregorac8f2802009-04-10 17:25:41 +00001082Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001083 if (ID == 0)
1084 return 0;
1085
1086 unsigned Index = ID - 1;
1087 if (DeclAlreadyLoaded[Index])
1088 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1089
1090 // Load the declaration from the PCH file.
1091 return ReadDeclRecord(DeclOffsets[Index], Index);
1092}
1093
1094bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001095 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001096 assert(DC->hasExternalLexicalStorage() &&
1097 "DeclContext has no lexical decls in storage");
1098 uint64_t Offset = DeclContextOffsets[DC].first;
1099 assert(Offset && "DeclContext has no lexical decls in storage");
1100
1101 // Load the record containing all of the declarations lexically in
1102 // this context.
1103 Stream.JumpToBit(Offset);
1104 RecordData Record;
1105 unsigned Code = Stream.ReadCode();
1106 unsigned RecCode = Stream.ReadRecord(Code, Record);
1107 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1108
1109 // Load all of the declaration IDs
1110 Decls.clear();
1111 Decls.insert(Decls.end(), Record.begin(), Record.end());
1112 return false;
1113}
1114
1115bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1116 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1117 assert(DC->hasExternalVisibleStorage() &&
1118 "DeclContext has no visible decls in storage");
1119 uint64_t Offset = DeclContextOffsets[DC].second;
1120 assert(Offset && "DeclContext has no visible decls in storage");
1121
1122 // Load the record containing all of the declarations visible in
1123 // this context.
1124 Stream.JumpToBit(Offset);
1125 RecordData Record;
1126 unsigned Code = Stream.ReadCode();
1127 unsigned RecCode = Stream.ReadRecord(Code, Record);
1128 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1129 if (Record.size() == 0)
1130 return false;
1131
1132 Decls.clear();
1133
1134 unsigned Idx = 0;
1135 // llvm::SmallVector<uintptr_t, 16> DeclIDs;
1136 while (Idx < Record.size()) {
1137 Decls.push_back(VisibleDeclaration());
1138 Decls.back().Name = ReadDeclarationName(Record, Idx);
1139
1140 // FIXME: Don't actually read anything here!
1141 unsigned Size = Record[Idx++];
1142 llvm::SmallVector<unsigned, 4> & LoadedDecls
1143 = Decls.back().Declarations;
1144 LoadedDecls.reserve(Size);
1145 for (unsigned I = 0; I < Size; ++I)
1146 LoadedDecls.push_back(Record[Idx++]);
1147 }
1148
1149 return false;
1150}
1151
1152void PCHReader::PrintStats() {
1153 std::fprintf(stderr, "*** PCH Statistics:\n");
1154
1155 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1156 TypeAlreadyLoaded.end(),
1157 true);
1158 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1159 DeclAlreadyLoaded.end(),
1160 true);
1161 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1162 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
1163 ((float)NumTypesLoaded/(float)TypeAlreadyLoaded.size() * 100));
1164 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1165 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
1166 ((float)NumDeclsLoaded/(float)DeclAlreadyLoaded.size() * 100));
1167 std::fprintf(stderr, "\n");
1168}
1169
Chris Lattner29241862009-04-11 21:15:38 +00001170IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001171 if (ID == 0)
1172 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001173
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001174 if (!IdentifierTable || IdentifierData.empty()) {
1175 Error("No identifier table in PCH file");
1176 return 0;
1177 }
Chris Lattner29241862009-04-11 21:15:38 +00001178
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001179 if (IdentifierData[ID - 1] & 0x01) {
1180 uint64_t Offset = IdentifierData[ID - 1];
1181 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001182 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001183 }
Chris Lattner29241862009-04-11 21:15:38 +00001184
1185 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001186}
1187
1188DeclarationName
1189PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1190 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1191 switch (Kind) {
1192 case DeclarationName::Identifier:
1193 return DeclarationName(GetIdentifierInfo(Record, Idx));
1194
1195 case DeclarationName::ObjCZeroArgSelector:
1196 case DeclarationName::ObjCOneArgSelector:
1197 case DeclarationName::ObjCMultiArgSelector:
1198 assert(false && "Unable to de-serialize Objective-C selectors");
1199 break;
1200
1201 case DeclarationName::CXXConstructorName:
1202 return Context.DeclarationNames.getCXXConstructorName(
1203 GetType(Record[Idx++]));
1204
1205 case DeclarationName::CXXDestructorName:
1206 return Context.DeclarationNames.getCXXDestructorName(
1207 GetType(Record[Idx++]));
1208
1209 case DeclarationName::CXXConversionFunctionName:
1210 return Context.DeclarationNames.getCXXConversionFunctionName(
1211 GetType(Record[Idx++]));
1212
1213 case DeclarationName::CXXOperatorName:
1214 return Context.DeclarationNames.getCXXOperatorName(
1215 (OverloadedOperatorKind)Record[Idx++]);
1216
1217 case DeclarationName::CXXUsingDirective:
1218 return DeclarationName::getUsingDirectiveName();
1219 }
1220
1221 // Required to silence GCC warning
1222 return DeclarationName();
1223}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001224
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001225/// \brief Read an integral value
1226llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1227 unsigned BitWidth = Record[Idx++];
1228 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1229 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1230 Idx += NumWords;
1231 return Result;
1232}
1233
1234/// \brief Read a signed integral value
1235llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1236 bool isUnsigned = Record[Idx++];
1237 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1238}
1239
Douglas Gregor179cfb12009-04-10 20:39:37 +00001240DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001241 return Diag(SourceLocation(), DiagID);
1242}
1243
1244DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1245 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001246 Context.getSourceManager()),
1247 DiagID);
1248}