blob: ad3c2e55a9906457cd19e3b5772eb7f1fd919339 [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 Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/StmtVisitor.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000025#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000026#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000028#include "llvm/Bitcode/BitstreamReader.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include <algorithm>
32#include <cstdio>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Declaration deserialization
38//===----------------------------------------------------------------------===//
39namespace {
40 class VISIBILITY_HIDDEN PCHDeclReader {
41 PCHReader &Reader;
42 const PCHReader::RecordData &Record;
43 unsigned &Idx;
44
45 public:
46 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
47 unsigned &Idx)
48 : Reader(Reader), Record(Record), Idx(Idx) { }
49
50 void VisitDecl(Decl *D);
51 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
52 void VisitNamedDecl(NamedDecl *ND);
53 void VisitTypeDecl(TypeDecl *TD);
54 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000055 void VisitTagDecl(TagDecl *TD);
56 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000057 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000058 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000059 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000060 void VisitFunctionDecl(FunctionDecl *FD);
Douglas Gregor982365e2009-04-13 21:20:57 +000061 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000062 void VisitVarDecl(VarDecl *VD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000063 void VisitParmVarDecl(ParmVarDecl *PD);
64 void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD);
Douglas Gregor2a491792009-04-13 22:49:25 +000065 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
66 void VisitBlockDecl(BlockDecl *BD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000067 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
68 };
69}
70
71void PCHDeclReader::VisitDecl(Decl *D) {
72 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
73 D->setLexicalDeclContext(
74 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
75 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
76 D->setInvalidDecl(Record[Idx++]);
77 // FIXME: hasAttrs
78 D->setImplicit(Record[Idx++]);
79 D->setAccess((AccessSpecifier)Record[Idx++]);
80}
81
82void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
83 VisitDecl(TU);
84}
85
86void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
87 VisitDecl(ND);
88 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
89}
90
91void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
92 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000093 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
94}
95
96void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000097 // Note that we cannot use VisitTypeDecl here, because we need to
98 // set the underlying type of the typedef *before* we try to read
99 // the type associated with the TypedefDecl.
100 VisitNamedDecl(TD);
101 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
102 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
103 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000104}
105
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000106void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
107 VisitTypeDecl(TD);
108 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
109 TD->setDefinition(Record[Idx++]);
110 TD->setTypedefForAnonDecl(
111 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
112}
113
114void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
115 VisitTagDecl(ED);
116 ED->setIntegerType(Reader.GetType(Record[Idx++]));
117}
118
Douglas Gregor982365e2009-04-13 21:20:57 +0000119void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
120 VisitTagDecl(RD);
121 RD->setHasFlexibleArrayMember(Record[Idx++]);
122 RD->setAnonymousStructOrUnion(Record[Idx++]);
123}
124
Douglas Gregorc34897d2009-04-09 22:27:44 +0000125void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
126 VisitNamedDecl(VD);
127 VD->setType(Reader.GetType(Record[Idx++]));
128}
129
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000130void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
131 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000132 if (Record[Idx++])
133 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000134 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
135}
136
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000137void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
138 VisitValueDecl(FD);
139 // FIXME: function body
140 FD->setPreviousDeclaration(
141 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
142 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
143 FD->setInline(Record[Idx++]);
144 FD->setVirtual(Record[Idx++]);
145 FD->setPure(Record[Idx++]);
146 FD->setInheritedPrototype(Record[Idx++]);
147 FD->setHasPrototype(Record[Idx++]);
148 FD->setDeleted(Record[Idx++]);
149 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
150 unsigned NumParams = Record[Idx++];
151 llvm::SmallVector<ParmVarDecl *, 16> Params;
152 Params.reserve(NumParams);
153 for (unsigned I = 0; I != NumParams; ++I)
154 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
155 FD->setParams(Reader.getContext(), &Params[0], NumParams);
156}
157
Douglas Gregor982365e2009-04-13 21:20:57 +0000158void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
159 VisitValueDecl(FD);
160 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000161 if (Record[Idx++])
162 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000163}
164
Douglas Gregorc34897d2009-04-09 22:27:44 +0000165void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
166 VisitValueDecl(VD);
167 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
168 VD->setThreadSpecified(Record[Idx++]);
169 VD->setCXXDirectInitializer(Record[Idx++]);
170 VD->setDeclaredInCondition(Record[Idx++]);
171 VD->setPreviousDeclaration(
172 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
173 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000174 if (Record[Idx++])
175 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000176}
177
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000178void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
179 VisitVarDecl(PD);
180 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
181 // FIXME: default argument
182}
183
184void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
185 VisitParmVarDecl(PD);
186 PD->setOriginalType(Reader.GetType(Record[Idx++]));
187}
188
Douglas Gregor2a491792009-04-13 22:49:25 +0000189void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
190 VisitDecl(AD);
191 // FIXME: read asm string
192}
193
194void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
195 VisitDecl(BD);
196 unsigned NumParams = Record[Idx++];
197 llvm::SmallVector<ParmVarDecl *, 16> Params;
198 Params.reserve(NumParams);
199 for (unsigned I = 0; I != NumParams; ++I)
200 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
201 BD->setParams(Reader.getContext(), &Params[0], NumParams);
202}
203
Douglas Gregorc34897d2009-04-09 22:27:44 +0000204std::pair<uint64_t, uint64_t>
205PCHDeclReader::VisitDeclContext(DeclContext *DC) {
206 uint64_t LexicalOffset = Record[Idx++];
207 uint64_t VisibleOffset = 0;
208 if (DC->getPrimaryContext() == DC)
209 VisibleOffset = Record[Idx++];
210 return std::make_pair(LexicalOffset, VisibleOffset);
211}
212
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000213//===----------------------------------------------------------------------===//
214// Statement/expression deserialization
215//===----------------------------------------------------------------------===//
216namespace {
217 class VISIBILITY_HIDDEN PCHStmtReader
Douglas Gregora151ba42009-04-14 23:32:43 +0000218 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000219 PCHReader &Reader;
220 const PCHReader::RecordData &Record;
221 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000222 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000223
224 public:
225 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000226 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
227 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000228
Douglas Gregora151ba42009-04-14 23:32:43 +0000229 // Each of the Visit* functions reads in part of the expression
230 // from the given record and the current expression stack, then
231 // return the total number of operands that it read from the
232 // expression stack.
233
234 unsigned VisitExpr(Expr *E);
235 unsigned VisitPredefinedExpr(PredefinedExpr *E);
236 unsigned VisitDeclRefExpr(DeclRefExpr *E);
237 unsigned VisitIntegerLiteral(IntegerLiteral *E);
238 unsigned VisitFloatingLiteral(FloatingLiteral *E);
239 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000240 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000241 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000242 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000243 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000244 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
245 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000246 };
247}
248
Douglas Gregora151ba42009-04-14 23:32:43 +0000249unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000250 E->setType(Reader.GetType(Record[Idx++]));
251 E->setTypeDependent(Record[Idx++]);
252 E->setValueDependent(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000253 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000254}
255
Douglas Gregora151ba42009-04-14 23:32:43 +0000256unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000257 VisitExpr(E);
258 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
259 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000260 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000261}
262
Douglas Gregora151ba42009-04-14 23:32:43 +0000263unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000264 VisitExpr(E);
265 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
266 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000267 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000268}
269
Douglas Gregora151ba42009-04-14 23:32:43 +0000270unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000271 VisitExpr(E);
272 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
273 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000274 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000275}
276
Douglas Gregora151ba42009-04-14 23:32:43 +0000277unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000278 VisitExpr(E);
279 E->setValue(Reader.ReadAPFloat(Record, Idx));
280 E->setExact(Record[Idx++]);
281 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000282 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000283}
284
Douglas Gregora151ba42009-04-14 23:32:43 +0000285unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000286 VisitExpr(E);
287 E->setValue(Record[Idx++]);
288 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
289 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000290 return 0;
291}
292
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000293unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
294 VisitExpr(E);
295 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
296 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
297 E->setSubExpr(ExprStack.back());
298 return 1;
299}
300
Douglas Gregora151ba42009-04-14 23:32:43 +0000301unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
302 VisitExpr(E);
303 E->setSubExpr(ExprStack.back());
304 return 1;
305}
306
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000307unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
308 VisitExpr(E);
309 E->setLHS(ExprStack.end()[-2]);
310 E->setRHS(ExprStack.end()[-1]);
311 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
312 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
313 return 2;
314}
315
Douglas Gregora151ba42009-04-14 23:32:43 +0000316unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
317 VisitCastExpr(E);
318 E->setLvalueCast(Record[Idx++]);
319 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000320}
321
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000322unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
323 VisitCastExpr(E);
324 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
325 return 1;
326}
327
328unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
329 VisitExplicitCastExpr(E);
330 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
331 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
332 return 1;
333}
334
Douglas Gregorc34897d2009-04-09 22:27:44 +0000335// FIXME: use the diagnostics machinery
336static bool Error(const char *Str) {
337 std::fprintf(stderr, "%s\n", Str);
338 return true;
339}
340
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000341/// \brief Check the contents of the predefines buffer against the
342/// contents of the predefines buffer used to build the PCH file.
343///
344/// The contents of the two predefines buffers should be the same. If
345/// not, then some command-line option changed the preprocessor state
346/// and we must reject the PCH file.
347///
348/// \param PCHPredef The start of the predefines buffer in the PCH
349/// file.
350///
351/// \param PCHPredefLen The length of the predefines buffer in the PCH
352/// file.
353///
354/// \param PCHBufferID The FileID for the PCH predefines buffer.
355///
356/// \returns true if there was a mismatch (in which case the PCH file
357/// should be ignored), or false otherwise.
358bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
359 unsigned PCHPredefLen,
360 FileID PCHBufferID) {
361 const char *Predef = PP.getPredefines().c_str();
362 unsigned PredefLen = PP.getPredefines().size();
363
364 // If the two predefines buffers compare equal, we're done!.
365 if (PredefLen == PCHPredefLen &&
366 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
367 return false;
368
369 // The predefines buffers are different. Produce a reasonable
370 // diagnostic showing where they are different.
371
372 // The source locations (potentially in the two different predefines
373 // buffers)
374 SourceLocation Loc1, Loc2;
375 SourceManager &SourceMgr = PP.getSourceManager();
376
377 // Create a source buffer for our predefines string, so
378 // that we can build a diagnostic that points into that
379 // source buffer.
380 FileID BufferID;
381 if (Predef && Predef[0]) {
382 llvm::MemoryBuffer *Buffer
383 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
384 "<built-in>");
385 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
386 }
387
388 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
389 std::pair<const char *, const char *> Locations
390 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
391
392 if (Locations.first != Predef + MinLen) {
393 // We found the location in the two buffers where there is a
394 // difference. Form source locations to point there (in both
395 // buffers).
396 unsigned Offset = Locations.first - Predef;
397 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
398 .getFileLocWithOffset(Offset);
399 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
400 .getFileLocWithOffset(Offset);
401 } else if (PredefLen > PCHPredefLen) {
402 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
403 .getFileLocWithOffset(MinLen);
404 } else {
405 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
406 .getFileLocWithOffset(MinLen);
407 }
408
409 Diag(Loc1, diag::warn_pch_preprocessor);
410 if (Loc2.isValid())
411 Diag(Loc2, diag::note_predef_in_pch);
412 Diag(diag::note_ignoring_pch) << FileName;
413 return true;
414}
415
Douglas Gregor635f97f2009-04-13 16:31:14 +0000416/// \brief Read the line table in the source manager block.
417/// \returns true if ther was an error.
418static bool ParseLineTable(SourceManager &SourceMgr,
419 llvm::SmallVectorImpl<uint64_t> &Record) {
420 unsigned Idx = 0;
421 LineTableInfo &LineTable = SourceMgr.getLineTable();
422
423 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000424 std::map<int, int> FileIDs;
425 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000426 // Extract the file name
427 unsigned FilenameLen = Record[Idx++];
428 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
429 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000430 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
431 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000432 }
433
434 // Parse the line entries
435 std::vector<LineEntry> Entries;
436 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000437 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000438
439 // Extract the line entries
440 unsigned NumEntries = Record[Idx++];
441 Entries.clear();
442 Entries.reserve(NumEntries);
443 for (unsigned I = 0; I != NumEntries; ++I) {
444 unsigned FileOffset = Record[Idx++];
445 unsigned LineNo = Record[Idx++];
446 int FilenameID = Record[Idx++];
447 SrcMgr::CharacteristicKind FileKind
448 = (SrcMgr::CharacteristicKind)Record[Idx++];
449 unsigned IncludeOffset = Record[Idx++];
450 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
451 FileKind, IncludeOffset));
452 }
453 LineTable.AddEntry(FID, Entries);
454 }
455
456 return false;
457}
458
Douglas Gregorab1cef72009-04-10 03:52:48 +0000459/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000460PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000461 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000462 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
463 Error("Malformed source manager block record");
464 return Failure;
465 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000466
467 SourceManager &SourceMgr = Context.getSourceManager();
468 RecordData Record;
469 while (true) {
470 unsigned Code = Stream.ReadCode();
471 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000472 if (Stream.ReadBlockEnd()) {
473 Error("Error at end of Source Manager block");
474 return Failure;
475 }
476
477 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000478 }
479
480 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
481 // No known subblocks, always skip them.
482 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000483 if (Stream.SkipBlock()) {
484 Error("Malformed block record");
485 return Failure;
486 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000487 continue;
488 }
489
490 if (Code == llvm::bitc::DEFINE_ABBREV) {
491 Stream.ReadAbbrevRecord();
492 continue;
493 }
494
495 // Read a record.
496 const char *BlobStart;
497 unsigned BlobLen;
498 Record.clear();
499 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
500 default: // Default behavior: ignore.
501 break;
502
503 case pch::SM_SLOC_FILE_ENTRY: {
504 // FIXME: We would really like to delay the creation of this
505 // FileEntry until it is actually required, e.g., when producing
506 // a diagnostic with a source location in this file.
507 const FileEntry *File
508 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
509 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000510 FileID ID = SourceMgr.createFileID(File,
511 SourceLocation::getFromRawEncoding(Record[1]),
512 (CharacteristicKind)Record[2]);
513 if (Record[3])
514 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
515 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000516 break;
517 }
518
519 case pch::SM_SLOC_BUFFER_ENTRY: {
520 const char *Name = BlobStart;
521 unsigned Code = Stream.ReadCode();
522 Record.clear();
523 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
524 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000525 llvm::MemoryBuffer *Buffer
526 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
527 BlobStart + BlobLen - 1,
528 Name);
529 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
530
531 if (strcmp(Name, "<built-in>") == 0
532 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
533 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000534 break;
535 }
536
537 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
538 SourceLocation SpellingLoc
539 = SourceLocation::getFromRawEncoding(Record[1]);
540 SourceMgr.createInstantiationLoc(
541 SpellingLoc,
542 SourceLocation::getFromRawEncoding(Record[2]),
543 SourceLocation::getFromRawEncoding(Record[3]),
544 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000545 SourceMgr,
546 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000547 break;
548 }
549
Chris Lattnere1be6022009-04-14 23:22:57 +0000550 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000551 if (ParseLineTable(SourceMgr, Record))
552 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000553 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000554 }
555 }
556}
557
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000558bool PCHReader::ReadPreprocessorBlock() {
559 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
560 return Error("Malformed preprocessor block record");
561
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000562 RecordData Record;
563 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
564 MacroInfo *LastMacro = 0;
565
566 while (true) {
567 unsigned Code = Stream.ReadCode();
568 switch (Code) {
569 case llvm::bitc::END_BLOCK:
570 if (Stream.ReadBlockEnd())
571 return Error("Error at end of preprocessor block");
572 return false;
573
574 case llvm::bitc::ENTER_SUBBLOCK:
575 // No known subblocks, always skip them.
576 Stream.ReadSubBlockID();
577 if (Stream.SkipBlock())
578 return Error("Malformed block record");
579 continue;
580
581 case llvm::bitc::DEFINE_ABBREV:
582 Stream.ReadAbbrevRecord();
583 continue;
584 default: break;
585 }
586
587 // Read a record.
588 Record.clear();
589 pch::PreprocessorRecordTypes RecType =
590 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
591 switch (RecType) {
592 default: // Default behavior: ignore unknown records.
593 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000594 case pch::PP_COUNTER_VALUE:
595 if (!Record.empty())
596 PP.setCounterValue(Record[0]);
597 break;
598
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000599 case pch::PP_MACRO_OBJECT_LIKE:
600 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000601 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
602 if (II == 0)
603 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000604 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
605 bool isUsed = Record[2];
606
607 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
608 MI->setIsUsed(isUsed);
609
610 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
611 // Decode function-like macro info.
612 bool isC99VarArgs = Record[3];
613 bool isGNUVarArgs = Record[4];
614 MacroArgs.clear();
615 unsigned NumArgs = Record[5];
616 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000617 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000618
619 // Install function-like macro info.
620 MI->setIsFunctionLike();
621 if (isC99VarArgs) MI->setIsC99Varargs();
622 if (isGNUVarArgs) MI->setIsGNUVarargs();
623 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
624 PP.getPreprocessorAllocator());
625 }
626
627 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000628 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000629
630 // Remember that we saw this macro last so that we add the tokens that
631 // form its body to it.
632 LastMacro = MI;
633 break;
634 }
635
636 case pch::PP_TOKEN: {
637 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
638 // pretend we didn't see this.
639 if (LastMacro == 0) break;
640
641 Token Tok;
642 Tok.startToken();
643 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
644 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000645 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
646 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000647 Tok.setKind((tok::TokenKind)Record[3]);
648 Tok.setFlag((Token::TokenFlags)Record[4]);
649 LastMacro->AddTokenToBody(Tok);
650 break;
651 }
652 }
653 }
654}
655
Douglas Gregor179cfb12009-04-10 20:39:37 +0000656PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
657 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
658 Error("Malformed block record");
659 return Failure;
660 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000661
Chris Lattner29241862009-04-11 21:15:38 +0000662 uint64_t PreprocessorBlockBit = 0;
663
Douglas Gregorc34897d2009-04-09 22:27:44 +0000664 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000665 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000666 while (!Stream.AtEndOfStream()) {
667 unsigned Code = Stream.ReadCode();
668 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000669 // If we saw the preprocessor block, read it now.
670 if (PreprocessorBlockBit) {
671 uint64_t SavedPos = Stream.GetCurrentBitNo();
672 Stream.JumpToBit(PreprocessorBlockBit);
673 if (ReadPreprocessorBlock()) {
674 Error("Malformed preprocessor block");
675 return Failure;
676 }
677 Stream.JumpToBit(SavedPos);
678 }
679
Douglas Gregor179cfb12009-04-10 20:39:37 +0000680 if (Stream.ReadBlockEnd()) {
681 Error("Error at end of module block");
682 return Failure;
683 }
Chris Lattner29241862009-04-11 21:15:38 +0000684
Douglas Gregor179cfb12009-04-10 20:39:37 +0000685 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000686 }
687
688 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
689 switch (Stream.ReadSubBlockID()) {
690 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
691 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
692 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000693 if (Stream.SkipBlock()) {
694 Error("Malformed block record");
695 return Failure;
696 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000697 break;
698
Chris Lattner29241862009-04-11 21:15:38 +0000699 case pch::PREPROCESSOR_BLOCK_ID:
700 // Skip the preprocessor block for now, but remember where it is. We
701 // want to read it in after the identifier table.
702 if (PreprocessorBlockBit) {
703 Error("Multiple preprocessor blocks found.");
704 return Failure;
705 }
706 PreprocessorBlockBit = Stream.GetCurrentBitNo();
707 if (Stream.SkipBlock()) {
708 Error("Malformed block record");
709 return Failure;
710 }
711 break;
712
Douglas Gregorab1cef72009-04-10 03:52:48 +0000713 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000714 switch (ReadSourceManagerBlock()) {
715 case Success:
716 break;
717
718 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000719 Error("Malformed source manager block");
720 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000721
722 case IgnorePCH:
723 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000724 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000725 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000726 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000727 continue;
728 }
729
730 if (Code == llvm::bitc::DEFINE_ABBREV) {
731 Stream.ReadAbbrevRecord();
732 continue;
733 }
734
735 // Read and process a record.
736 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000737 const char *BlobStart = 0;
738 unsigned BlobLen = 0;
739 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
740 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000741 default: // Default behavior: ignore.
742 break;
743
744 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000745 if (!TypeOffsets.empty()) {
746 Error("Duplicate TYPE_OFFSET record in PCH file");
747 return Failure;
748 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000749 TypeOffsets.swap(Record);
750 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
751 break;
752
753 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000754 if (!DeclOffsets.empty()) {
755 Error("Duplicate DECL_OFFSET record in PCH file");
756 return Failure;
757 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000758 DeclOffsets.swap(Record);
759 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
760 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000761
762 case pch::LANGUAGE_OPTIONS:
763 if (ParseLanguageOptions(Record))
764 return IgnorePCH;
765 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000766
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000767 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000768 std::string TargetTriple(BlobStart, BlobLen);
769 if (TargetTriple != Context.Target.getTargetTriple()) {
770 Diag(diag::warn_pch_target_triple)
771 << TargetTriple << Context.Target.getTargetTriple();
772 Diag(diag::note_ignoring_pch) << FileName;
773 return IgnorePCH;
774 }
775 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000776 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000777
778 case pch::IDENTIFIER_TABLE:
779 IdentifierTable = BlobStart;
780 break;
781
782 case pch::IDENTIFIER_OFFSET:
783 if (!IdentifierData.empty()) {
784 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
785 return Failure;
786 }
787 IdentifierData.swap(Record);
788#ifndef NDEBUG
789 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
790 if ((IdentifierData[I] & 0x01) == 0) {
791 Error("Malformed identifier table in the precompiled header");
792 return Failure;
793 }
794 }
795#endif
796 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000797
798 case pch::EXTERNAL_DEFINITIONS:
799 if (!ExternalDefinitions.empty()) {
800 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
801 return Failure;
802 }
803 ExternalDefinitions.swap(Record);
804 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000805 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000806 }
807
Douglas Gregor179cfb12009-04-10 20:39:37 +0000808 Error("Premature end of bitstream");
809 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000810}
811
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000812PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000813 // Set the PCH file name.
814 this->FileName = FileName;
815
Douglas Gregorc34897d2009-04-09 22:27:44 +0000816 // Open the PCH file.
817 std::string ErrStr;
818 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000819 if (!Buffer) {
820 Error(ErrStr.c_str());
821 return IgnorePCH;
822 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000823
824 // Initialize the stream
825 Stream.init((const unsigned char *)Buffer->getBufferStart(),
826 (const unsigned char *)Buffer->getBufferEnd());
827
828 // Sniff for the signature.
829 if (Stream.Read(8) != 'C' ||
830 Stream.Read(8) != 'P' ||
831 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000832 Stream.Read(8) != 'H') {
833 Error("Not a PCH file");
834 return IgnorePCH;
835 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000836
837 // We expect a number of well-defined blocks, though we don't necessarily
838 // need to understand them all.
839 while (!Stream.AtEndOfStream()) {
840 unsigned Code = Stream.ReadCode();
841
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000842 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
843 Error("Invalid record at top-level");
844 return Failure;
845 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000846
847 unsigned BlockID = Stream.ReadSubBlockID();
848
849 // We only know the PCH subblock ID.
850 switch (BlockID) {
851 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000852 if (Stream.ReadBlockInfoBlock()) {
853 Error("Malformed BlockInfoBlock");
854 return Failure;
855 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000856 break;
857 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000858 switch (ReadPCHBlock()) {
859 case Success:
860 break;
861
862 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000863 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000864
865 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000866 // FIXME: We could consider reading through to the end of this
867 // PCH block, skipping subblocks, to see if there are other
868 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000869 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000870 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000871 break;
872 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000873 if (Stream.SkipBlock()) {
874 Error("Malformed block record");
875 return Failure;
876 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000877 break;
878 }
879 }
880
881 // Load the translation unit declaration
882 ReadDeclRecord(DeclOffsets[0], 0);
883
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000884 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000885}
886
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000887namespace {
888 /// \brief Helper class that saves the current stream position and
889 /// then restores it when destroyed.
890 struct VISIBILITY_HIDDEN SavedStreamPosition {
891 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000892 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000893
894 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000895 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000896 }
897
898 private:
899 llvm::BitstreamReader &Stream;
900 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000901 };
902}
903
Douglas Gregor179cfb12009-04-10 20:39:37 +0000904/// \brief Parse the record that corresponds to a LangOptions data
905/// structure.
906///
907/// This routine compares the language options used to generate the
908/// PCH file against the language options set for the current
909/// compilation. For each option, we classify differences between the
910/// two compiler states as either "benign" or "important". Benign
911/// differences don't matter, and we accept them without complaint
912/// (and without modifying the language options). Differences between
913/// the states for important options cause the PCH file to be
914/// unusable, so we emit a warning and return true to indicate that
915/// there was an error.
916///
917/// \returns true if the PCH file is unacceptable, false otherwise.
918bool PCHReader::ParseLanguageOptions(
919 const llvm::SmallVectorImpl<uint64_t> &Record) {
920 const LangOptions &LangOpts = Context.getLangOptions();
921#define PARSE_LANGOPT_BENIGN(Option) ++Idx
922#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
923 if (Record[Idx] != LangOpts.Option) { \
924 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
925 Diag(diag::note_ignoring_pch) << FileName; \
926 return true; \
927 } \
928 ++Idx
929
930 unsigned Idx = 0;
931 PARSE_LANGOPT_BENIGN(Trigraphs);
932 PARSE_LANGOPT_BENIGN(BCPLComment);
933 PARSE_LANGOPT_BENIGN(DollarIdents);
934 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
935 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
936 PARSE_LANGOPT_BENIGN(ImplicitInt);
937 PARSE_LANGOPT_BENIGN(Digraphs);
938 PARSE_LANGOPT_BENIGN(HexFloats);
939 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
940 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
941 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
942 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
943 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
944 PARSE_LANGOPT_BENIGN(CXXOperatorName);
945 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
946 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
947 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
948 PARSE_LANGOPT_BENIGN(PascalStrings);
949 PARSE_LANGOPT_BENIGN(Boolean);
950 PARSE_LANGOPT_BENIGN(WritableStrings);
951 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
952 diag::warn_pch_lax_vector_conversions);
953 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
954 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
955 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
956 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
957 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
958 diag::warn_pch_thread_safe_statics);
959 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
960 PARSE_LANGOPT_BENIGN(EmitAllDecls);
961 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
962 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
963 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
964 diag::warn_pch_heinous_extensions);
965 // FIXME: Most of the options below are benign if the macro wasn't
966 // used. Unfortunately, this means that a PCH compiled without
967 // optimization can't be used with optimization turned on, even
968 // though the only thing that changes is whether __OPTIMIZE__ was
969 // defined... but if __OPTIMIZE__ never showed up in the header, it
970 // doesn't matter. We could consider making this some special kind
971 // of check.
972 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
973 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
974 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
975 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
976 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
977 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
978 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
979 Diag(diag::warn_pch_gc_mode)
980 << (unsigned)Record[Idx] << LangOpts.getGCMode();
981 Diag(diag::note_ignoring_pch) << FileName;
982 return true;
983 }
984 ++Idx;
985 PARSE_LANGOPT_BENIGN(getVisibilityMode());
986 PARSE_LANGOPT_BENIGN(InstantiationDepth);
987#undef PARSE_LANGOPT_IRRELEVANT
988#undef PARSE_LANGOPT_BENIGN
989
990 return false;
991}
992
Douglas Gregorc34897d2009-04-09 22:27:44 +0000993/// \brief Read and return the type at the given offset.
994///
995/// This routine actually reads the record corresponding to the type
996/// at the given offset in the bitstream. It is a helper routine for
997/// GetType, which deals with reading type IDs.
998QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000999 // Keep track of where we are in the stream, then jump back there
1000 // after reading this type.
1001 SavedStreamPosition SavedPosition(Stream);
1002
Douglas Gregorc34897d2009-04-09 22:27:44 +00001003 Stream.JumpToBit(Offset);
1004 RecordData Record;
1005 unsigned Code = Stream.ReadCode();
1006 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001007 case pch::TYPE_EXT_QUAL:
1008 // FIXME: Deserialize ExtQualType
1009 assert(false && "Cannot deserialize qualified types yet");
1010 return QualType();
1011
Douglas Gregorc34897d2009-04-09 22:27:44 +00001012 case pch::TYPE_FIXED_WIDTH_INT: {
1013 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1014 return Context.getFixedWidthIntType(Record[0], Record[1]);
1015 }
1016
1017 case pch::TYPE_COMPLEX: {
1018 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1019 QualType ElemType = GetType(Record[0]);
1020 return Context.getComplexType(ElemType);
1021 }
1022
1023 case pch::TYPE_POINTER: {
1024 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1025 QualType PointeeType = GetType(Record[0]);
1026 return Context.getPointerType(PointeeType);
1027 }
1028
1029 case pch::TYPE_BLOCK_POINTER: {
1030 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1031 QualType PointeeType = GetType(Record[0]);
1032 return Context.getBlockPointerType(PointeeType);
1033 }
1034
1035 case pch::TYPE_LVALUE_REFERENCE: {
1036 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1037 QualType PointeeType = GetType(Record[0]);
1038 return Context.getLValueReferenceType(PointeeType);
1039 }
1040
1041 case pch::TYPE_RVALUE_REFERENCE: {
1042 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1043 QualType PointeeType = GetType(Record[0]);
1044 return Context.getRValueReferenceType(PointeeType);
1045 }
1046
1047 case pch::TYPE_MEMBER_POINTER: {
1048 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1049 QualType PointeeType = GetType(Record[0]);
1050 QualType ClassType = GetType(Record[1]);
1051 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1052 }
1053
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001054 case pch::TYPE_CONSTANT_ARRAY: {
1055 QualType ElementType = GetType(Record[0]);
1056 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1057 unsigned IndexTypeQuals = Record[2];
1058 unsigned Idx = 3;
1059 llvm::APInt Size = ReadAPInt(Record, Idx);
1060 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1061 }
1062
1063 case pch::TYPE_INCOMPLETE_ARRAY: {
1064 QualType ElementType = GetType(Record[0]);
1065 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1066 unsigned IndexTypeQuals = Record[2];
1067 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1068 }
1069
1070 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001071 QualType ElementType = GetType(Record[0]);
1072 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1073 unsigned IndexTypeQuals = Record[2];
1074 return Context.getVariableArrayType(ElementType, ReadExpr(),
1075 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001076 }
1077
1078 case pch::TYPE_VECTOR: {
1079 if (Record.size() != 2) {
1080 Error("Incorrect encoding of vector type in PCH file");
1081 return QualType();
1082 }
1083
1084 QualType ElementType = GetType(Record[0]);
1085 unsigned NumElements = Record[1];
1086 return Context.getVectorType(ElementType, NumElements);
1087 }
1088
1089 case pch::TYPE_EXT_VECTOR: {
1090 if (Record.size() != 2) {
1091 Error("Incorrect encoding of extended vector type in PCH file");
1092 return QualType();
1093 }
1094
1095 QualType ElementType = GetType(Record[0]);
1096 unsigned NumElements = Record[1];
1097 return Context.getExtVectorType(ElementType, NumElements);
1098 }
1099
1100 case pch::TYPE_FUNCTION_NO_PROTO: {
1101 if (Record.size() != 1) {
1102 Error("Incorrect encoding of no-proto function type");
1103 return QualType();
1104 }
1105 QualType ResultType = GetType(Record[0]);
1106 return Context.getFunctionNoProtoType(ResultType);
1107 }
1108
1109 case pch::TYPE_FUNCTION_PROTO: {
1110 QualType ResultType = GetType(Record[0]);
1111 unsigned Idx = 1;
1112 unsigned NumParams = Record[Idx++];
1113 llvm::SmallVector<QualType, 16> ParamTypes;
1114 for (unsigned I = 0; I != NumParams; ++I)
1115 ParamTypes.push_back(GetType(Record[Idx++]));
1116 bool isVariadic = Record[Idx++];
1117 unsigned Quals = Record[Idx++];
1118 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1119 isVariadic, Quals);
1120 }
1121
1122 case pch::TYPE_TYPEDEF:
1123 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1124 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1125
1126 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001127 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001128
1129 case pch::TYPE_TYPEOF: {
1130 if (Record.size() != 1) {
1131 Error("Incorrect encoding of typeof(type) in PCH file");
1132 return QualType();
1133 }
1134 QualType UnderlyingType = GetType(Record[0]);
1135 return Context.getTypeOfType(UnderlyingType);
1136 }
1137
1138 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001139 assert(Record.size() == 1 && "Incorrect encoding of record type");
1140 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001141
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001142 case pch::TYPE_ENUM:
1143 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1144 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1145
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001146 case pch::TYPE_OBJC_INTERFACE:
1147 // FIXME: Deserialize ObjCInterfaceType
1148 assert(false && "Cannot de-serialize ObjC interface types yet");
1149 return QualType();
1150
1151 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1152 // FIXME: Deserialize ObjCQualifiedInterfaceType
1153 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1154 return QualType();
1155
1156 case pch::TYPE_OBJC_QUALIFIED_ID:
1157 // FIXME: Deserialize ObjCQualifiedIdType
1158 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1159 return QualType();
1160
1161 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1162 // FIXME: Deserialize ObjCQualifiedClassType
1163 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1164 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001165 }
1166
1167 // Suppress a GCC warning
1168 return QualType();
1169}
1170
1171/// \brief Note that we have loaded the declaration with the given
1172/// Index.
1173///
1174/// This routine notes that this declaration has already been loaded,
1175/// so that future GetDecl calls will return this declaration rather
1176/// than trying to load a new declaration.
1177inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1178 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1179 DeclAlreadyLoaded[Index] = true;
1180 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1181}
1182
1183/// \brief Read the declaration at the given offset from the PCH file.
1184Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001185 // Keep track of where we are in the stream, then jump back there
1186 // after reading this declaration.
1187 SavedStreamPosition SavedPosition(Stream);
1188
Douglas Gregorc34897d2009-04-09 22:27:44 +00001189 Decl *D = 0;
1190 Stream.JumpToBit(Offset);
1191 RecordData Record;
1192 unsigned Code = Stream.ReadCode();
1193 unsigned Idx = 0;
1194 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001195
Douglas Gregorc34897d2009-04-09 22:27:44 +00001196 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1197 case pch::DECL_TRANSLATION_UNIT:
1198 assert(Index == 0 && "Translation unit must be at index 0");
1199 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1200 D = Context.getTranslationUnitDecl();
1201 LoadedDecl(Index, D);
1202 break;
1203
1204 case pch::DECL_TYPEDEF: {
1205 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1206 0, QualType());
1207 LoadedDecl(Index, Typedef);
1208 Reader.VisitTypedefDecl(Typedef);
1209 D = Typedef;
1210 break;
1211 }
1212
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001213 case pch::DECL_ENUM: {
1214 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1215 LoadedDecl(Index, Enum);
1216 Reader.VisitEnumDecl(Enum);
1217 D = Enum;
1218 break;
1219 }
1220
Douglas Gregor982365e2009-04-13 21:20:57 +00001221 case pch::DECL_RECORD: {
1222 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1223 0, SourceLocation(), 0, 0);
1224 LoadedDecl(Index, Record);
1225 Reader.VisitRecordDecl(Record);
1226 D = Record;
1227 break;
1228 }
1229
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001230 case pch::DECL_ENUM_CONSTANT: {
1231 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1232 SourceLocation(), 0,
1233 QualType(), 0,
1234 llvm::APSInt());
1235 LoadedDecl(Index, ECD);
1236 Reader.VisitEnumConstantDecl(ECD);
1237 D = ECD;
1238 break;
1239 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001240
1241 case pch::DECL_FUNCTION: {
1242 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1243 DeclarationName(),
1244 QualType());
1245 LoadedDecl(Index, Function);
1246 Reader.VisitFunctionDecl(Function);
1247 D = Function;
1248 break;
1249 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001250
Douglas Gregor982365e2009-04-13 21:20:57 +00001251 case pch::DECL_FIELD: {
1252 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1253 QualType(), 0, false);
1254 LoadedDecl(Index, Field);
1255 Reader.VisitFieldDecl(Field);
1256 D = Field;
1257 break;
1258 }
1259
Douglas Gregorc34897d2009-04-09 22:27:44 +00001260 case pch::DECL_VAR: {
1261 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1262 VarDecl::None, SourceLocation());
1263 LoadedDecl(Index, Var);
1264 Reader.VisitVarDecl(Var);
1265 D = Var;
1266 break;
1267 }
1268
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001269 case pch::DECL_PARM_VAR: {
1270 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1271 QualType(), VarDecl::None, 0);
1272 LoadedDecl(Index, Parm);
1273 Reader.VisitParmVarDecl(Parm);
1274 D = Parm;
1275 break;
1276 }
1277
1278 case pch::DECL_ORIGINAL_PARM_VAR: {
1279 OriginalParmVarDecl *Parm
1280 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1281 QualType(), QualType(), VarDecl::None,
1282 0);
1283 LoadedDecl(Index, Parm);
1284 Reader.VisitOriginalParmVarDecl(Parm);
1285 D = Parm;
1286 break;
1287 }
1288
Douglas Gregor2a491792009-04-13 22:49:25 +00001289 case pch::DECL_FILE_SCOPE_ASM: {
1290 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1291 SourceLocation(), 0);
1292 LoadedDecl(Index, Asm);
1293 Reader.VisitFileScopeAsmDecl(Asm);
1294 D = Asm;
1295 break;
1296 }
1297
1298 case pch::DECL_BLOCK: {
1299 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1300 LoadedDecl(Index, Block);
1301 Reader.VisitBlockDecl(Block);
1302 D = Block;
1303 break;
1304 }
1305
Douglas Gregorc34897d2009-04-09 22:27:44 +00001306 default:
1307 assert(false && "Cannot de-serialize this kind of declaration");
1308 break;
1309 }
1310
1311 // If this declaration is also a declaration context, get the
1312 // offsets for its tables of lexical and visible declarations.
1313 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1314 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1315 if (Offsets.first || Offsets.second) {
1316 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1317 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1318 DeclContextOffsets[DC] = Offsets;
1319 }
1320 }
1321 assert(Idx == Record.size());
1322
1323 return D;
1324}
1325
Douglas Gregorac8f2802009-04-10 17:25:41 +00001326QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001327 unsigned Quals = ID & 0x07;
1328 unsigned Index = ID >> 3;
1329
1330 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1331 QualType T;
1332 switch ((pch::PredefinedTypeIDs)Index) {
1333 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1334 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1335 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1336
1337 case pch::PREDEF_TYPE_CHAR_U_ID:
1338 case pch::PREDEF_TYPE_CHAR_S_ID:
1339 // FIXME: Check that the signedness of CharTy is correct!
1340 T = Context.CharTy;
1341 break;
1342
1343 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1344 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1345 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1346 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1347 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1348 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1349 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1350 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1351 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1352 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1353 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1354 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1355 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1356 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1357 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1358 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1359 }
1360
1361 assert(!T.isNull() && "Unknown predefined type");
1362 return T.getQualifiedType(Quals);
1363 }
1364
1365 Index -= pch::NUM_PREDEF_TYPE_IDS;
1366 if (!TypeAlreadyLoaded[Index]) {
1367 // Load the type from the PCH file.
1368 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1369 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1370 TypeAlreadyLoaded[Index] = true;
1371 }
1372
1373 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1374}
1375
Douglas Gregorac8f2802009-04-10 17:25:41 +00001376Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001377 if (ID == 0)
1378 return 0;
1379
1380 unsigned Index = ID - 1;
1381 if (DeclAlreadyLoaded[Index])
1382 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1383
1384 // Load the declaration from the PCH file.
1385 return ReadDeclRecord(DeclOffsets[Index], Index);
1386}
1387
1388bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001389 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001390 assert(DC->hasExternalLexicalStorage() &&
1391 "DeclContext has no lexical decls in storage");
1392 uint64_t Offset = DeclContextOffsets[DC].first;
1393 assert(Offset && "DeclContext has no lexical decls in storage");
1394
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001395 // Keep track of where we are in the stream, then jump back there
1396 // after reading this context.
1397 SavedStreamPosition SavedPosition(Stream);
1398
Douglas Gregorc34897d2009-04-09 22:27:44 +00001399 // Load the record containing all of the declarations lexically in
1400 // this context.
1401 Stream.JumpToBit(Offset);
1402 RecordData Record;
1403 unsigned Code = Stream.ReadCode();
1404 unsigned RecCode = Stream.ReadRecord(Code, Record);
1405 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1406
1407 // Load all of the declaration IDs
1408 Decls.clear();
1409 Decls.insert(Decls.end(), Record.begin(), Record.end());
1410 return false;
1411}
1412
1413bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1414 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1415 assert(DC->hasExternalVisibleStorage() &&
1416 "DeclContext has no visible decls in storage");
1417 uint64_t Offset = DeclContextOffsets[DC].second;
1418 assert(Offset && "DeclContext has no visible decls in storage");
1419
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001420 // Keep track of where we are in the stream, then jump back there
1421 // after reading this context.
1422 SavedStreamPosition SavedPosition(Stream);
1423
Douglas Gregorc34897d2009-04-09 22:27:44 +00001424 // Load the record containing all of the declarations visible in
1425 // this context.
1426 Stream.JumpToBit(Offset);
1427 RecordData Record;
1428 unsigned Code = Stream.ReadCode();
1429 unsigned RecCode = Stream.ReadRecord(Code, Record);
1430 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1431 if (Record.size() == 0)
1432 return false;
1433
1434 Decls.clear();
1435
1436 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001437 while (Idx < Record.size()) {
1438 Decls.push_back(VisibleDeclaration());
1439 Decls.back().Name = ReadDeclarationName(Record, Idx);
1440
Douglas Gregorc34897d2009-04-09 22:27:44 +00001441 unsigned Size = Record[Idx++];
1442 llvm::SmallVector<unsigned, 4> & LoadedDecls
1443 = Decls.back().Declarations;
1444 LoadedDecls.reserve(Size);
1445 for (unsigned I = 0; I < Size; ++I)
1446 LoadedDecls.push_back(Record[Idx++]);
1447 }
1448
1449 return false;
1450}
1451
Douglas Gregor631f6c62009-04-14 00:24:19 +00001452void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1453 if (!Consumer)
1454 return;
1455
1456 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1457 Decl *D = GetDecl(ExternalDefinitions[I]);
1458 DeclGroupRef DG(D);
1459 Consumer->HandleTopLevelDecl(DG);
1460 }
1461}
1462
Douglas Gregorc34897d2009-04-09 22:27:44 +00001463void PCHReader::PrintStats() {
1464 std::fprintf(stderr, "*** PCH Statistics:\n");
1465
1466 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1467 TypeAlreadyLoaded.end(),
1468 true);
1469 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1470 DeclAlreadyLoaded.end(),
1471 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001472 unsigned NumIdentifiersLoaded = 0;
1473 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1474 if ((IdentifierData[I] & 0x01) == 0)
1475 ++NumIdentifiersLoaded;
1476 }
1477
Douglas Gregorc34897d2009-04-09 22:27:44 +00001478 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1479 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001480 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001481 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1482 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001483 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1484 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1485 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1486 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001487 std::fprintf(stderr, "\n");
1488}
1489
Chris Lattner29241862009-04-11 21:15:38 +00001490IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001491 if (ID == 0)
1492 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001493
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001494 if (!IdentifierTable || IdentifierData.empty()) {
1495 Error("No identifier table in PCH file");
1496 return 0;
1497 }
Chris Lattner29241862009-04-11 21:15:38 +00001498
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001499 if (IdentifierData[ID - 1] & 0x01) {
1500 uint64_t Offset = IdentifierData[ID - 1];
1501 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001502 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001503 }
Chris Lattner29241862009-04-11 21:15:38 +00001504
1505 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001506}
1507
1508DeclarationName
1509PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1510 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1511 switch (Kind) {
1512 case DeclarationName::Identifier:
1513 return DeclarationName(GetIdentifierInfo(Record, Idx));
1514
1515 case DeclarationName::ObjCZeroArgSelector:
1516 case DeclarationName::ObjCOneArgSelector:
1517 case DeclarationName::ObjCMultiArgSelector:
1518 assert(false && "Unable to de-serialize Objective-C selectors");
1519 break;
1520
1521 case DeclarationName::CXXConstructorName:
1522 return Context.DeclarationNames.getCXXConstructorName(
1523 GetType(Record[Idx++]));
1524
1525 case DeclarationName::CXXDestructorName:
1526 return Context.DeclarationNames.getCXXDestructorName(
1527 GetType(Record[Idx++]));
1528
1529 case DeclarationName::CXXConversionFunctionName:
1530 return Context.DeclarationNames.getCXXConversionFunctionName(
1531 GetType(Record[Idx++]));
1532
1533 case DeclarationName::CXXOperatorName:
1534 return Context.DeclarationNames.getCXXOperatorName(
1535 (OverloadedOperatorKind)Record[Idx++]);
1536
1537 case DeclarationName::CXXUsingDirective:
1538 return DeclarationName::getUsingDirectiveName();
1539 }
1540
1541 // Required to silence GCC warning
1542 return DeclarationName();
1543}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001544
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001545/// \brief Read an integral value
1546llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1547 unsigned BitWidth = Record[Idx++];
1548 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1549 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1550 Idx += NumWords;
1551 return Result;
1552}
1553
1554/// \brief Read a signed integral value
1555llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1556 bool isUnsigned = Record[Idx++];
1557 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1558}
1559
Douglas Gregore2f37202009-04-14 21:55:33 +00001560/// \brief Read a floating-point value
1561llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1562 // FIXME: is this really correct?
1563 return llvm::APFloat(ReadAPInt(Record, Idx));
1564}
1565
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001566Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001567 // Within the bitstream, expressions are stored in Reverse Polish
1568 // Notation, with each of the subexpressions preceding the
1569 // expression they are stored in. To evaluate expressions, we
1570 // continue reading expressions and placing them on the stack, with
1571 // expressions having operands removing those operands from the
1572 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1573 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001574 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001575 unsigned Idx;
1576 llvm::SmallVector<Expr *, 16> ExprStack;
1577 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001578 Stmt::EmptyShell Empty;
1579
Douglas Gregora151ba42009-04-14 23:32:43 +00001580 while (true) {
1581 unsigned Code = Stream.ReadCode();
1582 if (Code == llvm::bitc::END_BLOCK) {
1583 if (Stream.ReadBlockEnd()) {
1584 Error("Error at end of Source Manager block");
1585 return 0;
1586 }
1587 break;
1588 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001589
Douglas Gregora151ba42009-04-14 23:32:43 +00001590 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1591 // No known subblocks, always skip them.
1592 Stream.ReadSubBlockID();
1593 if (Stream.SkipBlock()) {
1594 Error("Malformed block record");
1595 return 0;
1596 }
1597 continue;
1598 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001599
Douglas Gregora151ba42009-04-14 23:32:43 +00001600 if (Code == llvm::bitc::DEFINE_ABBREV) {
1601 Stream.ReadAbbrevRecord();
1602 continue;
1603 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001604
Douglas Gregora151ba42009-04-14 23:32:43 +00001605 Expr *E = 0;
1606 Idx = 0;
1607 Record.clear();
1608 bool Finished = false;
1609 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1610 case pch::EXPR_STOP:
1611 Finished = true;
1612 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001613
Douglas Gregora151ba42009-04-14 23:32:43 +00001614 case pch::EXPR_NULL:
1615 E = 0;
1616 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001617
Douglas Gregora151ba42009-04-14 23:32:43 +00001618 case pch::EXPR_PREDEFINED:
1619 // FIXME: untested (until we can serialize function bodies).
1620 E = new (Context) PredefinedExpr(Empty);
1621 break;
1622
1623 case pch::EXPR_DECL_REF:
1624 E = new (Context) DeclRefExpr(Empty);
1625 break;
1626
1627 case pch::EXPR_INTEGER_LITERAL:
1628 E = new (Context) IntegerLiteral(Empty);
1629 break;
1630
1631 case pch::EXPR_FLOATING_LITERAL:
1632 E = new (Context) FloatingLiteral(Empty);
1633 break;
1634
1635 case pch::EXPR_CHARACTER_LITERAL:
1636 E = new (Context) CharacterLiteral(Empty);
1637 break;
1638
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001639 case pch::EXPR_PAREN:
1640 E = new (Context) ParenExpr(Empty);
1641 break;
1642
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001643 case pch::EXPR_BINARY_OPERATOR:
1644 E = new (Context) BinaryOperator(Empty);
1645 break;
1646
Douglas Gregora151ba42009-04-14 23:32:43 +00001647 case pch::EXPR_IMPLICIT_CAST:
1648 E = new (Context) ImplicitCastExpr(Empty);
1649 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001650
1651 case pch::EXPR_CSTYLE_CAST:
1652 E = new (Context) CStyleCastExpr(Empty);
1653 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001654 }
1655
1656 // We hit an EXPR_STOP, so we're done with this expression.
1657 if (Finished)
1658 break;
1659
1660 if (E) {
1661 unsigned NumSubExprs = Reader.Visit(E);
1662 while (NumSubExprs > 0) {
1663 ExprStack.pop_back();
1664 --NumSubExprs;
1665 }
1666 }
1667
1668 assert(Idx == Record.size() && "Invalid deserialization of expression");
1669 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001670 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001671 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1672 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001673}
1674
Douglas Gregor179cfb12009-04-10 20:39:37 +00001675DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001676 return Diag(SourceLocation(), DiagID);
1677}
1678
1679DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1680 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001681 Context.getSourceManager()),
1682 DiagID);
1683}