blob: 983c2b880728bf0680fd2df5e17bd946dfb83269 [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);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000191 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000192}
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 Gregor596e0932009-04-15 16:35:07 +0000229 /// \brief The number of record fields required for the Expr class
230 /// itself.
231 static const unsigned NumExprFields = 3;
232
Douglas Gregora151ba42009-04-14 23:32:43 +0000233 // Each of the Visit* functions reads in part of the expression
234 // from the given record and the current expression stack, then
235 // return the total number of operands that it read from the
236 // expression stack.
237
238 unsigned VisitExpr(Expr *E);
239 unsigned VisitPredefinedExpr(PredefinedExpr *E);
240 unsigned VisitDeclRefExpr(DeclRefExpr *E);
241 unsigned VisitIntegerLiteral(IntegerLiteral *E);
242 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000243 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000244 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000245 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000246 unsigned VisitUnaryOperator(UnaryOperator *E);
247 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000248 unsigned VisitCallExpr(CallExpr *E);
249 unsigned VisitMemberExpr(MemberExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000250 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000251 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000252 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000253 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
254 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000255 };
256}
257
Douglas Gregora151ba42009-04-14 23:32:43 +0000258unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000259 E->setType(Reader.GetType(Record[Idx++]));
260 E->setTypeDependent(Record[Idx++]);
261 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000262 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000263 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000264}
265
Douglas Gregora151ba42009-04-14 23:32:43 +0000266unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000267 VisitExpr(E);
268 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
269 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000270 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000271}
272
Douglas Gregora151ba42009-04-14 23:32:43 +0000273unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000274 VisitExpr(E);
275 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
276 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000277 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000278}
279
Douglas Gregora151ba42009-04-14 23:32:43 +0000280unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000281 VisitExpr(E);
282 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
283 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000284 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000285}
286
Douglas Gregora151ba42009-04-14 23:32:43 +0000287unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000288 VisitExpr(E);
289 E->setValue(Reader.ReadAPFloat(Record, Idx));
290 E->setExact(Record[Idx++]);
291 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000292 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000293}
294
Douglas Gregor596e0932009-04-15 16:35:07 +0000295unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
296 VisitExpr(E);
297 unsigned Len = Record[Idx++];
298 assert(Record[Idx] == E->getNumConcatenated() &&
299 "Wrong number of concatenated tokens!");
300 ++Idx;
301 E->setWide(Record[Idx++]);
302
303 // Read string data
304 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
305 E->setStrData(Reader.getContext(), &Str[0], Len);
306 Idx += Len;
307
308 // Read source locations
309 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
310 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
311
312 return 0;
313}
314
Douglas Gregora151ba42009-04-14 23:32:43 +0000315unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000316 VisitExpr(E);
317 E->setValue(Record[Idx++]);
318 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
319 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000320 return 0;
321}
322
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000323unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
324 VisitExpr(E);
325 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
326 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
327 E->setSubExpr(ExprStack.back());
328 return 1;
329}
330
Douglas Gregor12d74052009-04-15 15:58:59 +0000331unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
332 VisitExpr(E);
333 E->setSubExpr(ExprStack.back());
334 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
335 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
336 return 1;
337}
338
339unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
340 VisitExpr(E);
341 E->setSizeof(Record[Idx++]);
342 if (Record[Idx] == 0) {
343 E->setArgument(ExprStack.back());
344 ++Idx;
345 } else {
346 E->setArgument(Reader.GetType(Record[Idx++]));
347 }
348 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
349 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
350 return E->isArgumentType()? 0 : 1;
351}
352
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000353unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
354 VisitExpr(E);
355 E->setNumArgs(Reader.getContext(), Record[Idx++]);
356 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
357 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
358 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
359 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
360 return E->getNumArgs() + 1;
361}
362
363unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
364 VisitExpr(E);
365 E->setBase(ExprStack.back());
366 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
367 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
368 E->setArrow(Record[Idx++]);
369 return 1;
370}
371
Douglas Gregora151ba42009-04-14 23:32:43 +0000372unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
373 VisitExpr(E);
374 E->setSubExpr(ExprStack.back());
375 return 1;
376}
377
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000378unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
379 VisitExpr(E);
380 E->setLHS(ExprStack.end()[-2]);
381 E->setRHS(ExprStack.end()[-1]);
382 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
383 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
384 return 2;
385}
386
Douglas Gregora151ba42009-04-14 23:32:43 +0000387unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
388 VisitCastExpr(E);
389 E->setLvalueCast(Record[Idx++]);
390 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000391}
392
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000393unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
394 VisitCastExpr(E);
395 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
396 return 1;
397}
398
399unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
400 VisitExplicitCastExpr(E);
401 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
402 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
403 return 1;
404}
405
Douglas Gregorc34897d2009-04-09 22:27:44 +0000406// FIXME: use the diagnostics machinery
407static bool Error(const char *Str) {
408 std::fprintf(stderr, "%s\n", Str);
409 return true;
410}
411
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000412/// \brief Check the contents of the predefines buffer against the
413/// contents of the predefines buffer used to build the PCH file.
414///
415/// The contents of the two predefines buffers should be the same. If
416/// not, then some command-line option changed the preprocessor state
417/// and we must reject the PCH file.
418///
419/// \param PCHPredef The start of the predefines buffer in the PCH
420/// file.
421///
422/// \param PCHPredefLen The length of the predefines buffer in the PCH
423/// file.
424///
425/// \param PCHBufferID The FileID for the PCH predefines buffer.
426///
427/// \returns true if there was a mismatch (in which case the PCH file
428/// should be ignored), or false otherwise.
429bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
430 unsigned PCHPredefLen,
431 FileID PCHBufferID) {
432 const char *Predef = PP.getPredefines().c_str();
433 unsigned PredefLen = PP.getPredefines().size();
434
435 // If the two predefines buffers compare equal, we're done!.
436 if (PredefLen == PCHPredefLen &&
437 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
438 return false;
439
440 // The predefines buffers are different. Produce a reasonable
441 // diagnostic showing where they are different.
442
443 // The source locations (potentially in the two different predefines
444 // buffers)
445 SourceLocation Loc1, Loc2;
446 SourceManager &SourceMgr = PP.getSourceManager();
447
448 // Create a source buffer for our predefines string, so
449 // that we can build a diagnostic that points into that
450 // source buffer.
451 FileID BufferID;
452 if (Predef && Predef[0]) {
453 llvm::MemoryBuffer *Buffer
454 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
455 "<built-in>");
456 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
457 }
458
459 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
460 std::pair<const char *, const char *> Locations
461 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
462
463 if (Locations.first != Predef + MinLen) {
464 // We found the location in the two buffers where there is a
465 // difference. Form source locations to point there (in both
466 // buffers).
467 unsigned Offset = Locations.first - Predef;
468 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
469 .getFileLocWithOffset(Offset);
470 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
471 .getFileLocWithOffset(Offset);
472 } else if (PredefLen > PCHPredefLen) {
473 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
474 .getFileLocWithOffset(MinLen);
475 } else {
476 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
477 .getFileLocWithOffset(MinLen);
478 }
479
480 Diag(Loc1, diag::warn_pch_preprocessor);
481 if (Loc2.isValid())
482 Diag(Loc2, diag::note_predef_in_pch);
483 Diag(diag::note_ignoring_pch) << FileName;
484 return true;
485}
486
Douglas Gregor635f97f2009-04-13 16:31:14 +0000487/// \brief Read the line table in the source manager block.
488/// \returns true if ther was an error.
489static bool ParseLineTable(SourceManager &SourceMgr,
490 llvm::SmallVectorImpl<uint64_t> &Record) {
491 unsigned Idx = 0;
492 LineTableInfo &LineTable = SourceMgr.getLineTable();
493
494 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000495 std::map<int, int> FileIDs;
496 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000497 // Extract the file name
498 unsigned FilenameLen = Record[Idx++];
499 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
500 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000501 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
502 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000503 }
504
505 // Parse the line entries
506 std::vector<LineEntry> Entries;
507 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000508 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000509
510 // Extract the line entries
511 unsigned NumEntries = Record[Idx++];
512 Entries.clear();
513 Entries.reserve(NumEntries);
514 for (unsigned I = 0; I != NumEntries; ++I) {
515 unsigned FileOffset = Record[Idx++];
516 unsigned LineNo = Record[Idx++];
517 int FilenameID = Record[Idx++];
518 SrcMgr::CharacteristicKind FileKind
519 = (SrcMgr::CharacteristicKind)Record[Idx++];
520 unsigned IncludeOffset = Record[Idx++];
521 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
522 FileKind, IncludeOffset));
523 }
524 LineTable.AddEntry(FID, Entries);
525 }
526
527 return false;
528}
529
Douglas Gregorab1cef72009-04-10 03:52:48 +0000530/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000531PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000532 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000533 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
534 Error("Malformed source manager block record");
535 return Failure;
536 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000537
538 SourceManager &SourceMgr = Context.getSourceManager();
539 RecordData Record;
540 while (true) {
541 unsigned Code = Stream.ReadCode();
542 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000543 if (Stream.ReadBlockEnd()) {
544 Error("Error at end of Source Manager block");
545 return Failure;
546 }
547
548 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000549 }
550
551 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
552 // No known subblocks, always skip them.
553 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000554 if (Stream.SkipBlock()) {
555 Error("Malformed block record");
556 return Failure;
557 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000558 continue;
559 }
560
561 if (Code == llvm::bitc::DEFINE_ABBREV) {
562 Stream.ReadAbbrevRecord();
563 continue;
564 }
565
566 // Read a record.
567 const char *BlobStart;
568 unsigned BlobLen;
569 Record.clear();
570 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
571 default: // Default behavior: ignore.
572 break;
573
574 case pch::SM_SLOC_FILE_ENTRY: {
575 // FIXME: We would really like to delay the creation of this
576 // FileEntry until it is actually required, e.g., when producing
577 // a diagnostic with a source location in this file.
578 const FileEntry *File
579 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
580 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000581 FileID ID = SourceMgr.createFileID(File,
582 SourceLocation::getFromRawEncoding(Record[1]),
583 (CharacteristicKind)Record[2]);
584 if (Record[3])
585 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
586 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000587 break;
588 }
589
590 case pch::SM_SLOC_BUFFER_ENTRY: {
591 const char *Name = BlobStart;
592 unsigned Code = Stream.ReadCode();
593 Record.clear();
594 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
595 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000596 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000597 llvm::MemoryBuffer *Buffer
598 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
599 BlobStart + BlobLen - 1,
600 Name);
601 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
602
603 if (strcmp(Name, "<built-in>") == 0
604 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
605 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000606 break;
607 }
608
609 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
610 SourceLocation SpellingLoc
611 = SourceLocation::getFromRawEncoding(Record[1]);
612 SourceMgr.createInstantiationLoc(
613 SpellingLoc,
614 SourceLocation::getFromRawEncoding(Record[2]),
615 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000616 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000617 break;
618 }
619
Chris Lattnere1be6022009-04-14 23:22:57 +0000620 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000621 if (ParseLineTable(SourceMgr, Record))
622 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000623 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000624 }
625 }
626}
627
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000628bool PCHReader::ReadPreprocessorBlock() {
629 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
630 return Error("Malformed preprocessor block record");
631
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000632 RecordData Record;
633 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
634 MacroInfo *LastMacro = 0;
635
636 while (true) {
637 unsigned Code = Stream.ReadCode();
638 switch (Code) {
639 case llvm::bitc::END_BLOCK:
640 if (Stream.ReadBlockEnd())
641 return Error("Error at end of preprocessor block");
642 return false;
643
644 case llvm::bitc::ENTER_SUBBLOCK:
645 // No known subblocks, always skip them.
646 Stream.ReadSubBlockID();
647 if (Stream.SkipBlock())
648 return Error("Malformed block record");
649 continue;
650
651 case llvm::bitc::DEFINE_ABBREV:
652 Stream.ReadAbbrevRecord();
653 continue;
654 default: break;
655 }
656
657 // Read a record.
658 Record.clear();
659 pch::PreprocessorRecordTypes RecType =
660 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
661 switch (RecType) {
662 default: // Default behavior: ignore unknown records.
663 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000664 case pch::PP_COUNTER_VALUE:
665 if (!Record.empty())
666 PP.setCounterValue(Record[0]);
667 break;
668
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000669 case pch::PP_MACRO_OBJECT_LIKE:
670 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000671 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
672 if (II == 0)
673 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000674 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
675 bool isUsed = Record[2];
676
677 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
678 MI->setIsUsed(isUsed);
679
680 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
681 // Decode function-like macro info.
682 bool isC99VarArgs = Record[3];
683 bool isGNUVarArgs = Record[4];
684 MacroArgs.clear();
685 unsigned NumArgs = Record[5];
686 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000687 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000688
689 // Install function-like macro info.
690 MI->setIsFunctionLike();
691 if (isC99VarArgs) MI->setIsC99Varargs();
692 if (isGNUVarArgs) MI->setIsGNUVarargs();
693 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
694 PP.getPreprocessorAllocator());
695 }
696
697 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000698 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000699
700 // Remember that we saw this macro last so that we add the tokens that
701 // form its body to it.
702 LastMacro = MI;
703 break;
704 }
705
706 case pch::PP_TOKEN: {
707 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
708 // pretend we didn't see this.
709 if (LastMacro == 0) break;
710
711 Token Tok;
712 Tok.startToken();
713 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
714 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000715 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
716 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000717 Tok.setKind((tok::TokenKind)Record[3]);
718 Tok.setFlag((Token::TokenFlags)Record[4]);
719 LastMacro->AddTokenToBody(Tok);
720 break;
721 }
722 }
723 }
724}
725
Douglas Gregor179cfb12009-04-10 20:39:37 +0000726PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
727 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
728 Error("Malformed block record");
729 return Failure;
730 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000731
Chris Lattner29241862009-04-11 21:15:38 +0000732 uint64_t PreprocessorBlockBit = 0;
733
Douglas Gregorc34897d2009-04-09 22:27:44 +0000734 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000735 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000736 while (!Stream.AtEndOfStream()) {
737 unsigned Code = Stream.ReadCode();
738 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000739 // If we saw the preprocessor block, read it now.
740 if (PreprocessorBlockBit) {
741 uint64_t SavedPos = Stream.GetCurrentBitNo();
742 Stream.JumpToBit(PreprocessorBlockBit);
743 if (ReadPreprocessorBlock()) {
744 Error("Malformed preprocessor block");
745 return Failure;
746 }
747 Stream.JumpToBit(SavedPos);
748 }
749
Douglas Gregor179cfb12009-04-10 20:39:37 +0000750 if (Stream.ReadBlockEnd()) {
751 Error("Error at end of module block");
752 return Failure;
753 }
Chris Lattner29241862009-04-11 21:15:38 +0000754
Douglas Gregor179cfb12009-04-10 20:39:37 +0000755 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000756 }
757
758 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
759 switch (Stream.ReadSubBlockID()) {
760 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
761 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
762 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000763 if (Stream.SkipBlock()) {
764 Error("Malformed block record");
765 return Failure;
766 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000767 break;
768
Chris Lattner29241862009-04-11 21:15:38 +0000769 case pch::PREPROCESSOR_BLOCK_ID:
770 // Skip the preprocessor block for now, but remember where it is. We
771 // want to read it in after the identifier table.
772 if (PreprocessorBlockBit) {
773 Error("Multiple preprocessor blocks found.");
774 return Failure;
775 }
776 PreprocessorBlockBit = Stream.GetCurrentBitNo();
777 if (Stream.SkipBlock()) {
778 Error("Malformed block record");
779 return Failure;
780 }
781 break;
782
Douglas Gregorab1cef72009-04-10 03:52:48 +0000783 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000784 switch (ReadSourceManagerBlock()) {
785 case Success:
786 break;
787
788 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000789 Error("Malformed source manager block");
790 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000791
792 case IgnorePCH:
793 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000794 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000795 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000796 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000797 continue;
798 }
799
800 if (Code == llvm::bitc::DEFINE_ABBREV) {
801 Stream.ReadAbbrevRecord();
802 continue;
803 }
804
805 // Read and process a record.
806 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000807 const char *BlobStart = 0;
808 unsigned BlobLen = 0;
809 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
810 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000811 default: // Default behavior: ignore.
812 break;
813
814 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000815 if (!TypeOffsets.empty()) {
816 Error("Duplicate TYPE_OFFSET record in PCH file");
817 return Failure;
818 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000819 TypeOffsets.swap(Record);
820 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
821 break;
822
823 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000824 if (!DeclOffsets.empty()) {
825 Error("Duplicate DECL_OFFSET record in PCH file");
826 return Failure;
827 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000828 DeclOffsets.swap(Record);
829 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
830 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000831
832 case pch::LANGUAGE_OPTIONS:
833 if (ParseLanguageOptions(Record))
834 return IgnorePCH;
835 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000836
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000837 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000838 std::string TargetTriple(BlobStart, BlobLen);
839 if (TargetTriple != Context.Target.getTargetTriple()) {
840 Diag(diag::warn_pch_target_triple)
841 << TargetTriple << Context.Target.getTargetTriple();
842 Diag(diag::note_ignoring_pch) << FileName;
843 return IgnorePCH;
844 }
845 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000846 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000847
848 case pch::IDENTIFIER_TABLE:
849 IdentifierTable = BlobStart;
850 break;
851
852 case pch::IDENTIFIER_OFFSET:
853 if (!IdentifierData.empty()) {
854 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
855 return Failure;
856 }
857 IdentifierData.swap(Record);
858#ifndef NDEBUG
859 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
860 if ((IdentifierData[I] & 0x01) == 0) {
861 Error("Malformed identifier table in the precompiled header");
862 return Failure;
863 }
864 }
865#endif
866 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000867
868 case pch::EXTERNAL_DEFINITIONS:
869 if (!ExternalDefinitions.empty()) {
870 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
871 return Failure;
872 }
873 ExternalDefinitions.swap(Record);
874 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000875 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000876 }
877
Douglas Gregor179cfb12009-04-10 20:39:37 +0000878 Error("Premature end of bitstream");
879 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000880}
881
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000882PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000883 // Set the PCH file name.
884 this->FileName = FileName;
885
Douglas Gregorc34897d2009-04-09 22:27:44 +0000886 // Open the PCH file.
887 std::string ErrStr;
888 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000889 if (!Buffer) {
890 Error(ErrStr.c_str());
891 return IgnorePCH;
892 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000893
894 // Initialize the stream
895 Stream.init((const unsigned char *)Buffer->getBufferStart(),
896 (const unsigned char *)Buffer->getBufferEnd());
897
898 // Sniff for the signature.
899 if (Stream.Read(8) != 'C' ||
900 Stream.Read(8) != 'P' ||
901 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000902 Stream.Read(8) != 'H') {
903 Error("Not a PCH file");
904 return IgnorePCH;
905 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000906
907 // We expect a number of well-defined blocks, though we don't necessarily
908 // need to understand them all.
909 while (!Stream.AtEndOfStream()) {
910 unsigned Code = Stream.ReadCode();
911
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000912 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
913 Error("Invalid record at top-level");
914 return Failure;
915 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000916
917 unsigned BlockID = Stream.ReadSubBlockID();
918
919 // We only know the PCH subblock ID.
920 switch (BlockID) {
921 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000922 if (Stream.ReadBlockInfoBlock()) {
923 Error("Malformed BlockInfoBlock");
924 return Failure;
925 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000926 break;
927 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000928 switch (ReadPCHBlock()) {
929 case Success:
930 break;
931
932 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000933 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000934
935 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000936 // FIXME: We could consider reading through to the end of this
937 // PCH block, skipping subblocks, to see if there are other
938 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000939 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000940 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000941 break;
942 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000943 if (Stream.SkipBlock()) {
944 Error("Malformed block record");
945 return Failure;
946 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000947 break;
948 }
949 }
950
951 // Load the translation unit declaration
952 ReadDeclRecord(DeclOffsets[0], 0);
953
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000954 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000955}
956
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000957namespace {
958 /// \brief Helper class that saves the current stream position and
959 /// then restores it when destroyed.
960 struct VISIBILITY_HIDDEN SavedStreamPosition {
961 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000962 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000963
964 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000965 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000966 }
967
968 private:
969 llvm::BitstreamReader &Stream;
970 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000971 };
972}
973
Douglas Gregor179cfb12009-04-10 20:39:37 +0000974/// \brief Parse the record that corresponds to a LangOptions data
975/// structure.
976///
977/// This routine compares the language options used to generate the
978/// PCH file against the language options set for the current
979/// compilation. For each option, we classify differences between the
980/// two compiler states as either "benign" or "important". Benign
981/// differences don't matter, and we accept them without complaint
982/// (and without modifying the language options). Differences between
983/// the states for important options cause the PCH file to be
984/// unusable, so we emit a warning and return true to indicate that
985/// there was an error.
986///
987/// \returns true if the PCH file is unacceptable, false otherwise.
988bool PCHReader::ParseLanguageOptions(
989 const llvm::SmallVectorImpl<uint64_t> &Record) {
990 const LangOptions &LangOpts = Context.getLangOptions();
991#define PARSE_LANGOPT_BENIGN(Option) ++Idx
992#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
993 if (Record[Idx] != LangOpts.Option) { \
994 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
995 Diag(diag::note_ignoring_pch) << FileName; \
996 return true; \
997 } \
998 ++Idx
999
1000 unsigned Idx = 0;
1001 PARSE_LANGOPT_BENIGN(Trigraphs);
1002 PARSE_LANGOPT_BENIGN(BCPLComment);
1003 PARSE_LANGOPT_BENIGN(DollarIdents);
1004 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1005 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1006 PARSE_LANGOPT_BENIGN(ImplicitInt);
1007 PARSE_LANGOPT_BENIGN(Digraphs);
1008 PARSE_LANGOPT_BENIGN(HexFloats);
1009 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1010 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1011 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1012 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1013 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1014 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1015 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1016 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1017 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1018 PARSE_LANGOPT_BENIGN(PascalStrings);
1019 PARSE_LANGOPT_BENIGN(Boolean);
1020 PARSE_LANGOPT_BENIGN(WritableStrings);
1021 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1022 diag::warn_pch_lax_vector_conversions);
1023 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1024 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1025 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1026 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1027 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1028 diag::warn_pch_thread_safe_statics);
1029 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1030 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1031 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1032 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1033 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1034 diag::warn_pch_heinous_extensions);
1035 // FIXME: Most of the options below are benign if the macro wasn't
1036 // used. Unfortunately, this means that a PCH compiled without
1037 // optimization can't be used with optimization turned on, even
1038 // though the only thing that changes is whether __OPTIMIZE__ was
1039 // defined... but if __OPTIMIZE__ never showed up in the header, it
1040 // doesn't matter. We could consider making this some special kind
1041 // of check.
1042 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1043 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1044 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1045 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1046 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1047 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1048 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1049 Diag(diag::warn_pch_gc_mode)
1050 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1051 Diag(diag::note_ignoring_pch) << FileName;
1052 return true;
1053 }
1054 ++Idx;
1055 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1056 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1057#undef PARSE_LANGOPT_IRRELEVANT
1058#undef PARSE_LANGOPT_BENIGN
1059
1060 return false;
1061}
1062
Douglas Gregorc34897d2009-04-09 22:27:44 +00001063/// \brief Read and return the type at the given offset.
1064///
1065/// This routine actually reads the record corresponding to the type
1066/// at the given offset in the bitstream. It is a helper routine for
1067/// GetType, which deals with reading type IDs.
1068QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001069 // Keep track of where we are in the stream, then jump back there
1070 // after reading this type.
1071 SavedStreamPosition SavedPosition(Stream);
1072
Douglas Gregorc34897d2009-04-09 22:27:44 +00001073 Stream.JumpToBit(Offset);
1074 RecordData Record;
1075 unsigned Code = Stream.ReadCode();
1076 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001077 case pch::TYPE_EXT_QUAL:
1078 // FIXME: Deserialize ExtQualType
1079 assert(false && "Cannot deserialize qualified types yet");
1080 return QualType();
1081
Douglas Gregorc34897d2009-04-09 22:27:44 +00001082 case pch::TYPE_FIXED_WIDTH_INT: {
1083 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1084 return Context.getFixedWidthIntType(Record[0], Record[1]);
1085 }
1086
1087 case pch::TYPE_COMPLEX: {
1088 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1089 QualType ElemType = GetType(Record[0]);
1090 return Context.getComplexType(ElemType);
1091 }
1092
1093 case pch::TYPE_POINTER: {
1094 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1095 QualType PointeeType = GetType(Record[0]);
1096 return Context.getPointerType(PointeeType);
1097 }
1098
1099 case pch::TYPE_BLOCK_POINTER: {
1100 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1101 QualType PointeeType = GetType(Record[0]);
1102 return Context.getBlockPointerType(PointeeType);
1103 }
1104
1105 case pch::TYPE_LVALUE_REFERENCE: {
1106 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1107 QualType PointeeType = GetType(Record[0]);
1108 return Context.getLValueReferenceType(PointeeType);
1109 }
1110
1111 case pch::TYPE_RVALUE_REFERENCE: {
1112 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1113 QualType PointeeType = GetType(Record[0]);
1114 return Context.getRValueReferenceType(PointeeType);
1115 }
1116
1117 case pch::TYPE_MEMBER_POINTER: {
1118 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1119 QualType PointeeType = GetType(Record[0]);
1120 QualType ClassType = GetType(Record[1]);
1121 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1122 }
1123
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001124 case pch::TYPE_CONSTANT_ARRAY: {
1125 QualType ElementType = GetType(Record[0]);
1126 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1127 unsigned IndexTypeQuals = Record[2];
1128 unsigned Idx = 3;
1129 llvm::APInt Size = ReadAPInt(Record, Idx);
1130 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1131 }
1132
1133 case pch::TYPE_INCOMPLETE_ARRAY: {
1134 QualType ElementType = GetType(Record[0]);
1135 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1136 unsigned IndexTypeQuals = Record[2];
1137 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1138 }
1139
1140 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001141 QualType ElementType = GetType(Record[0]);
1142 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1143 unsigned IndexTypeQuals = Record[2];
1144 return Context.getVariableArrayType(ElementType, ReadExpr(),
1145 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001146 }
1147
1148 case pch::TYPE_VECTOR: {
1149 if (Record.size() != 2) {
1150 Error("Incorrect encoding of vector type in PCH file");
1151 return QualType();
1152 }
1153
1154 QualType ElementType = GetType(Record[0]);
1155 unsigned NumElements = Record[1];
1156 return Context.getVectorType(ElementType, NumElements);
1157 }
1158
1159 case pch::TYPE_EXT_VECTOR: {
1160 if (Record.size() != 2) {
1161 Error("Incorrect encoding of extended vector type in PCH file");
1162 return QualType();
1163 }
1164
1165 QualType ElementType = GetType(Record[0]);
1166 unsigned NumElements = Record[1];
1167 return Context.getExtVectorType(ElementType, NumElements);
1168 }
1169
1170 case pch::TYPE_FUNCTION_NO_PROTO: {
1171 if (Record.size() != 1) {
1172 Error("Incorrect encoding of no-proto function type");
1173 return QualType();
1174 }
1175 QualType ResultType = GetType(Record[0]);
1176 return Context.getFunctionNoProtoType(ResultType);
1177 }
1178
1179 case pch::TYPE_FUNCTION_PROTO: {
1180 QualType ResultType = GetType(Record[0]);
1181 unsigned Idx = 1;
1182 unsigned NumParams = Record[Idx++];
1183 llvm::SmallVector<QualType, 16> ParamTypes;
1184 for (unsigned I = 0; I != NumParams; ++I)
1185 ParamTypes.push_back(GetType(Record[Idx++]));
1186 bool isVariadic = Record[Idx++];
1187 unsigned Quals = Record[Idx++];
1188 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1189 isVariadic, Quals);
1190 }
1191
1192 case pch::TYPE_TYPEDEF:
1193 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1194 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1195
1196 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001197 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001198
1199 case pch::TYPE_TYPEOF: {
1200 if (Record.size() != 1) {
1201 Error("Incorrect encoding of typeof(type) in PCH file");
1202 return QualType();
1203 }
1204 QualType UnderlyingType = GetType(Record[0]);
1205 return Context.getTypeOfType(UnderlyingType);
1206 }
1207
1208 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001209 assert(Record.size() == 1 && "Incorrect encoding of record type");
1210 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001211
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001212 case pch::TYPE_ENUM:
1213 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1214 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1215
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001216 case pch::TYPE_OBJC_INTERFACE:
1217 // FIXME: Deserialize ObjCInterfaceType
1218 assert(false && "Cannot de-serialize ObjC interface types yet");
1219 return QualType();
1220
1221 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1222 // FIXME: Deserialize ObjCQualifiedInterfaceType
1223 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1224 return QualType();
1225
1226 case pch::TYPE_OBJC_QUALIFIED_ID:
1227 // FIXME: Deserialize ObjCQualifiedIdType
1228 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1229 return QualType();
1230
1231 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1232 // FIXME: Deserialize ObjCQualifiedClassType
1233 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1234 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001235 }
1236
1237 // Suppress a GCC warning
1238 return QualType();
1239}
1240
1241/// \brief Note that we have loaded the declaration with the given
1242/// Index.
1243///
1244/// This routine notes that this declaration has already been loaded,
1245/// so that future GetDecl calls will return this declaration rather
1246/// than trying to load a new declaration.
1247inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1248 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1249 DeclAlreadyLoaded[Index] = true;
1250 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1251}
1252
1253/// \brief Read the declaration at the given offset from the PCH file.
1254Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001255 // Keep track of where we are in the stream, then jump back there
1256 // after reading this declaration.
1257 SavedStreamPosition SavedPosition(Stream);
1258
Douglas Gregorc34897d2009-04-09 22:27:44 +00001259 Decl *D = 0;
1260 Stream.JumpToBit(Offset);
1261 RecordData Record;
1262 unsigned Code = Stream.ReadCode();
1263 unsigned Idx = 0;
1264 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001265
Douglas Gregorc34897d2009-04-09 22:27:44 +00001266 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1267 case pch::DECL_TRANSLATION_UNIT:
1268 assert(Index == 0 && "Translation unit must be at index 0");
1269 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1270 D = Context.getTranslationUnitDecl();
1271 LoadedDecl(Index, D);
1272 break;
1273
1274 case pch::DECL_TYPEDEF: {
1275 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1276 0, QualType());
1277 LoadedDecl(Index, Typedef);
1278 Reader.VisitTypedefDecl(Typedef);
1279 D = Typedef;
1280 break;
1281 }
1282
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001283 case pch::DECL_ENUM: {
1284 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1285 LoadedDecl(Index, Enum);
1286 Reader.VisitEnumDecl(Enum);
1287 D = Enum;
1288 break;
1289 }
1290
Douglas Gregor982365e2009-04-13 21:20:57 +00001291 case pch::DECL_RECORD: {
1292 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1293 0, SourceLocation(), 0, 0);
1294 LoadedDecl(Index, Record);
1295 Reader.VisitRecordDecl(Record);
1296 D = Record;
1297 break;
1298 }
1299
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001300 case pch::DECL_ENUM_CONSTANT: {
1301 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1302 SourceLocation(), 0,
1303 QualType(), 0,
1304 llvm::APSInt());
1305 LoadedDecl(Index, ECD);
1306 Reader.VisitEnumConstantDecl(ECD);
1307 D = ECD;
1308 break;
1309 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001310
1311 case pch::DECL_FUNCTION: {
1312 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1313 DeclarationName(),
1314 QualType());
1315 LoadedDecl(Index, Function);
1316 Reader.VisitFunctionDecl(Function);
1317 D = Function;
1318 break;
1319 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001320
Douglas Gregor982365e2009-04-13 21:20:57 +00001321 case pch::DECL_FIELD: {
1322 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1323 QualType(), 0, false);
1324 LoadedDecl(Index, Field);
1325 Reader.VisitFieldDecl(Field);
1326 D = Field;
1327 break;
1328 }
1329
Douglas Gregorc34897d2009-04-09 22:27:44 +00001330 case pch::DECL_VAR: {
1331 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1332 VarDecl::None, SourceLocation());
1333 LoadedDecl(Index, Var);
1334 Reader.VisitVarDecl(Var);
1335 D = Var;
1336 break;
1337 }
1338
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001339 case pch::DECL_PARM_VAR: {
1340 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1341 QualType(), VarDecl::None, 0);
1342 LoadedDecl(Index, Parm);
1343 Reader.VisitParmVarDecl(Parm);
1344 D = Parm;
1345 break;
1346 }
1347
1348 case pch::DECL_ORIGINAL_PARM_VAR: {
1349 OriginalParmVarDecl *Parm
1350 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1351 QualType(), QualType(), VarDecl::None,
1352 0);
1353 LoadedDecl(Index, Parm);
1354 Reader.VisitOriginalParmVarDecl(Parm);
1355 D = Parm;
1356 break;
1357 }
1358
Douglas Gregor2a491792009-04-13 22:49:25 +00001359 case pch::DECL_FILE_SCOPE_ASM: {
1360 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1361 SourceLocation(), 0);
1362 LoadedDecl(Index, Asm);
1363 Reader.VisitFileScopeAsmDecl(Asm);
1364 D = Asm;
1365 break;
1366 }
1367
1368 case pch::DECL_BLOCK: {
1369 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1370 LoadedDecl(Index, Block);
1371 Reader.VisitBlockDecl(Block);
1372 D = Block;
1373 break;
1374 }
1375
Douglas Gregorc34897d2009-04-09 22:27:44 +00001376 default:
1377 assert(false && "Cannot de-serialize this kind of declaration");
1378 break;
1379 }
1380
1381 // If this declaration is also a declaration context, get the
1382 // offsets for its tables of lexical and visible declarations.
1383 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1384 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1385 if (Offsets.first || Offsets.second) {
1386 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1387 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1388 DeclContextOffsets[DC] = Offsets;
1389 }
1390 }
1391 assert(Idx == Record.size());
1392
1393 return D;
1394}
1395
Douglas Gregorac8f2802009-04-10 17:25:41 +00001396QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001397 unsigned Quals = ID & 0x07;
1398 unsigned Index = ID >> 3;
1399
1400 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1401 QualType T;
1402 switch ((pch::PredefinedTypeIDs)Index) {
1403 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1404 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1405 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1406
1407 case pch::PREDEF_TYPE_CHAR_U_ID:
1408 case pch::PREDEF_TYPE_CHAR_S_ID:
1409 // FIXME: Check that the signedness of CharTy is correct!
1410 T = Context.CharTy;
1411 break;
1412
1413 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1414 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1415 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1416 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1417 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1418 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1419 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1420 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1421 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1422 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1423 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1424 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1425 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1426 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1427 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1428 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1429 }
1430
1431 assert(!T.isNull() && "Unknown predefined type");
1432 return T.getQualifiedType(Quals);
1433 }
1434
1435 Index -= pch::NUM_PREDEF_TYPE_IDS;
1436 if (!TypeAlreadyLoaded[Index]) {
1437 // Load the type from the PCH file.
1438 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1439 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1440 TypeAlreadyLoaded[Index] = true;
1441 }
1442
1443 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1444}
1445
Douglas Gregorac8f2802009-04-10 17:25:41 +00001446Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001447 if (ID == 0)
1448 return 0;
1449
1450 unsigned Index = ID - 1;
1451 if (DeclAlreadyLoaded[Index])
1452 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1453
1454 // Load the declaration from the PCH file.
1455 return ReadDeclRecord(DeclOffsets[Index], Index);
1456}
1457
1458bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001459 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001460 assert(DC->hasExternalLexicalStorage() &&
1461 "DeclContext has no lexical decls in storage");
1462 uint64_t Offset = DeclContextOffsets[DC].first;
1463 assert(Offset && "DeclContext has no lexical decls in storage");
1464
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001465 // Keep track of where we are in the stream, then jump back there
1466 // after reading this context.
1467 SavedStreamPosition SavedPosition(Stream);
1468
Douglas Gregorc34897d2009-04-09 22:27:44 +00001469 // Load the record containing all of the declarations lexically in
1470 // this context.
1471 Stream.JumpToBit(Offset);
1472 RecordData Record;
1473 unsigned Code = Stream.ReadCode();
1474 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001475 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001476 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1477
1478 // Load all of the declaration IDs
1479 Decls.clear();
1480 Decls.insert(Decls.end(), Record.begin(), Record.end());
1481 return false;
1482}
1483
1484bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1485 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1486 assert(DC->hasExternalVisibleStorage() &&
1487 "DeclContext has no visible decls in storage");
1488 uint64_t Offset = DeclContextOffsets[DC].second;
1489 assert(Offset && "DeclContext has no visible decls in storage");
1490
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001491 // Keep track of where we are in the stream, then jump back there
1492 // after reading this context.
1493 SavedStreamPosition SavedPosition(Stream);
1494
Douglas Gregorc34897d2009-04-09 22:27:44 +00001495 // Load the record containing all of the declarations visible in
1496 // this context.
1497 Stream.JumpToBit(Offset);
1498 RecordData Record;
1499 unsigned Code = Stream.ReadCode();
1500 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001501 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001502 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1503 if (Record.size() == 0)
1504 return false;
1505
1506 Decls.clear();
1507
1508 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001509 while (Idx < Record.size()) {
1510 Decls.push_back(VisibleDeclaration());
1511 Decls.back().Name = ReadDeclarationName(Record, Idx);
1512
Douglas Gregorc34897d2009-04-09 22:27:44 +00001513 unsigned Size = Record[Idx++];
1514 llvm::SmallVector<unsigned, 4> & LoadedDecls
1515 = Decls.back().Declarations;
1516 LoadedDecls.reserve(Size);
1517 for (unsigned I = 0; I < Size; ++I)
1518 LoadedDecls.push_back(Record[Idx++]);
1519 }
1520
1521 return false;
1522}
1523
Douglas Gregor631f6c62009-04-14 00:24:19 +00001524void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1525 if (!Consumer)
1526 return;
1527
1528 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1529 Decl *D = GetDecl(ExternalDefinitions[I]);
1530 DeclGroupRef DG(D);
1531 Consumer->HandleTopLevelDecl(DG);
1532 }
1533}
1534
Douglas Gregorc34897d2009-04-09 22:27:44 +00001535void PCHReader::PrintStats() {
1536 std::fprintf(stderr, "*** PCH Statistics:\n");
1537
1538 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1539 TypeAlreadyLoaded.end(),
1540 true);
1541 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1542 DeclAlreadyLoaded.end(),
1543 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001544 unsigned NumIdentifiersLoaded = 0;
1545 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1546 if ((IdentifierData[I] & 0x01) == 0)
1547 ++NumIdentifiersLoaded;
1548 }
1549
Douglas Gregorc34897d2009-04-09 22:27:44 +00001550 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1551 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001552 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001553 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1554 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001555 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1556 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1557 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1558 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001559 std::fprintf(stderr, "\n");
1560}
1561
Chris Lattner29241862009-04-11 21:15:38 +00001562IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001563 if (ID == 0)
1564 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001565
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001566 if (!IdentifierTable || IdentifierData.empty()) {
1567 Error("No identifier table in PCH file");
1568 return 0;
1569 }
Chris Lattner29241862009-04-11 21:15:38 +00001570
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001571 if (IdentifierData[ID - 1] & 0x01) {
1572 uint64_t Offset = IdentifierData[ID - 1];
1573 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001574 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001575 }
Chris Lattner29241862009-04-11 21:15:38 +00001576
1577 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001578}
1579
1580DeclarationName
1581PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1582 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1583 switch (Kind) {
1584 case DeclarationName::Identifier:
1585 return DeclarationName(GetIdentifierInfo(Record, Idx));
1586
1587 case DeclarationName::ObjCZeroArgSelector:
1588 case DeclarationName::ObjCOneArgSelector:
1589 case DeclarationName::ObjCMultiArgSelector:
1590 assert(false && "Unable to de-serialize Objective-C selectors");
1591 break;
1592
1593 case DeclarationName::CXXConstructorName:
1594 return Context.DeclarationNames.getCXXConstructorName(
1595 GetType(Record[Idx++]));
1596
1597 case DeclarationName::CXXDestructorName:
1598 return Context.DeclarationNames.getCXXDestructorName(
1599 GetType(Record[Idx++]));
1600
1601 case DeclarationName::CXXConversionFunctionName:
1602 return Context.DeclarationNames.getCXXConversionFunctionName(
1603 GetType(Record[Idx++]));
1604
1605 case DeclarationName::CXXOperatorName:
1606 return Context.DeclarationNames.getCXXOperatorName(
1607 (OverloadedOperatorKind)Record[Idx++]);
1608
1609 case DeclarationName::CXXUsingDirective:
1610 return DeclarationName::getUsingDirectiveName();
1611 }
1612
1613 // Required to silence GCC warning
1614 return DeclarationName();
1615}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001616
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001617/// \brief Read an integral value
1618llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1619 unsigned BitWidth = Record[Idx++];
1620 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1621 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1622 Idx += NumWords;
1623 return Result;
1624}
1625
1626/// \brief Read a signed integral value
1627llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1628 bool isUnsigned = Record[Idx++];
1629 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1630}
1631
Douglas Gregore2f37202009-04-14 21:55:33 +00001632/// \brief Read a floating-point value
1633llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1634 // FIXME: is this really correct?
1635 return llvm::APFloat(ReadAPInt(Record, Idx));
1636}
1637
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001638Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001639 // Within the bitstream, expressions are stored in Reverse Polish
1640 // Notation, with each of the subexpressions preceding the
1641 // expression they are stored in. To evaluate expressions, we
1642 // continue reading expressions and placing them on the stack, with
1643 // expressions having operands removing those operands from the
1644 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1645 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001646 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001647 unsigned Idx;
1648 llvm::SmallVector<Expr *, 16> ExprStack;
1649 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001650 Stmt::EmptyShell Empty;
1651
Douglas Gregora151ba42009-04-14 23:32:43 +00001652 while (true) {
1653 unsigned Code = Stream.ReadCode();
1654 if (Code == llvm::bitc::END_BLOCK) {
1655 if (Stream.ReadBlockEnd()) {
1656 Error("Error at end of Source Manager block");
1657 return 0;
1658 }
1659 break;
1660 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001661
Douglas Gregora151ba42009-04-14 23:32:43 +00001662 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1663 // No known subblocks, always skip them.
1664 Stream.ReadSubBlockID();
1665 if (Stream.SkipBlock()) {
1666 Error("Malformed block record");
1667 return 0;
1668 }
1669 continue;
1670 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001671
Douglas Gregora151ba42009-04-14 23:32:43 +00001672 if (Code == llvm::bitc::DEFINE_ABBREV) {
1673 Stream.ReadAbbrevRecord();
1674 continue;
1675 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001676
Douglas Gregora151ba42009-04-14 23:32:43 +00001677 Expr *E = 0;
1678 Idx = 0;
1679 Record.clear();
1680 bool Finished = false;
1681 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1682 case pch::EXPR_STOP:
1683 Finished = true;
1684 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001685
Douglas Gregora151ba42009-04-14 23:32:43 +00001686 case pch::EXPR_NULL:
1687 E = 0;
1688 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001689
Douglas Gregora151ba42009-04-14 23:32:43 +00001690 case pch::EXPR_PREDEFINED:
1691 // FIXME: untested (until we can serialize function bodies).
1692 E = new (Context) PredefinedExpr(Empty);
1693 break;
1694
1695 case pch::EXPR_DECL_REF:
1696 E = new (Context) DeclRefExpr(Empty);
1697 break;
1698
1699 case pch::EXPR_INTEGER_LITERAL:
1700 E = new (Context) IntegerLiteral(Empty);
1701 break;
1702
1703 case pch::EXPR_FLOATING_LITERAL:
1704 E = new (Context) FloatingLiteral(Empty);
1705 break;
1706
Douglas Gregor596e0932009-04-15 16:35:07 +00001707 case pch::EXPR_STRING_LITERAL:
1708 E = StringLiteral::CreateEmpty(Context,
1709 Record[PCHStmtReader::NumExprFields + 1]);
1710 break;
1711
Douglas Gregora151ba42009-04-14 23:32:43 +00001712 case pch::EXPR_CHARACTER_LITERAL:
1713 E = new (Context) CharacterLiteral(Empty);
1714 break;
1715
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001716 case pch::EXPR_PAREN:
1717 E = new (Context) ParenExpr(Empty);
1718 break;
1719
Douglas Gregor12d74052009-04-15 15:58:59 +00001720 case pch::EXPR_UNARY_OPERATOR:
1721 E = new (Context) UnaryOperator(Empty);
1722 break;
1723
1724 case pch::EXPR_SIZEOF_ALIGN_OF:
1725 E = new (Context) SizeOfAlignOfExpr(Empty);
1726 break;
1727
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00001728 case pch::EXPR_CALL:
1729 E = new (Context) CallExpr(Context, Empty);
1730 break;
1731
1732 case pch::EXPR_MEMBER:
1733 E = new (Context) MemberExpr(Empty);
1734 break;
1735
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001736 case pch::EXPR_BINARY_OPERATOR:
1737 E = new (Context) BinaryOperator(Empty);
1738 break;
1739
Douglas Gregora151ba42009-04-14 23:32:43 +00001740 case pch::EXPR_IMPLICIT_CAST:
1741 E = new (Context) ImplicitCastExpr(Empty);
1742 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001743
1744 case pch::EXPR_CSTYLE_CAST:
1745 E = new (Context) CStyleCastExpr(Empty);
1746 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001747 }
1748
1749 // We hit an EXPR_STOP, so we're done with this expression.
1750 if (Finished)
1751 break;
1752
1753 if (E) {
1754 unsigned NumSubExprs = Reader.Visit(E);
1755 while (NumSubExprs > 0) {
1756 ExprStack.pop_back();
1757 --NumSubExprs;
1758 }
1759 }
1760
1761 assert(Idx == Record.size() && "Invalid deserialization of expression");
1762 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001763 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001764 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1765 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001766}
1767
Douglas Gregor179cfb12009-04-10 20:39:37 +00001768DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001769 return Diag(SourceLocation(), DiagID);
1770}
1771
1772DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1773 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001774 Context.getSourceManager()),
1775 DiagID);
1776}