blob: f5f6f5d41c99e53b98d1d0f78ba809454e17a3ec [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 Gregor631f6c62009-04-14 00:24:19 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Douglas Gregor631f6c62009-04-14 00:24:19 +000018#include "clang/AST/DeclGroup.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000019#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000020#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000023#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000024#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000025#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000026#include "llvm/Bitcode/BitstreamReader.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include <algorithm>
30#include <cstdio>
31
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Declaration deserialization
36//===----------------------------------------------------------------------===//
37namespace {
38 class VISIBILITY_HIDDEN PCHDeclReader {
39 PCHReader &Reader;
40 const PCHReader::RecordData &Record;
41 unsigned &Idx;
42
43 public:
44 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
45 unsigned &Idx)
46 : Reader(Reader), Record(Record), Idx(Idx) { }
47
48 void VisitDecl(Decl *D);
49 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
50 void VisitNamedDecl(NamedDecl *ND);
51 void VisitTypeDecl(TypeDecl *TD);
52 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000053 void VisitTagDecl(TagDecl *TD);
54 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000055 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000056 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000057 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000058 void VisitFunctionDecl(FunctionDecl *FD);
Douglas Gregor982365e2009-04-13 21:20:57 +000059 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000060 void VisitVarDecl(VarDecl *VD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000061 void VisitParmVarDecl(ParmVarDecl *PD);
62 void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD);
Douglas Gregor2a491792009-04-13 22:49:25 +000063 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
64 void VisitBlockDecl(BlockDecl *BD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000065 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
66 };
67}
68
69void PCHDeclReader::VisitDecl(Decl *D) {
70 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
71 D->setLexicalDeclContext(
72 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
73 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
74 D->setInvalidDecl(Record[Idx++]);
75 // FIXME: hasAttrs
76 D->setImplicit(Record[Idx++]);
77 D->setAccess((AccessSpecifier)Record[Idx++]);
78}
79
80void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
81 VisitDecl(TU);
82}
83
84void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
85 VisitDecl(ND);
86 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
87}
88
89void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
90 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000091 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
92}
93
94void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000095 // Note that we cannot use VisitTypeDecl here, because we need to
96 // set the underlying type of the typedef *before* we try to read
97 // the type associated with the TypedefDecl.
98 VisitNamedDecl(TD);
99 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
100 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
101 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000102}
103
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000104void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
105 VisitTypeDecl(TD);
106 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
107 TD->setDefinition(Record[Idx++]);
108 TD->setTypedefForAnonDecl(
109 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
110}
111
112void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
113 VisitTagDecl(ED);
114 ED->setIntegerType(Reader.GetType(Record[Idx++]));
115}
116
Douglas Gregor982365e2009-04-13 21:20:57 +0000117void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
118 VisitTagDecl(RD);
119 RD->setHasFlexibleArrayMember(Record[Idx++]);
120 RD->setAnonymousStructOrUnion(Record[Idx++]);
121}
122
Douglas Gregorc34897d2009-04-09 22:27:44 +0000123void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
124 VisitNamedDecl(VD);
125 VD->setType(Reader.GetType(Record[Idx++]));
126}
127
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000128void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
129 VisitValueDecl(ECD);
Douglas Gregor982365e2009-04-13 21:20:57 +0000130 // FIXME: read the initialization expression
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000131 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
132}
133
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000134void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
135 VisitValueDecl(FD);
136 // FIXME: function body
137 FD->setPreviousDeclaration(
138 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
139 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
140 FD->setInline(Record[Idx++]);
141 FD->setVirtual(Record[Idx++]);
142 FD->setPure(Record[Idx++]);
143 FD->setInheritedPrototype(Record[Idx++]);
144 FD->setHasPrototype(Record[Idx++]);
145 FD->setDeleted(Record[Idx++]);
146 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
147 unsigned NumParams = Record[Idx++];
148 llvm::SmallVector<ParmVarDecl *, 16> Params;
149 Params.reserve(NumParams);
150 for (unsigned I = 0; I != NumParams; ++I)
151 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
152 FD->setParams(Reader.getContext(), &Params[0], NumParams);
153}
154
Douglas Gregor982365e2009-04-13 21:20:57 +0000155void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
156 VisitValueDecl(FD);
157 FD->setMutable(Record[Idx++]);
158 // FIXME: Read the bit width.
159}
160
Douglas Gregorc34897d2009-04-09 22:27:44 +0000161void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
162 VisitValueDecl(VD);
163 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
164 VD->setThreadSpecified(Record[Idx++]);
165 VD->setCXXDirectInitializer(Record[Idx++]);
166 VD->setDeclaredInCondition(Record[Idx++]);
167 VD->setPreviousDeclaration(
168 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
169 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
170}
171
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000172void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
173 VisitVarDecl(PD);
174 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
175 // FIXME: default argument
176}
177
178void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
179 VisitParmVarDecl(PD);
180 PD->setOriginalType(Reader.GetType(Record[Idx++]));
181}
182
Douglas Gregor2a491792009-04-13 22:49:25 +0000183void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
184 VisitDecl(AD);
185 // FIXME: read asm string
186}
187
188void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
189 VisitDecl(BD);
190 unsigned NumParams = Record[Idx++];
191 llvm::SmallVector<ParmVarDecl *, 16> Params;
192 Params.reserve(NumParams);
193 for (unsigned I = 0; I != NumParams; ++I)
194 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
195 BD->setParams(Reader.getContext(), &Params[0], NumParams);
196}
197
Douglas Gregorc34897d2009-04-09 22:27:44 +0000198std::pair<uint64_t, uint64_t>
199PCHDeclReader::VisitDeclContext(DeclContext *DC) {
200 uint64_t LexicalOffset = Record[Idx++];
201 uint64_t VisibleOffset = 0;
202 if (DC->getPrimaryContext() == DC)
203 VisibleOffset = Record[Idx++];
204 return std::make_pair(LexicalOffset, VisibleOffset);
205}
206
207// FIXME: use the diagnostics machinery
208static bool Error(const char *Str) {
209 std::fprintf(stderr, "%s\n", Str);
210 return true;
211}
212
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000213/// \brief Check the contents of the predefines buffer against the
214/// contents of the predefines buffer used to build the PCH file.
215///
216/// The contents of the two predefines buffers should be the same. If
217/// not, then some command-line option changed the preprocessor state
218/// and we must reject the PCH file.
219///
220/// \param PCHPredef The start of the predefines buffer in the PCH
221/// file.
222///
223/// \param PCHPredefLen The length of the predefines buffer in the PCH
224/// file.
225///
226/// \param PCHBufferID The FileID for the PCH predefines buffer.
227///
228/// \returns true if there was a mismatch (in which case the PCH file
229/// should be ignored), or false otherwise.
230bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
231 unsigned PCHPredefLen,
232 FileID PCHBufferID) {
233 const char *Predef = PP.getPredefines().c_str();
234 unsigned PredefLen = PP.getPredefines().size();
235
236 // If the two predefines buffers compare equal, we're done!.
237 if (PredefLen == PCHPredefLen &&
238 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
239 return false;
240
241 // The predefines buffers are different. Produce a reasonable
242 // diagnostic showing where they are different.
243
244 // The source locations (potentially in the two different predefines
245 // buffers)
246 SourceLocation Loc1, Loc2;
247 SourceManager &SourceMgr = PP.getSourceManager();
248
249 // Create a source buffer for our predefines string, so
250 // that we can build a diagnostic that points into that
251 // source buffer.
252 FileID BufferID;
253 if (Predef && Predef[0]) {
254 llvm::MemoryBuffer *Buffer
255 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
256 "<built-in>");
257 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
258 }
259
260 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
261 std::pair<const char *, const char *> Locations
262 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
263
264 if (Locations.first != Predef + MinLen) {
265 // We found the location in the two buffers where there is a
266 // difference. Form source locations to point there (in both
267 // buffers).
268 unsigned Offset = Locations.first - Predef;
269 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
270 .getFileLocWithOffset(Offset);
271 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
272 .getFileLocWithOffset(Offset);
273 } else if (PredefLen > PCHPredefLen) {
274 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
275 .getFileLocWithOffset(MinLen);
276 } else {
277 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
278 .getFileLocWithOffset(MinLen);
279 }
280
281 Diag(Loc1, diag::warn_pch_preprocessor);
282 if (Loc2.isValid())
283 Diag(Loc2, diag::note_predef_in_pch);
284 Diag(diag::note_ignoring_pch) << FileName;
285 return true;
286}
287
Douglas Gregor635f97f2009-04-13 16:31:14 +0000288/// \brief Read the line table in the source manager block.
289/// \returns true if ther was an error.
290static bool ParseLineTable(SourceManager &SourceMgr,
291 llvm::SmallVectorImpl<uint64_t> &Record) {
292 unsigned Idx = 0;
293 LineTableInfo &LineTable = SourceMgr.getLineTable();
294
295 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000296 std::map<int, int> FileIDs;
297 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000298 // Extract the file name
299 unsigned FilenameLen = Record[Idx++];
300 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
301 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000302 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
303 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000304 }
305
306 // Parse the line entries
307 std::vector<LineEntry> Entries;
308 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000309 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000310
311 // Extract the line entries
312 unsigned NumEntries = Record[Idx++];
313 Entries.clear();
314 Entries.reserve(NumEntries);
315 for (unsigned I = 0; I != NumEntries; ++I) {
316 unsigned FileOffset = Record[Idx++];
317 unsigned LineNo = Record[Idx++];
318 int FilenameID = Record[Idx++];
319 SrcMgr::CharacteristicKind FileKind
320 = (SrcMgr::CharacteristicKind)Record[Idx++];
321 unsigned IncludeOffset = Record[Idx++];
322 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
323 FileKind, IncludeOffset));
324 }
325 LineTable.AddEntry(FID, Entries);
326 }
327
328 return false;
329}
330
Douglas Gregorab1cef72009-04-10 03:52:48 +0000331/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000332PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000333 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000334 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
335 Error("Malformed source manager block record");
336 return Failure;
337 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000338
339 SourceManager &SourceMgr = Context.getSourceManager();
340 RecordData Record;
341 while (true) {
342 unsigned Code = Stream.ReadCode();
343 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000344 if (Stream.ReadBlockEnd()) {
345 Error("Error at end of Source Manager block");
346 return Failure;
347 }
348
349 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000350 }
351
352 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
353 // No known subblocks, always skip them.
354 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000355 if (Stream.SkipBlock()) {
356 Error("Malformed block record");
357 return Failure;
358 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000359 continue;
360 }
361
362 if (Code == llvm::bitc::DEFINE_ABBREV) {
363 Stream.ReadAbbrevRecord();
364 continue;
365 }
366
367 // Read a record.
368 const char *BlobStart;
369 unsigned BlobLen;
370 Record.clear();
371 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
372 default: // Default behavior: ignore.
373 break;
374
375 case pch::SM_SLOC_FILE_ENTRY: {
376 // FIXME: We would really like to delay the creation of this
377 // FileEntry until it is actually required, e.g., when producing
378 // a diagnostic with a source location in this file.
379 const FileEntry *File
380 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
381 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000382 FileID ID = SourceMgr.createFileID(File,
383 SourceLocation::getFromRawEncoding(Record[1]),
384 (CharacteristicKind)Record[2]);
385 if (Record[3])
386 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
387 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000388 break;
389 }
390
391 case pch::SM_SLOC_BUFFER_ENTRY: {
392 const char *Name = BlobStart;
393 unsigned Code = Stream.ReadCode();
394 Record.clear();
395 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
396 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000397 llvm::MemoryBuffer *Buffer
398 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
399 BlobStart + BlobLen - 1,
400 Name);
401 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
402
403 if (strcmp(Name, "<built-in>") == 0
404 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
405 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000406 break;
407 }
408
409 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
410 SourceLocation SpellingLoc
411 = SourceLocation::getFromRawEncoding(Record[1]);
412 SourceMgr.createInstantiationLoc(
413 SpellingLoc,
414 SourceLocation::getFromRawEncoding(Record[2]),
415 SourceLocation::getFromRawEncoding(Record[3]),
416 Lexer::MeasureTokenLength(SpellingLoc,
417 SourceMgr));
418 break;
419 }
420
Douglas Gregor635f97f2009-04-13 16:31:14 +0000421 case pch::SM_LINE_TABLE: {
422 if (ParseLineTable(SourceMgr, Record))
423 return Failure;
424 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000425 }
426 }
427}
428
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000429bool PCHReader::ReadPreprocessorBlock() {
430 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
431 return Error("Malformed preprocessor block record");
432
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000433 RecordData Record;
434 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
435 MacroInfo *LastMacro = 0;
436
437 while (true) {
438 unsigned Code = Stream.ReadCode();
439 switch (Code) {
440 case llvm::bitc::END_BLOCK:
441 if (Stream.ReadBlockEnd())
442 return Error("Error at end of preprocessor block");
443 return false;
444
445 case llvm::bitc::ENTER_SUBBLOCK:
446 // No known subblocks, always skip them.
447 Stream.ReadSubBlockID();
448 if (Stream.SkipBlock())
449 return Error("Malformed block record");
450 continue;
451
452 case llvm::bitc::DEFINE_ABBREV:
453 Stream.ReadAbbrevRecord();
454 continue;
455 default: break;
456 }
457
458 // Read a record.
459 Record.clear();
460 pch::PreprocessorRecordTypes RecType =
461 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
462 switch (RecType) {
463 default: // Default behavior: ignore unknown records.
464 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000465 case pch::PP_COUNTER_VALUE:
466 if (!Record.empty())
467 PP.setCounterValue(Record[0]);
468 break;
469
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000470 case pch::PP_MACRO_OBJECT_LIKE:
471 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000472 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
473 if (II == 0)
474 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000475 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
476 bool isUsed = Record[2];
477
478 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
479 MI->setIsUsed(isUsed);
480
481 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
482 // Decode function-like macro info.
483 bool isC99VarArgs = Record[3];
484 bool isGNUVarArgs = Record[4];
485 MacroArgs.clear();
486 unsigned NumArgs = Record[5];
487 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000488 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000489
490 // Install function-like macro info.
491 MI->setIsFunctionLike();
492 if (isC99VarArgs) MI->setIsC99Varargs();
493 if (isGNUVarArgs) MI->setIsGNUVarargs();
494 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
495 PP.getPreprocessorAllocator());
496 }
497
498 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000499 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000500
501 // Remember that we saw this macro last so that we add the tokens that
502 // form its body to it.
503 LastMacro = MI;
504 break;
505 }
506
507 case pch::PP_TOKEN: {
508 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
509 // pretend we didn't see this.
510 if (LastMacro == 0) break;
511
512 Token Tok;
513 Tok.startToken();
514 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
515 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000516 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
517 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000518 Tok.setKind((tok::TokenKind)Record[3]);
519 Tok.setFlag((Token::TokenFlags)Record[4]);
520 LastMacro->AddTokenToBody(Tok);
521 break;
522 }
523 }
524 }
525}
526
Douglas Gregor179cfb12009-04-10 20:39:37 +0000527PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
528 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
529 Error("Malformed block record");
530 return Failure;
531 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000532
Chris Lattner29241862009-04-11 21:15:38 +0000533 uint64_t PreprocessorBlockBit = 0;
534
Douglas Gregorc34897d2009-04-09 22:27:44 +0000535 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000536 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000537 while (!Stream.AtEndOfStream()) {
538 unsigned Code = Stream.ReadCode();
539 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000540 // If we saw the preprocessor block, read it now.
541 if (PreprocessorBlockBit) {
542 uint64_t SavedPos = Stream.GetCurrentBitNo();
543 Stream.JumpToBit(PreprocessorBlockBit);
544 if (ReadPreprocessorBlock()) {
545 Error("Malformed preprocessor block");
546 return Failure;
547 }
548 Stream.JumpToBit(SavedPos);
549 }
550
Douglas Gregor179cfb12009-04-10 20:39:37 +0000551 if (Stream.ReadBlockEnd()) {
552 Error("Error at end of module block");
553 return Failure;
554 }
Chris Lattner29241862009-04-11 21:15:38 +0000555
Douglas Gregor179cfb12009-04-10 20:39:37 +0000556 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000557 }
558
559 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
560 switch (Stream.ReadSubBlockID()) {
561 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
562 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
563 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000564 if (Stream.SkipBlock()) {
565 Error("Malformed block record");
566 return Failure;
567 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000568 break;
569
Chris Lattner29241862009-04-11 21:15:38 +0000570 case pch::PREPROCESSOR_BLOCK_ID:
571 // Skip the preprocessor block for now, but remember where it is. We
572 // want to read it in after the identifier table.
573 if (PreprocessorBlockBit) {
574 Error("Multiple preprocessor blocks found.");
575 return Failure;
576 }
577 PreprocessorBlockBit = Stream.GetCurrentBitNo();
578 if (Stream.SkipBlock()) {
579 Error("Malformed block record");
580 return Failure;
581 }
582 break;
583
Douglas Gregorab1cef72009-04-10 03:52:48 +0000584 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000585 switch (ReadSourceManagerBlock()) {
586 case Success:
587 break;
588
589 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000590 Error("Malformed source manager block");
591 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000592
593 case IgnorePCH:
594 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000595 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000596 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000597 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000598 continue;
599 }
600
601 if (Code == llvm::bitc::DEFINE_ABBREV) {
602 Stream.ReadAbbrevRecord();
603 continue;
604 }
605
606 // Read and process a record.
607 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000608 const char *BlobStart = 0;
609 unsigned BlobLen = 0;
610 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
611 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000612 default: // Default behavior: ignore.
613 break;
614
615 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000616 if (!TypeOffsets.empty()) {
617 Error("Duplicate TYPE_OFFSET record in PCH file");
618 return Failure;
619 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000620 TypeOffsets.swap(Record);
621 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
622 break;
623
624 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000625 if (!DeclOffsets.empty()) {
626 Error("Duplicate DECL_OFFSET record in PCH file");
627 return Failure;
628 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000629 DeclOffsets.swap(Record);
630 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
631 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000632
633 case pch::LANGUAGE_OPTIONS:
634 if (ParseLanguageOptions(Record))
635 return IgnorePCH;
636 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000637
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000638 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000639 std::string TargetTriple(BlobStart, BlobLen);
640 if (TargetTriple != Context.Target.getTargetTriple()) {
641 Diag(diag::warn_pch_target_triple)
642 << TargetTriple << Context.Target.getTargetTriple();
643 Diag(diag::note_ignoring_pch) << FileName;
644 return IgnorePCH;
645 }
646 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000647 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000648
649 case pch::IDENTIFIER_TABLE:
650 IdentifierTable = BlobStart;
651 break;
652
653 case pch::IDENTIFIER_OFFSET:
654 if (!IdentifierData.empty()) {
655 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
656 return Failure;
657 }
658 IdentifierData.swap(Record);
659#ifndef NDEBUG
660 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
661 if ((IdentifierData[I] & 0x01) == 0) {
662 Error("Malformed identifier table in the precompiled header");
663 return Failure;
664 }
665 }
666#endif
667 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000668
669 case pch::EXTERNAL_DEFINITIONS:
670 if (!ExternalDefinitions.empty()) {
671 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
672 return Failure;
673 }
674 ExternalDefinitions.swap(Record);
675 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000676 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000677 }
678
Douglas Gregor179cfb12009-04-10 20:39:37 +0000679 Error("Premature end of bitstream");
680 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000681}
682
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000683PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000684 // Set the PCH file name.
685 this->FileName = FileName;
686
Douglas Gregorc34897d2009-04-09 22:27:44 +0000687 // Open the PCH file.
688 std::string ErrStr;
689 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000690 if (!Buffer) {
691 Error(ErrStr.c_str());
692 return IgnorePCH;
693 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000694
695 // Initialize the stream
696 Stream.init((const unsigned char *)Buffer->getBufferStart(),
697 (const unsigned char *)Buffer->getBufferEnd());
698
699 // Sniff for the signature.
700 if (Stream.Read(8) != 'C' ||
701 Stream.Read(8) != 'P' ||
702 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000703 Stream.Read(8) != 'H') {
704 Error("Not a PCH file");
705 return IgnorePCH;
706 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000707
708 // We expect a number of well-defined blocks, though we don't necessarily
709 // need to understand them all.
710 while (!Stream.AtEndOfStream()) {
711 unsigned Code = Stream.ReadCode();
712
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000713 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
714 Error("Invalid record at top-level");
715 return Failure;
716 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000717
718 unsigned BlockID = Stream.ReadSubBlockID();
719
720 // We only know the PCH subblock ID.
721 switch (BlockID) {
722 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000723 if (Stream.ReadBlockInfoBlock()) {
724 Error("Malformed BlockInfoBlock");
725 return Failure;
726 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000727 break;
728 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000729 switch (ReadPCHBlock()) {
730 case Success:
731 break;
732
733 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000734 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000735
736 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000737 // FIXME: We could consider reading through to the end of this
738 // PCH block, skipping subblocks, to see if there are other
739 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000740 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000741 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000742 break;
743 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000744 if (Stream.SkipBlock()) {
745 Error("Malformed block record");
746 return Failure;
747 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000748 break;
749 }
750 }
751
752 // Load the translation unit declaration
753 ReadDeclRecord(DeclOffsets[0], 0);
754
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000755 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000756}
757
Douglas Gregor179cfb12009-04-10 20:39:37 +0000758/// \brief Parse the record that corresponds to a LangOptions data
759/// structure.
760///
761/// This routine compares the language options used to generate the
762/// PCH file against the language options set for the current
763/// compilation. For each option, we classify differences between the
764/// two compiler states as either "benign" or "important". Benign
765/// differences don't matter, and we accept them without complaint
766/// (and without modifying the language options). Differences between
767/// the states for important options cause the PCH file to be
768/// unusable, so we emit a warning and return true to indicate that
769/// there was an error.
770///
771/// \returns true if the PCH file is unacceptable, false otherwise.
772bool PCHReader::ParseLanguageOptions(
773 const llvm::SmallVectorImpl<uint64_t> &Record) {
774 const LangOptions &LangOpts = Context.getLangOptions();
775#define PARSE_LANGOPT_BENIGN(Option) ++Idx
776#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
777 if (Record[Idx] != LangOpts.Option) { \
778 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
779 Diag(diag::note_ignoring_pch) << FileName; \
780 return true; \
781 } \
782 ++Idx
783
784 unsigned Idx = 0;
785 PARSE_LANGOPT_BENIGN(Trigraphs);
786 PARSE_LANGOPT_BENIGN(BCPLComment);
787 PARSE_LANGOPT_BENIGN(DollarIdents);
788 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
789 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
790 PARSE_LANGOPT_BENIGN(ImplicitInt);
791 PARSE_LANGOPT_BENIGN(Digraphs);
792 PARSE_LANGOPT_BENIGN(HexFloats);
793 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
794 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
795 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
796 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
797 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
798 PARSE_LANGOPT_BENIGN(CXXOperatorName);
799 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
800 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
801 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
802 PARSE_LANGOPT_BENIGN(PascalStrings);
803 PARSE_LANGOPT_BENIGN(Boolean);
804 PARSE_LANGOPT_BENIGN(WritableStrings);
805 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
806 diag::warn_pch_lax_vector_conversions);
807 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
808 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
809 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
810 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
811 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
812 diag::warn_pch_thread_safe_statics);
813 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
814 PARSE_LANGOPT_BENIGN(EmitAllDecls);
815 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
816 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
817 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
818 diag::warn_pch_heinous_extensions);
819 // FIXME: Most of the options below are benign if the macro wasn't
820 // used. Unfortunately, this means that a PCH compiled without
821 // optimization can't be used with optimization turned on, even
822 // though the only thing that changes is whether __OPTIMIZE__ was
823 // defined... but if __OPTIMIZE__ never showed up in the header, it
824 // doesn't matter. We could consider making this some special kind
825 // of check.
826 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
827 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
828 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
829 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
830 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
831 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
832 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
833 Diag(diag::warn_pch_gc_mode)
834 << (unsigned)Record[Idx] << LangOpts.getGCMode();
835 Diag(diag::note_ignoring_pch) << FileName;
836 return true;
837 }
838 ++Idx;
839 PARSE_LANGOPT_BENIGN(getVisibilityMode());
840 PARSE_LANGOPT_BENIGN(InstantiationDepth);
841#undef PARSE_LANGOPT_IRRELEVANT
842#undef PARSE_LANGOPT_BENIGN
843
844 return false;
845}
846
Douglas Gregorc34897d2009-04-09 22:27:44 +0000847/// \brief Read and return the type at the given offset.
848///
849/// This routine actually reads the record corresponding to the type
850/// at the given offset in the bitstream. It is a helper routine for
851/// GetType, which deals with reading type IDs.
852QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
853 Stream.JumpToBit(Offset);
854 RecordData Record;
855 unsigned Code = Stream.ReadCode();
856 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000857 case pch::TYPE_EXT_QUAL:
858 // FIXME: Deserialize ExtQualType
859 assert(false && "Cannot deserialize qualified types yet");
860 return QualType();
861
Douglas Gregorc34897d2009-04-09 22:27:44 +0000862 case pch::TYPE_FIXED_WIDTH_INT: {
863 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
864 return Context.getFixedWidthIntType(Record[0], Record[1]);
865 }
866
867 case pch::TYPE_COMPLEX: {
868 assert(Record.size() == 1 && "Incorrect encoding of complex type");
869 QualType ElemType = GetType(Record[0]);
870 return Context.getComplexType(ElemType);
871 }
872
873 case pch::TYPE_POINTER: {
874 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
875 QualType PointeeType = GetType(Record[0]);
876 return Context.getPointerType(PointeeType);
877 }
878
879 case pch::TYPE_BLOCK_POINTER: {
880 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
881 QualType PointeeType = GetType(Record[0]);
882 return Context.getBlockPointerType(PointeeType);
883 }
884
885 case pch::TYPE_LVALUE_REFERENCE: {
886 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
887 QualType PointeeType = GetType(Record[0]);
888 return Context.getLValueReferenceType(PointeeType);
889 }
890
891 case pch::TYPE_RVALUE_REFERENCE: {
892 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
893 QualType PointeeType = GetType(Record[0]);
894 return Context.getRValueReferenceType(PointeeType);
895 }
896
897 case pch::TYPE_MEMBER_POINTER: {
898 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
899 QualType PointeeType = GetType(Record[0]);
900 QualType ClassType = GetType(Record[1]);
901 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
902 }
903
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000904 case pch::TYPE_CONSTANT_ARRAY: {
905 QualType ElementType = GetType(Record[0]);
906 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
907 unsigned IndexTypeQuals = Record[2];
908 unsigned Idx = 3;
909 llvm::APInt Size = ReadAPInt(Record, Idx);
910 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
911 }
912
913 case pch::TYPE_INCOMPLETE_ARRAY: {
914 QualType ElementType = GetType(Record[0]);
915 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
916 unsigned IndexTypeQuals = Record[2];
917 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
918 }
919
920 case pch::TYPE_VARIABLE_ARRAY: {
921 // FIXME: implement this
922 assert(false && "Unable to de-serialize variable-length array type");
923 return QualType();
924 }
925
926 case pch::TYPE_VECTOR: {
927 if (Record.size() != 2) {
928 Error("Incorrect encoding of vector type in PCH file");
929 return QualType();
930 }
931
932 QualType ElementType = GetType(Record[0]);
933 unsigned NumElements = Record[1];
934 return Context.getVectorType(ElementType, NumElements);
935 }
936
937 case pch::TYPE_EXT_VECTOR: {
938 if (Record.size() != 2) {
939 Error("Incorrect encoding of extended vector type in PCH file");
940 return QualType();
941 }
942
943 QualType ElementType = GetType(Record[0]);
944 unsigned NumElements = Record[1];
945 return Context.getExtVectorType(ElementType, NumElements);
946 }
947
948 case pch::TYPE_FUNCTION_NO_PROTO: {
949 if (Record.size() != 1) {
950 Error("Incorrect encoding of no-proto function type");
951 return QualType();
952 }
953 QualType ResultType = GetType(Record[0]);
954 return Context.getFunctionNoProtoType(ResultType);
955 }
956
957 case pch::TYPE_FUNCTION_PROTO: {
958 QualType ResultType = GetType(Record[0]);
959 unsigned Idx = 1;
960 unsigned NumParams = Record[Idx++];
961 llvm::SmallVector<QualType, 16> ParamTypes;
962 for (unsigned I = 0; I != NumParams; ++I)
963 ParamTypes.push_back(GetType(Record[Idx++]));
964 bool isVariadic = Record[Idx++];
965 unsigned Quals = Record[Idx++];
966 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
967 isVariadic, Quals);
968 }
969
970 case pch::TYPE_TYPEDEF:
971 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
972 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
973
974 case pch::TYPE_TYPEOF_EXPR:
975 // FIXME: Deserialize TypeOfExprType
976 assert(false && "Cannot de-serialize typeof(expr) from a PCH file");
977 return QualType();
978
979 case pch::TYPE_TYPEOF: {
980 if (Record.size() != 1) {
981 Error("Incorrect encoding of typeof(type) in PCH file");
982 return QualType();
983 }
984 QualType UnderlyingType = GetType(Record[0]);
985 return Context.getTypeOfType(UnderlyingType);
986 }
987
988 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +0000989 assert(Record.size() == 1 && "Incorrect encoding of record type");
990 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000991
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000992 case pch::TYPE_ENUM:
993 assert(Record.size() == 1 && "Incorrect encoding of enum type");
994 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
995
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000996 case pch::TYPE_OBJC_INTERFACE:
997 // FIXME: Deserialize ObjCInterfaceType
998 assert(false && "Cannot de-serialize ObjC interface types yet");
999 return QualType();
1000
1001 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1002 // FIXME: Deserialize ObjCQualifiedInterfaceType
1003 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1004 return QualType();
1005
1006 case pch::TYPE_OBJC_QUALIFIED_ID:
1007 // FIXME: Deserialize ObjCQualifiedIdType
1008 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1009 return QualType();
1010
1011 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1012 // FIXME: Deserialize ObjCQualifiedClassType
1013 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1014 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001015 }
1016
1017 // Suppress a GCC warning
1018 return QualType();
1019}
1020
1021/// \brief Note that we have loaded the declaration with the given
1022/// Index.
1023///
1024/// This routine notes that this declaration has already been loaded,
1025/// so that future GetDecl calls will return this declaration rather
1026/// than trying to load a new declaration.
1027inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1028 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1029 DeclAlreadyLoaded[Index] = true;
1030 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1031}
1032
1033/// \brief Read the declaration at the given offset from the PCH file.
1034Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
1035 Decl *D = 0;
1036 Stream.JumpToBit(Offset);
1037 RecordData Record;
1038 unsigned Code = Stream.ReadCode();
1039 unsigned Idx = 0;
1040 PCHDeclReader Reader(*this, Record, Idx);
1041 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1042 case pch::DECL_TRANSLATION_UNIT:
1043 assert(Index == 0 && "Translation unit must be at index 0");
1044 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1045 D = Context.getTranslationUnitDecl();
1046 LoadedDecl(Index, D);
1047 break;
1048
1049 case pch::DECL_TYPEDEF: {
1050 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1051 0, QualType());
1052 LoadedDecl(Index, Typedef);
1053 Reader.VisitTypedefDecl(Typedef);
1054 D = Typedef;
1055 break;
1056 }
1057
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001058 case pch::DECL_ENUM: {
1059 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1060 LoadedDecl(Index, Enum);
1061 Reader.VisitEnumDecl(Enum);
1062 D = Enum;
1063 break;
1064 }
1065
Douglas Gregor982365e2009-04-13 21:20:57 +00001066 case pch::DECL_RECORD: {
1067 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1068 0, SourceLocation(), 0, 0);
1069 LoadedDecl(Index, Record);
1070 Reader.VisitRecordDecl(Record);
1071 D = Record;
1072 break;
1073 }
1074
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001075 case pch::DECL_ENUM_CONSTANT: {
1076 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1077 SourceLocation(), 0,
1078 QualType(), 0,
1079 llvm::APSInt());
1080 LoadedDecl(Index, ECD);
1081 Reader.VisitEnumConstantDecl(ECD);
1082 D = ECD;
1083 break;
1084 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001085
1086 case pch::DECL_FUNCTION: {
1087 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1088 DeclarationName(),
1089 QualType());
1090 LoadedDecl(Index, Function);
1091 Reader.VisitFunctionDecl(Function);
1092 D = Function;
1093 break;
1094 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001095
Douglas Gregor982365e2009-04-13 21:20:57 +00001096 case pch::DECL_FIELD: {
1097 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1098 QualType(), 0, false);
1099 LoadedDecl(Index, Field);
1100 Reader.VisitFieldDecl(Field);
1101 D = Field;
1102 break;
1103 }
1104
Douglas Gregorc34897d2009-04-09 22:27:44 +00001105 case pch::DECL_VAR: {
1106 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1107 VarDecl::None, SourceLocation());
1108 LoadedDecl(Index, Var);
1109 Reader.VisitVarDecl(Var);
1110 D = Var;
1111 break;
1112 }
1113
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001114 case pch::DECL_PARM_VAR: {
1115 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1116 QualType(), VarDecl::None, 0);
1117 LoadedDecl(Index, Parm);
1118 Reader.VisitParmVarDecl(Parm);
1119 D = Parm;
1120 break;
1121 }
1122
1123 case pch::DECL_ORIGINAL_PARM_VAR: {
1124 OriginalParmVarDecl *Parm
1125 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1126 QualType(), QualType(), VarDecl::None,
1127 0);
1128 LoadedDecl(Index, Parm);
1129 Reader.VisitOriginalParmVarDecl(Parm);
1130 D = Parm;
1131 break;
1132 }
1133
Douglas Gregor2a491792009-04-13 22:49:25 +00001134 case pch::DECL_FILE_SCOPE_ASM: {
1135 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1136 SourceLocation(), 0);
1137 LoadedDecl(Index, Asm);
1138 Reader.VisitFileScopeAsmDecl(Asm);
1139 D = Asm;
1140 break;
1141 }
1142
1143 case pch::DECL_BLOCK: {
1144 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1145 LoadedDecl(Index, Block);
1146 Reader.VisitBlockDecl(Block);
1147 D = Block;
1148 break;
1149 }
1150
Douglas Gregorc34897d2009-04-09 22:27:44 +00001151 default:
1152 assert(false && "Cannot de-serialize this kind of declaration");
1153 break;
1154 }
1155
1156 // If this declaration is also a declaration context, get the
1157 // offsets for its tables of lexical and visible declarations.
1158 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1159 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1160 if (Offsets.first || Offsets.second) {
1161 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1162 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1163 DeclContextOffsets[DC] = Offsets;
1164 }
1165 }
1166 assert(Idx == Record.size());
1167
1168 return D;
1169}
1170
Douglas Gregorac8f2802009-04-10 17:25:41 +00001171QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001172 unsigned Quals = ID & 0x07;
1173 unsigned Index = ID >> 3;
1174
1175 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1176 QualType T;
1177 switch ((pch::PredefinedTypeIDs)Index) {
1178 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1179 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1180 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1181
1182 case pch::PREDEF_TYPE_CHAR_U_ID:
1183 case pch::PREDEF_TYPE_CHAR_S_ID:
1184 // FIXME: Check that the signedness of CharTy is correct!
1185 T = Context.CharTy;
1186 break;
1187
1188 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1189 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1190 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1191 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1192 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1193 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1194 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1195 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1196 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1197 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1198 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1199 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1200 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1201 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1202 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1203 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1204 }
1205
1206 assert(!T.isNull() && "Unknown predefined type");
1207 return T.getQualifiedType(Quals);
1208 }
1209
1210 Index -= pch::NUM_PREDEF_TYPE_IDS;
1211 if (!TypeAlreadyLoaded[Index]) {
1212 // Load the type from the PCH file.
1213 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1214 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1215 TypeAlreadyLoaded[Index] = true;
1216 }
1217
1218 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1219}
1220
Douglas Gregorac8f2802009-04-10 17:25:41 +00001221Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001222 if (ID == 0)
1223 return 0;
1224
1225 unsigned Index = ID - 1;
1226 if (DeclAlreadyLoaded[Index])
1227 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1228
1229 // Load the declaration from the PCH file.
1230 return ReadDeclRecord(DeclOffsets[Index], Index);
1231}
1232
1233bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001234 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001235 assert(DC->hasExternalLexicalStorage() &&
1236 "DeclContext has no lexical decls in storage");
1237 uint64_t Offset = DeclContextOffsets[DC].first;
1238 assert(Offset && "DeclContext has no lexical decls in storage");
1239
1240 // Load the record containing all of the declarations lexically in
1241 // this context.
1242 Stream.JumpToBit(Offset);
1243 RecordData Record;
1244 unsigned Code = Stream.ReadCode();
1245 unsigned RecCode = Stream.ReadRecord(Code, Record);
1246 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1247
1248 // Load all of the declaration IDs
1249 Decls.clear();
1250 Decls.insert(Decls.end(), Record.begin(), Record.end());
1251 return false;
1252}
1253
1254bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1255 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1256 assert(DC->hasExternalVisibleStorage() &&
1257 "DeclContext has no visible decls in storage");
1258 uint64_t Offset = DeclContextOffsets[DC].second;
1259 assert(Offset && "DeclContext has no visible decls in storage");
1260
1261 // Load the record containing all of the declarations visible in
1262 // this context.
1263 Stream.JumpToBit(Offset);
1264 RecordData Record;
1265 unsigned Code = Stream.ReadCode();
1266 unsigned RecCode = Stream.ReadRecord(Code, Record);
1267 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1268 if (Record.size() == 0)
1269 return false;
1270
1271 Decls.clear();
1272
1273 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001274 while (Idx < Record.size()) {
1275 Decls.push_back(VisibleDeclaration());
1276 Decls.back().Name = ReadDeclarationName(Record, Idx);
1277
Douglas Gregorc34897d2009-04-09 22:27:44 +00001278 unsigned Size = Record[Idx++];
1279 llvm::SmallVector<unsigned, 4> & LoadedDecls
1280 = Decls.back().Declarations;
1281 LoadedDecls.reserve(Size);
1282 for (unsigned I = 0; I < Size; ++I)
1283 LoadedDecls.push_back(Record[Idx++]);
1284 }
1285
1286 return false;
1287}
1288
Douglas Gregor631f6c62009-04-14 00:24:19 +00001289void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1290 if (!Consumer)
1291 return;
1292
1293 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1294 Decl *D = GetDecl(ExternalDefinitions[I]);
1295 DeclGroupRef DG(D);
1296 Consumer->HandleTopLevelDecl(DG);
1297 }
1298}
1299
Douglas Gregorc34897d2009-04-09 22:27:44 +00001300void PCHReader::PrintStats() {
1301 std::fprintf(stderr, "*** PCH Statistics:\n");
1302
1303 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1304 TypeAlreadyLoaded.end(),
1305 true);
1306 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1307 DeclAlreadyLoaded.end(),
1308 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001309 unsigned NumIdentifiersLoaded = 0;
1310 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1311 if ((IdentifierData[I] & 0x01) == 0)
1312 ++NumIdentifiersLoaded;
1313 }
1314
Douglas Gregorc34897d2009-04-09 22:27:44 +00001315 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1316 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001317 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001318 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1319 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001320 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1321 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1322 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1323 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001324 std::fprintf(stderr, "\n");
1325}
1326
Chris Lattner29241862009-04-11 21:15:38 +00001327IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001328 if (ID == 0)
1329 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001330
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001331 if (!IdentifierTable || IdentifierData.empty()) {
1332 Error("No identifier table in PCH file");
1333 return 0;
1334 }
Chris Lattner29241862009-04-11 21:15:38 +00001335
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001336 if (IdentifierData[ID - 1] & 0x01) {
1337 uint64_t Offset = IdentifierData[ID - 1];
1338 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001339 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001340 }
Chris Lattner29241862009-04-11 21:15:38 +00001341
1342 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001343}
1344
1345DeclarationName
1346PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1347 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1348 switch (Kind) {
1349 case DeclarationName::Identifier:
1350 return DeclarationName(GetIdentifierInfo(Record, Idx));
1351
1352 case DeclarationName::ObjCZeroArgSelector:
1353 case DeclarationName::ObjCOneArgSelector:
1354 case DeclarationName::ObjCMultiArgSelector:
1355 assert(false && "Unable to de-serialize Objective-C selectors");
1356 break;
1357
1358 case DeclarationName::CXXConstructorName:
1359 return Context.DeclarationNames.getCXXConstructorName(
1360 GetType(Record[Idx++]));
1361
1362 case DeclarationName::CXXDestructorName:
1363 return Context.DeclarationNames.getCXXDestructorName(
1364 GetType(Record[Idx++]));
1365
1366 case DeclarationName::CXXConversionFunctionName:
1367 return Context.DeclarationNames.getCXXConversionFunctionName(
1368 GetType(Record[Idx++]));
1369
1370 case DeclarationName::CXXOperatorName:
1371 return Context.DeclarationNames.getCXXOperatorName(
1372 (OverloadedOperatorKind)Record[Idx++]);
1373
1374 case DeclarationName::CXXUsingDirective:
1375 return DeclarationName::getUsingDirectiveName();
1376 }
1377
1378 // Required to silence GCC warning
1379 return DeclarationName();
1380}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001381
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001382/// \brief Read an integral value
1383llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1384 unsigned BitWidth = Record[Idx++];
1385 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1386 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1387 Idx += NumWords;
1388 return Result;
1389}
1390
1391/// \brief Read a signed integral value
1392llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1393 bool isUnsigned = Record[Idx++];
1394 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1395}
1396
Douglas Gregor179cfb12009-04-10 20:39:37 +00001397DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001398 return Diag(SourceLocation(), DiagID);
1399}
1400
1401DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1402 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001403 Context.getSourceManager()),
1404 DiagID);
1405}