blob: 083d0d6082ddc4218e0f3b7c648a57e39b57ea55 [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 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 Gregorb3a04c82009-04-10 23:10:45 +0000596 llvm::MemoryBuffer *Buffer
597 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
598 BlobStart + BlobLen - 1,
599 Name);
600 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
601
602 if (strcmp(Name, "<built-in>") == 0
603 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
604 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000605 break;
606 }
607
608 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
609 SourceLocation SpellingLoc
610 = SourceLocation::getFromRawEncoding(Record[1]);
611 SourceMgr.createInstantiationLoc(
612 SpellingLoc,
613 SourceLocation::getFromRawEncoding(Record[2]),
614 SourceLocation::getFromRawEncoding(Record[3]),
615 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000616 SourceMgr,
617 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000618 break;
619 }
620
Chris Lattnere1be6022009-04-14 23:22:57 +0000621 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000622 if (ParseLineTable(SourceMgr, Record))
623 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000624 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000625 }
626 }
627}
628
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000629bool PCHReader::ReadPreprocessorBlock() {
630 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
631 return Error("Malformed preprocessor block record");
632
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000633 RecordData Record;
634 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
635 MacroInfo *LastMacro = 0;
636
637 while (true) {
638 unsigned Code = Stream.ReadCode();
639 switch (Code) {
640 case llvm::bitc::END_BLOCK:
641 if (Stream.ReadBlockEnd())
642 return Error("Error at end of preprocessor block");
643 return false;
644
645 case llvm::bitc::ENTER_SUBBLOCK:
646 // No known subblocks, always skip them.
647 Stream.ReadSubBlockID();
648 if (Stream.SkipBlock())
649 return Error("Malformed block record");
650 continue;
651
652 case llvm::bitc::DEFINE_ABBREV:
653 Stream.ReadAbbrevRecord();
654 continue;
655 default: break;
656 }
657
658 // Read a record.
659 Record.clear();
660 pch::PreprocessorRecordTypes RecType =
661 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
662 switch (RecType) {
663 default: // Default behavior: ignore unknown records.
664 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000665 case pch::PP_COUNTER_VALUE:
666 if (!Record.empty())
667 PP.setCounterValue(Record[0]);
668 break;
669
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000670 case pch::PP_MACRO_OBJECT_LIKE:
671 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000672 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
673 if (II == 0)
674 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000675 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
676 bool isUsed = Record[2];
677
678 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
679 MI->setIsUsed(isUsed);
680
681 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
682 // Decode function-like macro info.
683 bool isC99VarArgs = Record[3];
684 bool isGNUVarArgs = Record[4];
685 MacroArgs.clear();
686 unsigned NumArgs = Record[5];
687 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000688 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000689
690 // Install function-like macro info.
691 MI->setIsFunctionLike();
692 if (isC99VarArgs) MI->setIsC99Varargs();
693 if (isGNUVarArgs) MI->setIsGNUVarargs();
694 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
695 PP.getPreprocessorAllocator());
696 }
697
698 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000699 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000700
701 // Remember that we saw this macro last so that we add the tokens that
702 // form its body to it.
703 LastMacro = MI;
704 break;
705 }
706
707 case pch::PP_TOKEN: {
708 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
709 // pretend we didn't see this.
710 if (LastMacro == 0) break;
711
712 Token Tok;
713 Tok.startToken();
714 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
715 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000716 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
717 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000718 Tok.setKind((tok::TokenKind)Record[3]);
719 Tok.setFlag((Token::TokenFlags)Record[4]);
720 LastMacro->AddTokenToBody(Tok);
721 break;
722 }
723 }
724 }
725}
726
Douglas Gregor179cfb12009-04-10 20:39:37 +0000727PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
728 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
729 Error("Malformed block record");
730 return Failure;
731 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000732
Chris Lattner29241862009-04-11 21:15:38 +0000733 uint64_t PreprocessorBlockBit = 0;
734
Douglas Gregorc34897d2009-04-09 22:27:44 +0000735 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000736 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000737 while (!Stream.AtEndOfStream()) {
738 unsigned Code = Stream.ReadCode();
739 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000740 // If we saw the preprocessor block, read it now.
741 if (PreprocessorBlockBit) {
742 uint64_t SavedPos = Stream.GetCurrentBitNo();
743 Stream.JumpToBit(PreprocessorBlockBit);
744 if (ReadPreprocessorBlock()) {
745 Error("Malformed preprocessor block");
746 return Failure;
747 }
748 Stream.JumpToBit(SavedPos);
749 }
750
Douglas Gregor179cfb12009-04-10 20:39:37 +0000751 if (Stream.ReadBlockEnd()) {
752 Error("Error at end of module block");
753 return Failure;
754 }
Chris Lattner29241862009-04-11 21:15:38 +0000755
Douglas Gregor179cfb12009-04-10 20:39:37 +0000756 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000757 }
758
759 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
760 switch (Stream.ReadSubBlockID()) {
761 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
762 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
763 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000764 if (Stream.SkipBlock()) {
765 Error("Malformed block record");
766 return Failure;
767 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000768 break;
769
Chris Lattner29241862009-04-11 21:15:38 +0000770 case pch::PREPROCESSOR_BLOCK_ID:
771 // Skip the preprocessor block for now, but remember where it is. We
772 // want to read it in after the identifier table.
773 if (PreprocessorBlockBit) {
774 Error("Multiple preprocessor blocks found.");
775 return Failure;
776 }
777 PreprocessorBlockBit = Stream.GetCurrentBitNo();
778 if (Stream.SkipBlock()) {
779 Error("Malformed block record");
780 return Failure;
781 }
782 break;
783
Douglas Gregorab1cef72009-04-10 03:52:48 +0000784 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000785 switch (ReadSourceManagerBlock()) {
786 case Success:
787 break;
788
789 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000790 Error("Malformed source manager block");
791 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000792
793 case IgnorePCH:
794 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000795 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000796 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000797 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000798 continue;
799 }
800
801 if (Code == llvm::bitc::DEFINE_ABBREV) {
802 Stream.ReadAbbrevRecord();
803 continue;
804 }
805
806 // Read and process a record.
807 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000808 const char *BlobStart = 0;
809 unsigned BlobLen = 0;
810 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
811 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000812 default: // Default behavior: ignore.
813 break;
814
815 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000816 if (!TypeOffsets.empty()) {
817 Error("Duplicate TYPE_OFFSET record in PCH file");
818 return Failure;
819 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000820 TypeOffsets.swap(Record);
821 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
822 break;
823
824 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000825 if (!DeclOffsets.empty()) {
826 Error("Duplicate DECL_OFFSET record in PCH file");
827 return Failure;
828 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000829 DeclOffsets.swap(Record);
830 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
831 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000832
833 case pch::LANGUAGE_OPTIONS:
834 if (ParseLanguageOptions(Record))
835 return IgnorePCH;
836 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000837
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000838 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000839 std::string TargetTriple(BlobStart, BlobLen);
840 if (TargetTriple != Context.Target.getTargetTriple()) {
841 Diag(diag::warn_pch_target_triple)
842 << TargetTriple << Context.Target.getTargetTriple();
843 Diag(diag::note_ignoring_pch) << FileName;
844 return IgnorePCH;
845 }
846 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000847 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000848
849 case pch::IDENTIFIER_TABLE:
850 IdentifierTable = BlobStart;
851 break;
852
853 case pch::IDENTIFIER_OFFSET:
854 if (!IdentifierData.empty()) {
855 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
856 return Failure;
857 }
858 IdentifierData.swap(Record);
859#ifndef NDEBUG
860 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
861 if ((IdentifierData[I] & 0x01) == 0) {
862 Error("Malformed identifier table in the precompiled header");
863 return Failure;
864 }
865 }
866#endif
867 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000868
869 case pch::EXTERNAL_DEFINITIONS:
870 if (!ExternalDefinitions.empty()) {
871 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
872 return Failure;
873 }
874 ExternalDefinitions.swap(Record);
875 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000876 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000877 }
878
Douglas Gregor179cfb12009-04-10 20:39:37 +0000879 Error("Premature end of bitstream");
880 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000881}
882
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000883PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000884 // Set the PCH file name.
885 this->FileName = FileName;
886
Douglas Gregorc34897d2009-04-09 22:27:44 +0000887 // Open the PCH file.
888 std::string ErrStr;
889 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000890 if (!Buffer) {
891 Error(ErrStr.c_str());
892 return IgnorePCH;
893 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000894
895 // Initialize the stream
896 Stream.init((const unsigned char *)Buffer->getBufferStart(),
897 (const unsigned char *)Buffer->getBufferEnd());
898
899 // Sniff for the signature.
900 if (Stream.Read(8) != 'C' ||
901 Stream.Read(8) != 'P' ||
902 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000903 Stream.Read(8) != 'H') {
904 Error("Not a PCH file");
905 return IgnorePCH;
906 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000907
908 // We expect a number of well-defined blocks, though we don't necessarily
909 // need to understand them all.
910 while (!Stream.AtEndOfStream()) {
911 unsigned Code = Stream.ReadCode();
912
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000913 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
914 Error("Invalid record at top-level");
915 return Failure;
916 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000917
918 unsigned BlockID = Stream.ReadSubBlockID();
919
920 // We only know the PCH subblock ID.
921 switch (BlockID) {
922 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000923 if (Stream.ReadBlockInfoBlock()) {
924 Error("Malformed BlockInfoBlock");
925 return Failure;
926 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000927 break;
928 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000929 switch (ReadPCHBlock()) {
930 case Success:
931 break;
932
933 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000934 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000935
936 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000937 // FIXME: We could consider reading through to the end of this
938 // PCH block, skipping subblocks, to see if there are other
939 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000940 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000941 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000942 break;
943 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000944 if (Stream.SkipBlock()) {
945 Error("Malformed block record");
946 return Failure;
947 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000948 break;
949 }
950 }
951
952 // Load the translation unit declaration
953 ReadDeclRecord(DeclOffsets[0], 0);
954
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000955 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000956}
957
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000958namespace {
959 /// \brief Helper class that saves the current stream position and
960 /// then restores it when destroyed.
961 struct VISIBILITY_HIDDEN SavedStreamPosition {
962 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000963 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000964
965 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000966 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000967 }
968
969 private:
970 llvm::BitstreamReader &Stream;
971 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000972 };
973}
974
Douglas Gregor179cfb12009-04-10 20:39:37 +0000975/// \brief Parse the record that corresponds to a LangOptions data
976/// structure.
977///
978/// This routine compares the language options used to generate the
979/// PCH file against the language options set for the current
980/// compilation. For each option, we classify differences between the
981/// two compiler states as either "benign" or "important". Benign
982/// differences don't matter, and we accept them without complaint
983/// (and without modifying the language options). Differences between
984/// the states for important options cause the PCH file to be
985/// unusable, so we emit a warning and return true to indicate that
986/// there was an error.
987///
988/// \returns true if the PCH file is unacceptable, false otherwise.
989bool PCHReader::ParseLanguageOptions(
990 const llvm::SmallVectorImpl<uint64_t> &Record) {
991 const LangOptions &LangOpts = Context.getLangOptions();
992#define PARSE_LANGOPT_BENIGN(Option) ++Idx
993#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
994 if (Record[Idx] != LangOpts.Option) { \
995 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
996 Diag(diag::note_ignoring_pch) << FileName; \
997 return true; \
998 } \
999 ++Idx
1000
1001 unsigned Idx = 0;
1002 PARSE_LANGOPT_BENIGN(Trigraphs);
1003 PARSE_LANGOPT_BENIGN(BCPLComment);
1004 PARSE_LANGOPT_BENIGN(DollarIdents);
1005 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1006 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1007 PARSE_LANGOPT_BENIGN(ImplicitInt);
1008 PARSE_LANGOPT_BENIGN(Digraphs);
1009 PARSE_LANGOPT_BENIGN(HexFloats);
1010 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1011 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1012 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1013 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1014 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1015 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1016 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1017 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1018 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1019 PARSE_LANGOPT_BENIGN(PascalStrings);
1020 PARSE_LANGOPT_BENIGN(Boolean);
1021 PARSE_LANGOPT_BENIGN(WritableStrings);
1022 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1023 diag::warn_pch_lax_vector_conversions);
1024 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1025 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1026 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1027 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1028 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1029 diag::warn_pch_thread_safe_statics);
1030 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1031 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1032 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1033 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1034 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1035 diag::warn_pch_heinous_extensions);
1036 // FIXME: Most of the options below are benign if the macro wasn't
1037 // used. Unfortunately, this means that a PCH compiled without
1038 // optimization can't be used with optimization turned on, even
1039 // though the only thing that changes is whether __OPTIMIZE__ was
1040 // defined... but if __OPTIMIZE__ never showed up in the header, it
1041 // doesn't matter. We could consider making this some special kind
1042 // of check.
1043 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1044 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1045 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1046 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1047 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1048 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1049 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1050 Diag(diag::warn_pch_gc_mode)
1051 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1052 Diag(diag::note_ignoring_pch) << FileName;
1053 return true;
1054 }
1055 ++Idx;
1056 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1057 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1058#undef PARSE_LANGOPT_IRRELEVANT
1059#undef PARSE_LANGOPT_BENIGN
1060
1061 return false;
1062}
1063
Douglas Gregorc34897d2009-04-09 22:27:44 +00001064/// \brief Read and return the type at the given offset.
1065///
1066/// This routine actually reads the record corresponding to the type
1067/// at the given offset in the bitstream. It is a helper routine for
1068/// GetType, which deals with reading type IDs.
1069QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001070 // Keep track of where we are in the stream, then jump back there
1071 // after reading this type.
1072 SavedStreamPosition SavedPosition(Stream);
1073
Douglas Gregorc34897d2009-04-09 22:27:44 +00001074 Stream.JumpToBit(Offset);
1075 RecordData Record;
1076 unsigned Code = Stream.ReadCode();
1077 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001078 case pch::TYPE_EXT_QUAL:
1079 // FIXME: Deserialize ExtQualType
1080 assert(false && "Cannot deserialize qualified types yet");
1081 return QualType();
1082
Douglas Gregorc34897d2009-04-09 22:27:44 +00001083 case pch::TYPE_FIXED_WIDTH_INT: {
1084 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1085 return Context.getFixedWidthIntType(Record[0], Record[1]);
1086 }
1087
1088 case pch::TYPE_COMPLEX: {
1089 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1090 QualType ElemType = GetType(Record[0]);
1091 return Context.getComplexType(ElemType);
1092 }
1093
1094 case pch::TYPE_POINTER: {
1095 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1096 QualType PointeeType = GetType(Record[0]);
1097 return Context.getPointerType(PointeeType);
1098 }
1099
1100 case pch::TYPE_BLOCK_POINTER: {
1101 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1102 QualType PointeeType = GetType(Record[0]);
1103 return Context.getBlockPointerType(PointeeType);
1104 }
1105
1106 case pch::TYPE_LVALUE_REFERENCE: {
1107 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1108 QualType PointeeType = GetType(Record[0]);
1109 return Context.getLValueReferenceType(PointeeType);
1110 }
1111
1112 case pch::TYPE_RVALUE_REFERENCE: {
1113 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1114 QualType PointeeType = GetType(Record[0]);
1115 return Context.getRValueReferenceType(PointeeType);
1116 }
1117
1118 case pch::TYPE_MEMBER_POINTER: {
1119 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1120 QualType PointeeType = GetType(Record[0]);
1121 QualType ClassType = GetType(Record[1]);
1122 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1123 }
1124
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001125 case pch::TYPE_CONSTANT_ARRAY: {
1126 QualType ElementType = GetType(Record[0]);
1127 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1128 unsigned IndexTypeQuals = Record[2];
1129 unsigned Idx = 3;
1130 llvm::APInt Size = ReadAPInt(Record, Idx);
1131 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1132 }
1133
1134 case pch::TYPE_INCOMPLETE_ARRAY: {
1135 QualType ElementType = GetType(Record[0]);
1136 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1137 unsigned IndexTypeQuals = Record[2];
1138 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1139 }
1140
1141 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001142 QualType ElementType = GetType(Record[0]);
1143 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1144 unsigned IndexTypeQuals = Record[2];
1145 return Context.getVariableArrayType(ElementType, ReadExpr(),
1146 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001147 }
1148
1149 case pch::TYPE_VECTOR: {
1150 if (Record.size() != 2) {
1151 Error("Incorrect encoding of vector type in PCH file");
1152 return QualType();
1153 }
1154
1155 QualType ElementType = GetType(Record[0]);
1156 unsigned NumElements = Record[1];
1157 return Context.getVectorType(ElementType, NumElements);
1158 }
1159
1160 case pch::TYPE_EXT_VECTOR: {
1161 if (Record.size() != 2) {
1162 Error("Incorrect encoding of extended vector type in PCH file");
1163 return QualType();
1164 }
1165
1166 QualType ElementType = GetType(Record[0]);
1167 unsigned NumElements = Record[1];
1168 return Context.getExtVectorType(ElementType, NumElements);
1169 }
1170
1171 case pch::TYPE_FUNCTION_NO_PROTO: {
1172 if (Record.size() != 1) {
1173 Error("Incorrect encoding of no-proto function type");
1174 return QualType();
1175 }
1176 QualType ResultType = GetType(Record[0]);
1177 return Context.getFunctionNoProtoType(ResultType);
1178 }
1179
1180 case pch::TYPE_FUNCTION_PROTO: {
1181 QualType ResultType = GetType(Record[0]);
1182 unsigned Idx = 1;
1183 unsigned NumParams = Record[Idx++];
1184 llvm::SmallVector<QualType, 16> ParamTypes;
1185 for (unsigned I = 0; I != NumParams; ++I)
1186 ParamTypes.push_back(GetType(Record[Idx++]));
1187 bool isVariadic = Record[Idx++];
1188 unsigned Quals = Record[Idx++];
1189 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1190 isVariadic, Quals);
1191 }
1192
1193 case pch::TYPE_TYPEDEF:
1194 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1195 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1196
1197 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001198 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001199
1200 case pch::TYPE_TYPEOF: {
1201 if (Record.size() != 1) {
1202 Error("Incorrect encoding of typeof(type) in PCH file");
1203 return QualType();
1204 }
1205 QualType UnderlyingType = GetType(Record[0]);
1206 return Context.getTypeOfType(UnderlyingType);
1207 }
1208
1209 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001210 assert(Record.size() == 1 && "Incorrect encoding of record type");
1211 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001212
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001213 case pch::TYPE_ENUM:
1214 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1215 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1216
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001217 case pch::TYPE_OBJC_INTERFACE:
1218 // FIXME: Deserialize ObjCInterfaceType
1219 assert(false && "Cannot de-serialize ObjC interface types yet");
1220 return QualType();
1221
1222 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1223 // FIXME: Deserialize ObjCQualifiedInterfaceType
1224 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1225 return QualType();
1226
1227 case pch::TYPE_OBJC_QUALIFIED_ID:
1228 // FIXME: Deserialize ObjCQualifiedIdType
1229 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1230 return QualType();
1231
1232 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1233 // FIXME: Deserialize ObjCQualifiedClassType
1234 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1235 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001236 }
1237
1238 // Suppress a GCC warning
1239 return QualType();
1240}
1241
1242/// \brief Note that we have loaded the declaration with the given
1243/// Index.
1244///
1245/// This routine notes that this declaration has already been loaded,
1246/// so that future GetDecl calls will return this declaration rather
1247/// than trying to load a new declaration.
1248inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1249 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1250 DeclAlreadyLoaded[Index] = true;
1251 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1252}
1253
1254/// \brief Read the declaration at the given offset from the PCH file.
1255Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001256 // Keep track of where we are in the stream, then jump back there
1257 // after reading this declaration.
1258 SavedStreamPosition SavedPosition(Stream);
1259
Douglas Gregorc34897d2009-04-09 22:27:44 +00001260 Decl *D = 0;
1261 Stream.JumpToBit(Offset);
1262 RecordData Record;
1263 unsigned Code = Stream.ReadCode();
1264 unsigned Idx = 0;
1265 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001266
Douglas Gregorc34897d2009-04-09 22:27:44 +00001267 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1268 case pch::DECL_TRANSLATION_UNIT:
1269 assert(Index == 0 && "Translation unit must be at index 0");
1270 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1271 D = Context.getTranslationUnitDecl();
1272 LoadedDecl(Index, D);
1273 break;
1274
1275 case pch::DECL_TYPEDEF: {
1276 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1277 0, QualType());
1278 LoadedDecl(Index, Typedef);
1279 Reader.VisitTypedefDecl(Typedef);
1280 D = Typedef;
1281 break;
1282 }
1283
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001284 case pch::DECL_ENUM: {
1285 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1286 LoadedDecl(Index, Enum);
1287 Reader.VisitEnumDecl(Enum);
1288 D = Enum;
1289 break;
1290 }
1291
Douglas Gregor982365e2009-04-13 21:20:57 +00001292 case pch::DECL_RECORD: {
1293 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1294 0, SourceLocation(), 0, 0);
1295 LoadedDecl(Index, Record);
1296 Reader.VisitRecordDecl(Record);
1297 D = Record;
1298 break;
1299 }
1300
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001301 case pch::DECL_ENUM_CONSTANT: {
1302 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1303 SourceLocation(), 0,
1304 QualType(), 0,
1305 llvm::APSInt());
1306 LoadedDecl(Index, ECD);
1307 Reader.VisitEnumConstantDecl(ECD);
1308 D = ECD;
1309 break;
1310 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001311
1312 case pch::DECL_FUNCTION: {
1313 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1314 DeclarationName(),
1315 QualType());
1316 LoadedDecl(Index, Function);
1317 Reader.VisitFunctionDecl(Function);
1318 D = Function;
1319 break;
1320 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001321
Douglas Gregor982365e2009-04-13 21:20:57 +00001322 case pch::DECL_FIELD: {
1323 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1324 QualType(), 0, false);
1325 LoadedDecl(Index, Field);
1326 Reader.VisitFieldDecl(Field);
1327 D = Field;
1328 break;
1329 }
1330
Douglas Gregorc34897d2009-04-09 22:27:44 +00001331 case pch::DECL_VAR: {
1332 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1333 VarDecl::None, SourceLocation());
1334 LoadedDecl(Index, Var);
1335 Reader.VisitVarDecl(Var);
1336 D = Var;
1337 break;
1338 }
1339
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001340 case pch::DECL_PARM_VAR: {
1341 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1342 QualType(), VarDecl::None, 0);
1343 LoadedDecl(Index, Parm);
1344 Reader.VisitParmVarDecl(Parm);
1345 D = Parm;
1346 break;
1347 }
1348
1349 case pch::DECL_ORIGINAL_PARM_VAR: {
1350 OriginalParmVarDecl *Parm
1351 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1352 QualType(), QualType(), VarDecl::None,
1353 0);
1354 LoadedDecl(Index, Parm);
1355 Reader.VisitOriginalParmVarDecl(Parm);
1356 D = Parm;
1357 break;
1358 }
1359
Douglas Gregor2a491792009-04-13 22:49:25 +00001360 case pch::DECL_FILE_SCOPE_ASM: {
1361 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1362 SourceLocation(), 0);
1363 LoadedDecl(Index, Asm);
1364 Reader.VisitFileScopeAsmDecl(Asm);
1365 D = Asm;
1366 break;
1367 }
1368
1369 case pch::DECL_BLOCK: {
1370 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1371 LoadedDecl(Index, Block);
1372 Reader.VisitBlockDecl(Block);
1373 D = Block;
1374 break;
1375 }
1376
Douglas Gregorc34897d2009-04-09 22:27:44 +00001377 default:
1378 assert(false && "Cannot de-serialize this kind of declaration");
1379 break;
1380 }
1381
1382 // If this declaration is also a declaration context, get the
1383 // offsets for its tables of lexical and visible declarations.
1384 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1385 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1386 if (Offsets.first || Offsets.second) {
1387 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1388 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1389 DeclContextOffsets[DC] = Offsets;
1390 }
1391 }
1392 assert(Idx == Record.size());
1393
1394 return D;
1395}
1396
Douglas Gregorac8f2802009-04-10 17:25:41 +00001397QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001398 unsigned Quals = ID & 0x07;
1399 unsigned Index = ID >> 3;
1400
1401 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1402 QualType T;
1403 switch ((pch::PredefinedTypeIDs)Index) {
1404 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1405 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1406 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1407
1408 case pch::PREDEF_TYPE_CHAR_U_ID:
1409 case pch::PREDEF_TYPE_CHAR_S_ID:
1410 // FIXME: Check that the signedness of CharTy is correct!
1411 T = Context.CharTy;
1412 break;
1413
1414 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1415 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1416 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1417 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1418 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1419 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1420 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1421 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1422 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1423 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1424 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1425 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1426 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1427 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1428 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1429 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1430 }
1431
1432 assert(!T.isNull() && "Unknown predefined type");
1433 return T.getQualifiedType(Quals);
1434 }
1435
1436 Index -= pch::NUM_PREDEF_TYPE_IDS;
1437 if (!TypeAlreadyLoaded[Index]) {
1438 // Load the type from the PCH file.
1439 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1440 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1441 TypeAlreadyLoaded[Index] = true;
1442 }
1443
1444 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1445}
1446
Douglas Gregorac8f2802009-04-10 17:25:41 +00001447Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001448 if (ID == 0)
1449 return 0;
1450
1451 unsigned Index = ID - 1;
1452 if (DeclAlreadyLoaded[Index])
1453 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1454
1455 // Load the declaration from the PCH file.
1456 return ReadDeclRecord(DeclOffsets[Index], Index);
1457}
1458
1459bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001460 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001461 assert(DC->hasExternalLexicalStorage() &&
1462 "DeclContext has no lexical decls in storage");
1463 uint64_t Offset = DeclContextOffsets[DC].first;
1464 assert(Offset && "DeclContext has no lexical decls in storage");
1465
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001466 // Keep track of where we are in the stream, then jump back there
1467 // after reading this context.
1468 SavedStreamPosition SavedPosition(Stream);
1469
Douglas Gregorc34897d2009-04-09 22:27:44 +00001470 // Load the record containing all of the declarations lexically in
1471 // this context.
1472 Stream.JumpToBit(Offset);
1473 RecordData Record;
1474 unsigned Code = Stream.ReadCode();
1475 unsigned RecCode = Stream.ReadRecord(Code, Record);
1476 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);
1501 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1502 if (Record.size() == 0)
1503 return false;
1504
1505 Decls.clear();
1506
1507 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001508 while (Idx < Record.size()) {
1509 Decls.push_back(VisibleDeclaration());
1510 Decls.back().Name = ReadDeclarationName(Record, Idx);
1511
Douglas Gregorc34897d2009-04-09 22:27:44 +00001512 unsigned Size = Record[Idx++];
1513 llvm::SmallVector<unsigned, 4> & LoadedDecls
1514 = Decls.back().Declarations;
1515 LoadedDecls.reserve(Size);
1516 for (unsigned I = 0; I < Size; ++I)
1517 LoadedDecls.push_back(Record[Idx++]);
1518 }
1519
1520 return false;
1521}
1522
Douglas Gregor631f6c62009-04-14 00:24:19 +00001523void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1524 if (!Consumer)
1525 return;
1526
1527 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1528 Decl *D = GetDecl(ExternalDefinitions[I]);
1529 DeclGroupRef DG(D);
1530 Consumer->HandleTopLevelDecl(DG);
1531 }
1532}
1533
Douglas Gregorc34897d2009-04-09 22:27:44 +00001534void PCHReader::PrintStats() {
1535 std::fprintf(stderr, "*** PCH Statistics:\n");
1536
1537 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1538 TypeAlreadyLoaded.end(),
1539 true);
1540 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1541 DeclAlreadyLoaded.end(),
1542 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001543 unsigned NumIdentifiersLoaded = 0;
1544 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1545 if ((IdentifierData[I] & 0x01) == 0)
1546 ++NumIdentifiersLoaded;
1547 }
1548
Douglas Gregorc34897d2009-04-09 22:27:44 +00001549 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1550 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001551 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001552 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1553 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001554 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1555 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1556 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1557 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001558 std::fprintf(stderr, "\n");
1559}
1560
Chris Lattner29241862009-04-11 21:15:38 +00001561IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001562 if (ID == 0)
1563 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001564
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001565 if (!IdentifierTable || IdentifierData.empty()) {
1566 Error("No identifier table in PCH file");
1567 return 0;
1568 }
Chris Lattner29241862009-04-11 21:15:38 +00001569
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001570 if (IdentifierData[ID - 1] & 0x01) {
1571 uint64_t Offset = IdentifierData[ID - 1];
1572 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001573 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001574 }
Chris Lattner29241862009-04-11 21:15:38 +00001575
1576 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001577}
1578
1579DeclarationName
1580PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1581 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1582 switch (Kind) {
1583 case DeclarationName::Identifier:
1584 return DeclarationName(GetIdentifierInfo(Record, Idx));
1585
1586 case DeclarationName::ObjCZeroArgSelector:
1587 case DeclarationName::ObjCOneArgSelector:
1588 case DeclarationName::ObjCMultiArgSelector:
1589 assert(false && "Unable to de-serialize Objective-C selectors");
1590 break;
1591
1592 case DeclarationName::CXXConstructorName:
1593 return Context.DeclarationNames.getCXXConstructorName(
1594 GetType(Record[Idx++]));
1595
1596 case DeclarationName::CXXDestructorName:
1597 return Context.DeclarationNames.getCXXDestructorName(
1598 GetType(Record[Idx++]));
1599
1600 case DeclarationName::CXXConversionFunctionName:
1601 return Context.DeclarationNames.getCXXConversionFunctionName(
1602 GetType(Record[Idx++]));
1603
1604 case DeclarationName::CXXOperatorName:
1605 return Context.DeclarationNames.getCXXOperatorName(
1606 (OverloadedOperatorKind)Record[Idx++]);
1607
1608 case DeclarationName::CXXUsingDirective:
1609 return DeclarationName::getUsingDirectiveName();
1610 }
1611
1612 // Required to silence GCC warning
1613 return DeclarationName();
1614}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001615
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001616/// \brief Read an integral value
1617llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1618 unsigned BitWidth = Record[Idx++];
1619 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1620 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1621 Idx += NumWords;
1622 return Result;
1623}
1624
1625/// \brief Read a signed integral value
1626llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1627 bool isUnsigned = Record[Idx++];
1628 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1629}
1630
Douglas Gregore2f37202009-04-14 21:55:33 +00001631/// \brief Read a floating-point value
1632llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1633 // FIXME: is this really correct?
1634 return llvm::APFloat(ReadAPInt(Record, Idx));
1635}
1636
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001637Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001638 // Within the bitstream, expressions are stored in Reverse Polish
1639 // Notation, with each of the subexpressions preceding the
1640 // expression they are stored in. To evaluate expressions, we
1641 // continue reading expressions and placing them on the stack, with
1642 // expressions having operands removing those operands from the
1643 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1644 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001645 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001646 unsigned Idx;
1647 llvm::SmallVector<Expr *, 16> ExprStack;
1648 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001649 Stmt::EmptyShell Empty;
1650
Douglas Gregora151ba42009-04-14 23:32:43 +00001651 while (true) {
1652 unsigned Code = Stream.ReadCode();
1653 if (Code == llvm::bitc::END_BLOCK) {
1654 if (Stream.ReadBlockEnd()) {
1655 Error("Error at end of Source Manager block");
1656 return 0;
1657 }
1658 break;
1659 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001660
Douglas Gregora151ba42009-04-14 23:32:43 +00001661 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1662 // No known subblocks, always skip them.
1663 Stream.ReadSubBlockID();
1664 if (Stream.SkipBlock()) {
1665 Error("Malformed block record");
1666 return 0;
1667 }
1668 continue;
1669 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001670
Douglas Gregora151ba42009-04-14 23:32:43 +00001671 if (Code == llvm::bitc::DEFINE_ABBREV) {
1672 Stream.ReadAbbrevRecord();
1673 continue;
1674 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001675
Douglas Gregora151ba42009-04-14 23:32:43 +00001676 Expr *E = 0;
1677 Idx = 0;
1678 Record.clear();
1679 bool Finished = false;
1680 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1681 case pch::EXPR_STOP:
1682 Finished = true;
1683 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001684
Douglas Gregora151ba42009-04-14 23:32:43 +00001685 case pch::EXPR_NULL:
1686 E = 0;
1687 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001688
Douglas Gregora151ba42009-04-14 23:32:43 +00001689 case pch::EXPR_PREDEFINED:
1690 // FIXME: untested (until we can serialize function bodies).
1691 E = new (Context) PredefinedExpr(Empty);
1692 break;
1693
1694 case pch::EXPR_DECL_REF:
1695 E = new (Context) DeclRefExpr(Empty);
1696 break;
1697
1698 case pch::EXPR_INTEGER_LITERAL:
1699 E = new (Context) IntegerLiteral(Empty);
1700 break;
1701
1702 case pch::EXPR_FLOATING_LITERAL:
1703 E = new (Context) FloatingLiteral(Empty);
1704 break;
1705
Douglas Gregor596e0932009-04-15 16:35:07 +00001706 case pch::EXPR_STRING_LITERAL:
1707 E = StringLiteral::CreateEmpty(Context,
1708 Record[PCHStmtReader::NumExprFields + 1]);
1709 break;
1710
Douglas Gregora151ba42009-04-14 23:32:43 +00001711 case pch::EXPR_CHARACTER_LITERAL:
1712 E = new (Context) CharacterLiteral(Empty);
1713 break;
1714
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001715 case pch::EXPR_PAREN:
1716 E = new (Context) ParenExpr(Empty);
1717 break;
1718
Douglas Gregor12d74052009-04-15 15:58:59 +00001719 case pch::EXPR_UNARY_OPERATOR:
1720 E = new (Context) UnaryOperator(Empty);
1721 break;
1722
1723 case pch::EXPR_SIZEOF_ALIGN_OF:
1724 E = new (Context) SizeOfAlignOfExpr(Empty);
1725 break;
1726
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00001727 case pch::EXPR_CALL:
1728 E = new (Context) CallExpr(Context, Empty);
1729 break;
1730
1731 case pch::EXPR_MEMBER:
1732 E = new (Context) MemberExpr(Empty);
1733 break;
1734
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001735 case pch::EXPR_BINARY_OPERATOR:
1736 E = new (Context) BinaryOperator(Empty);
1737 break;
1738
Douglas Gregora151ba42009-04-14 23:32:43 +00001739 case pch::EXPR_IMPLICIT_CAST:
1740 E = new (Context) ImplicitCastExpr(Empty);
1741 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001742
1743 case pch::EXPR_CSTYLE_CAST:
1744 E = new (Context) CStyleCastExpr(Empty);
1745 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001746 }
1747
1748 // We hit an EXPR_STOP, so we're done with this expression.
1749 if (Finished)
1750 break;
1751
1752 if (E) {
1753 unsigned NumSubExprs = Reader.Visit(E);
1754 while (NumSubExprs > 0) {
1755 ExprStack.pop_back();
1756 --NumSubExprs;
1757 }
1758 }
1759
1760 assert(Idx == Record.size() && "Invalid deserialization of expression");
1761 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001762 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001763 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1764 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001765}
1766
Douglas Gregor179cfb12009-04-10 20:39:37 +00001767DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001768 return Diag(SourceLocation(), DiagID);
1769}
1770
1771DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1772 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001773 Context.getSourceManager()),
1774 DiagID);
1775}