blob: 042e56626e0522f0253e89835cac575301a098d7 [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++]);
Douglas Gregor1c507882009-04-15 21:30:51 +000077 if (Record[Idx++])
78 D->addAttr(Reader.ReadAttributes());
Douglas Gregorc34897d2009-04-09 22:27:44 +000079 D->setImplicit(Record[Idx++]);
80 D->setAccess((AccessSpecifier)Record[Idx++]);
81}
82
83void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
84 VisitDecl(TU);
85}
86
87void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
88 VisitDecl(ND);
89 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
90}
91
92void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
93 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000094 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
95}
96
97void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000098 // Note that we cannot use VisitTypeDecl here, because we need to
99 // set the underlying type of the typedef *before* we try to read
100 // the type associated with the TypedefDecl.
101 VisitNamedDecl(TD);
102 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
103 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
104 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000105}
106
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000107void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
108 VisitTypeDecl(TD);
109 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
110 TD->setDefinition(Record[Idx++]);
111 TD->setTypedefForAnonDecl(
112 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
113}
114
115void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
116 VisitTagDecl(ED);
117 ED->setIntegerType(Reader.GetType(Record[Idx++]));
118}
119
Douglas Gregor982365e2009-04-13 21:20:57 +0000120void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
121 VisitTagDecl(RD);
122 RD->setHasFlexibleArrayMember(Record[Idx++]);
123 RD->setAnonymousStructOrUnion(Record[Idx++]);
124}
125
Douglas Gregorc34897d2009-04-09 22:27:44 +0000126void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
127 VisitNamedDecl(VD);
128 VD->setType(Reader.GetType(Record[Idx++]));
129}
130
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000131void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
132 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000133 if (Record[Idx++])
134 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000135 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
136}
137
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000138void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
139 VisitValueDecl(FD);
140 // FIXME: function body
141 FD->setPreviousDeclaration(
142 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
143 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
144 FD->setInline(Record[Idx++]);
145 FD->setVirtual(Record[Idx++]);
146 FD->setPure(Record[Idx++]);
147 FD->setInheritedPrototype(Record[Idx++]);
148 FD->setHasPrototype(Record[Idx++]);
149 FD->setDeleted(Record[Idx++]);
150 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
151 unsigned NumParams = Record[Idx++];
152 llvm::SmallVector<ParmVarDecl *, 16> Params;
153 Params.reserve(NumParams);
154 for (unsigned I = 0; I != NumParams; ++I)
155 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
156 FD->setParams(Reader.getContext(), &Params[0], NumParams);
157}
158
Douglas Gregor982365e2009-04-13 21:20:57 +0000159void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
160 VisitValueDecl(FD);
161 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000162 if (Record[Idx++])
163 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000164}
165
Douglas Gregorc34897d2009-04-09 22:27:44 +0000166void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
167 VisitValueDecl(VD);
168 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
169 VD->setThreadSpecified(Record[Idx++]);
170 VD->setCXXDirectInitializer(Record[Idx++]);
171 VD->setDeclaredInCondition(Record[Idx++]);
172 VD->setPreviousDeclaration(
173 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
174 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000175 if (Record[Idx++])
176 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000177}
178
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000179void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
180 VisitVarDecl(PD);
181 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000182 // FIXME: default argument (C++ only)
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000183}
184
185void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
186 VisitParmVarDecl(PD);
187 PD->setOriginalType(Reader.GetType(Record[Idx++]));
188}
189
Douglas Gregor2a491792009-04-13 22:49:25 +0000190void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
191 VisitDecl(AD);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000192 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000193}
194
195void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
196 VisitDecl(BD);
197 unsigned NumParams = Record[Idx++];
198 llvm::SmallVector<ParmVarDecl *, 16> Params;
199 Params.reserve(NumParams);
200 for (unsigned I = 0; I != NumParams; ++I)
201 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
202 BD->setParams(Reader.getContext(), &Params[0], NumParams);
203}
204
Douglas Gregorc34897d2009-04-09 22:27:44 +0000205std::pair<uint64_t, uint64_t>
206PCHDeclReader::VisitDeclContext(DeclContext *DC) {
207 uint64_t LexicalOffset = Record[Idx++];
208 uint64_t VisibleOffset = 0;
209 if (DC->getPrimaryContext() == DC)
210 VisibleOffset = Record[Idx++];
211 return std::make_pair(LexicalOffset, VisibleOffset);
212}
213
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000214//===----------------------------------------------------------------------===//
215// Statement/expression deserialization
216//===----------------------------------------------------------------------===//
217namespace {
218 class VISIBILITY_HIDDEN PCHStmtReader
Douglas Gregora151ba42009-04-14 23:32:43 +0000219 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000220 PCHReader &Reader;
221 const PCHReader::RecordData &Record;
222 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000223 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000224
225 public:
226 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000227 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
228 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000229
Douglas Gregor596e0932009-04-15 16:35:07 +0000230 /// \brief The number of record fields required for the Expr class
231 /// itself.
232 static const unsigned NumExprFields = 3;
233
Douglas Gregora151ba42009-04-14 23:32:43 +0000234 // Each of the Visit* functions reads in part of the expression
235 // from the given record and the current expression stack, then
236 // return the total number of operands that it read from the
237 // expression stack.
238
239 unsigned VisitExpr(Expr *E);
240 unsigned VisitPredefinedExpr(PredefinedExpr *E);
241 unsigned VisitDeclRefExpr(DeclRefExpr *E);
242 unsigned VisitIntegerLiteral(IntegerLiteral *E);
243 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000244 unsigned VisitImaginaryLiteral(ImaginaryLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000245 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000246 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000247 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000248 unsigned VisitUnaryOperator(UnaryOperator *E);
249 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000250 unsigned VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000251 unsigned VisitCallExpr(CallExpr *E);
252 unsigned VisitMemberExpr(MemberExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000253 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000254 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000255 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000256 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
257 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000258 };
259}
260
Douglas Gregora151ba42009-04-14 23:32:43 +0000261unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000262 E->setType(Reader.GetType(Record[Idx++]));
263 E->setTypeDependent(Record[Idx++]);
264 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000265 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000266 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000267}
268
Douglas Gregora151ba42009-04-14 23:32:43 +0000269unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000270 VisitExpr(E);
271 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
272 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000273 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000274}
275
Douglas Gregora151ba42009-04-14 23:32:43 +0000276unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000277 VisitExpr(E);
278 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
279 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000280 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000281}
282
Douglas Gregora151ba42009-04-14 23:32:43 +0000283unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000284 VisitExpr(E);
285 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
286 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000287 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000288}
289
Douglas Gregora151ba42009-04-14 23:32:43 +0000290unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000291 VisitExpr(E);
292 E->setValue(Reader.ReadAPFloat(Record, Idx));
293 E->setExact(Record[Idx++]);
294 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000295 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000296}
297
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000298unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) {
299 VisitExpr(E);
300 E->setSubExpr(ExprStack.back());
301 return 1;
302}
303
Douglas Gregor596e0932009-04-15 16:35:07 +0000304unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
305 VisitExpr(E);
306 unsigned Len = Record[Idx++];
307 assert(Record[Idx] == E->getNumConcatenated() &&
308 "Wrong number of concatenated tokens!");
309 ++Idx;
310 E->setWide(Record[Idx++]);
311
312 // Read string data
313 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
314 E->setStrData(Reader.getContext(), &Str[0], Len);
315 Idx += Len;
316
317 // Read source locations
318 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
319 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
320
321 return 0;
322}
323
Douglas Gregora151ba42009-04-14 23:32:43 +0000324unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000325 VisitExpr(E);
326 E->setValue(Record[Idx++]);
327 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
328 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000329 return 0;
330}
331
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000332unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
333 VisitExpr(E);
334 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
335 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
336 E->setSubExpr(ExprStack.back());
337 return 1;
338}
339
Douglas Gregor12d74052009-04-15 15:58:59 +0000340unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
341 VisitExpr(E);
342 E->setSubExpr(ExprStack.back());
343 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
344 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
345 return 1;
346}
347
348unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
349 VisitExpr(E);
350 E->setSizeof(Record[Idx++]);
351 if (Record[Idx] == 0) {
352 E->setArgument(ExprStack.back());
353 ++Idx;
354 } else {
355 E->setArgument(Reader.GetType(Record[Idx++]));
356 }
357 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
358 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
359 return E->isArgumentType()? 0 : 1;
360}
361
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000362unsigned PCHStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
363 VisitExpr(E);
364 E->setLHS(ExprStack[ExprStack.size() - 2]);
365 E->setRHS(ExprStack[ExprStack.size() - 2]);
366 E->setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
367 return 2;
368}
369
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000370unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
371 VisitExpr(E);
372 E->setNumArgs(Reader.getContext(), Record[Idx++]);
373 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
374 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
375 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
376 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
377 return E->getNumArgs() + 1;
378}
379
380unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
381 VisitExpr(E);
382 E->setBase(ExprStack.back());
383 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
384 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
385 E->setArrow(Record[Idx++]);
386 return 1;
387}
388
Douglas Gregora151ba42009-04-14 23:32:43 +0000389unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
390 VisitExpr(E);
391 E->setSubExpr(ExprStack.back());
392 return 1;
393}
394
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000395unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
396 VisitExpr(E);
397 E->setLHS(ExprStack.end()[-2]);
398 E->setRHS(ExprStack.end()[-1]);
399 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
400 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
401 return 2;
402}
403
Douglas Gregora151ba42009-04-14 23:32:43 +0000404unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
405 VisitCastExpr(E);
406 E->setLvalueCast(Record[Idx++]);
407 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000408}
409
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000410unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
411 VisitCastExpr(E);
412 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
413 return 1;
414}
415
416unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
417 VisitExplicitCastExpr(E);
418 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
419 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
420 return 1;
421}
422
Douglas Gregorc34897d2009-04-09 22:27:44 +0000423// FIXME: use the diagnostics machinery
424static bool Error(const char *Str) {
425 std::fprintf(stderr, "%s\n", Str);
426 return true;
427}
428
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000429/// \brief Check the contents of the predefines buffer against the
430/// contents of the predefines buffer used to build the PCH file.
431///
432/// The contents of the two predefines buffers should be the same. If
433/// not, then some command-line option changed the preprocessor state
434/// and we must reject the PCH file.
435///
436/// \param PCHPredef The start of the predefines buffer in the PCH
437/// file.
438///
439/// \param PCHPredefLen The length of the predefines buffer in the PCH
440/// file.
441///
442/// \param PCHBufferID The FileID for the PCH predefines buffer.
443///
444/// \returns true if there was a mismatch (in which case the PCH file
445/// should be ignored), or false otherwise.
446bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
447 unsigned PCHPredefLen,
448 FileID PCHBufferID) {
449 const char *Predef = PP.getPredefines().c_str();
450 unsigned PredefLen = PP.getPredefines().size();
451
452 // If the two predefines buffers compare equal, we're done!.
453 if (PredefLen == PCHPredefLen &&
454 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
455 return false;
456
457 // The predefines buffers are different. Produce a reasonable
458 // diagnostic showing where they are different.
459
460 // The source locations (potentially in the two different predefines
461 // buffers)
462 SourceLocation Loc1, Loc2;
463 SourceManager &SourceMgr = PP.getSourceManager();
464
465 // Create a source buffer for our predefines string, so
466 // that we can build a diagnostic that points into that
467 // source buffer.
468 FileID BufferID;
469 if (Predef && Predef[0]) {
470 llvm::MemoryBuffer *Buffer
471 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
472 "<built-in>");
473 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
474 }
475
476 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
477 std::pair<const char *, const char *> Locations
478 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
479
480 if (Locations.first != Predef + MinLen) {
481 // We found the location in the two buffers where there is a
482 // difference. Form source locations to point there (in both
483 // buffers).
484 unsigned Offset = Locations.first - Predef;
485 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
486 .getFileLocWithOffset(Offset);
487 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
488 .getFileLocWithOffset(Offset);
489 } else if (PredefLen > PCHPredefLen) {
490 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
491 .getFileLocWithOffset(MinLen);
492 } else {
493 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
494 .getFileLocWithOffset(MinLen);
495 }
496
497 Diag(Loc1, diag::warn_pch_preprocessor);
498 if (Loc2.isValid())
499 Diag(Loc2, diag::note_predef_in_pch);
500 Diag(diag::note_ignoring_pch) << FileName;
501 return true;
502}
503
Douglas Gregor635f97f2009-04-13 16:31:14 +0000504/// \brief Read the line table in the source manager block.
505/// \returns true if ther was an error.
506static bool ParseLineTable(SourceManager &SourceMgr,
507 llvm::SmallVectorImpl<uint64_t> &Record) {
508 unsigned Idx = 0;
509 LineTableInfo &LineTable = SourceMgr.getLineTable();
510
511 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000512 std::map<int, int> FileIDs;
513 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000514 // Extract the file name
515 unsigned FilenameLen = Record[Idx++];
516 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
517 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000518 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
519 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000520 }
521
522 // Parse the line entries
523 std::vector<LineEntry> Entries;
524 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000525 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000526
527 // Extract the line entries
528 unsigned NumEntries = Record[Idx++];
529 Entries.clear();
530 Entries.reserve(NumEntries);
531 for (unsigned I = 0; I != NumEntries; ++I) {
532 unsigned FileOffset = Record[Idx++];
533 unsigned LineNo = Record[Idx++];
534 int FilenameID = Record[Idx++];
535 SrcMgr::CharacteristicKind FileKind
536 = (SrcMgr::CharacteristicKind)Record[Idx++];
537 unsigned IncludeOffset = Record[Idx++];
538 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
539 FileKind, IncludeOffset));
540 }
541 LineTable.AddEntry(FID, Entries);
542 }
543
544 return false;
545}
546
Douglas Gregorab1cef72009-04-10 03:52:48 +0000547/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000548PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000549 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000550 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
551 Error("Malformed source manager block record");
552 return Failure;
553 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000554
555 SourceManager &SourceMgr = Context.getSourceManager();
556 RecordData Record;
557 while (true) {
558 unsigned Code = Stream.ReadCode();
559 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000560 if (Stream.ReadBlockEnd()) {
561 Error("Error at end of Source Manager block");
562 return Failure;
563 }
564
565 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000566 }
567
568 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
569 // No known subblocks, always skip them.
570 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000571 if (Stream.SkipBlock()) {
572 Error("Malformed block record");
573 return Failure;
574 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000575 continue;
576 }
577
578 if (Code == llvm::bitc::DEFINE_ABBREV) {
579 Stream.ReadAbbrevRecord();
580 continue;
581 }
582
583 // Read a record.
584 const char *BlobStart;
585 unsigned BlobLen;
586 Record.clear();
587 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
588 default: // Default behavior: ignore.
589 break;
590
591 case pch::SM_SLOC_FILE_ENTRY: {
592 // FIXME: We would really like to delay the creation of this
593 // FileEntry until it is actually required, e.g., when producing
594 // a diagnostic with a source location in this file.
595 const FileEntry *File
596 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
597 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000598 FileID ID = SourceMgr.createFileID(File,
599 SourceLocation::getFromRawEncoding(Record[1]),
600 (CharacteristicKind)Record[2]);
601 if (Record[3])
602 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
603 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000604 break;
605 }
606
607 case pch::SM_SLOC_BUFFER_ENTRY: {
608 const char *Name = BlobStart;
609 unsigned Code = Stream.ReadCode();
610 Record.clear();
611 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
612 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000613 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000614 llvm::MemoryBuffer *Buffer
615 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
616 BlobStart + BlobLen - 1,
617 Name);
618 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
619
620 if (strcmp(Name, "<built-in>") == 0
621 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
622 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000623 break;
624 }
625
626 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
627 SourceLocation SpellingLoc
628 = SourceLocation::getFromRawEncoding(Record[1]);
629 SourceMgr.createInstantiationLoc(
630 SpellingLoc,
631 SourceLocation::getFromRawEncoding(Record[2]),
632 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000633 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000634 break;
635 }
636
Chris Lattnere1be6022009-04-14 23:22:57 +0000637 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000638 if (ParseLineTable(SourceMgr, Record))
639 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000640 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000641 }
642 }
643}
644
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000645bool PCHReader::ReadPreprocessorBlock() {
646 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
647 return Error("Malformed preprocessor block record");
648
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000649 RecordData Record;
650 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
651 MacroInfo *LastMacro = 0;
652
653 while (true) {
654 unsigned Code = Stream.ReadCode();
655 switch (Code) {
656 case llvm::bitc::END_BLOCK:
657 if (Stream.ReadBlockEnd())
658 return Error("Error at end of preprocessor block");
659 return false;
660
661 case llvm::bitc::ENTER_SUBBLOCK:
662 // No known subblocks, always skip them.
663 Stream.ReadSubBlockID();
664 if (Stream.SkipBlock())
665 return Error("Malformed block record");
666 continue;
667
668 case llvm::bitc::DEFINE_ABBREV:
669 Stream.ReadAbbrevRecord();
670 continue;
671 default: break;
672 }
673
674 // Read a record.
675 Record.clear();
676 pch::PreprocessorRecordTypes RecType =
677 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
678 switch (RecType) {
679 default: // Default behavior: ignore unknown records.
680 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000681 case pch::PP_COUNTER_VALUE:
682 if (!Record.empty())
683 PP.setCounterValue(Record[0]);
684 break;
685
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000686 case pch::PP_MACRO_OBJECT_LIKE:
687 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000688 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
689 if (II == 0)
690 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000691 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
692 bool isUsed = Record[2];
693
694 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
695 MI->setIsUsed(isUsed);
696
697 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
698 // Decode function-like macro info.
699 bool isC99VarArgs = Record[3];
700 bool isGNUVarArgs = Record[4];
701 MacroArgs.clear();
702 unsigned NumArgs = Record[5];
703 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000704 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000705
706 // Install function-like macro info.
707 MI->setIsFunctionLike();
708 if (isC99VarArgs) MI->setIsC99Varargs();
709 if (isGNUVarArgs) MI->setIsGNUVarargs();
710 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
711 PP.getPreprocessorAllocator());
712 }
713
714 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000715 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000716
717 // Remember that we saw this macro last so that we add the tokens that
718 // form its body to it.
719 LastMacro = MI;
720 break;
721 }
722
723 case pch::PP_TOKEN: {
724 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
725 // pretend we didn't see this.
726 if (LastMacro == 0) break;
727
728 Token Tok;
729 Tok.startToken();
730 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
731 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000732 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
733 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000734 Tok.setKind((tok::TokenKind)Record[3]);
735 Tok.setFlag((Token::TokenFlags)Record[4]);
736 LastMacro->AddTokenToBody(Tok);
737 break;
738 }
739 }
740 }
741}
742
Douglas Gregor179cfb12009-04-10 20:39:37 +0000743PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
744 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
745 Error("Malformed block record");
746 return Failure;
747 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000748
Chris Lattner29241862009-04-11 21:15:38 +0000749 uint64_t PreprocessorBlockBit = 0;
750
Douglas Gregorc34897d2009-04-09 22:27:44 +0000751 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000752 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000753 while (!Stream.AtEndOfStream()) {
754 unsigned Code = Stream.ReadCode();
755 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000756 // If we saw the preprocessor block, read it now.
757 if (PreprocessorBlockBit) {
758 uint64_t SavedPos = Stream.GetCurrentBitNo();
759 Stream.JumpToBit(PreprocessorBlockBit);
760 if (ReadPreprocessorBlock()) {
761 Error("Malformed preprocessor block");
762 return Failure;
763 }
764 Stream.JumpToBit(SavedPos);
765 }
766
Douglas Gregor179cfb12009-04-10 20:39:37 +0000767 if (Stream.ReadBlockEnd()) {
768 Error("Error at end of module block");
769 return Failure;
770 }
Chris Lattner29241862009-04-11 21:15:38 +0000771
Douglas Gregor179cfb12009-04-10 20:39:37 +0000772 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000773 }
774
775 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
776 switch (Stream.ReadSubBlockID()) {
777 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
778 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
779 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000780 if (Stream.SkipBlock()) {
781 Error("Malformed block record");
782 return Failure;
783 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000784 break;
785
Chris Lattner29241862009-04-11 21:15:38 +0000786 case pch::PREPROCESSOR_BLOCK_ID:
787 // Skip the preprocessor block for now, but remember where it is. We
788 // want to read it in after the identifier table.
789 if (PreprocessorBlockBit) {
790 Error("Multiple preprocessor blocks found.");
791 return Failure;
792 }
793 PreprocessorBlockBit = Stream.GetCurrentBitNo();
794 if (Stream.SkipBlock()) {
795 Error("Malformed block record");
796 return Failure;
797 }
798 break;
799
Douglas Gregorab1cef72009-04-10 03:52:48 +0000800 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000801 switch (ReadSourceManagerBlock()) {
802 case Success:
803 break;
804
805 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000806 Error("Malformed source manager block");
807 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000808
809 case IgnorePCH:
810 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000811 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000812 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000813 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000814 continue;
815 }
816
817 if (Code == llvm::bitc::DEFINE_ABBREV) {
818 Stream.ReadAbbrevRecord();
819 continue;
820 }
821
822 // Read and process a record.
823 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000824 const char *BlobStart = 0;
825 unsigned BlobLen = 0;
826 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
827 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000828 default: // Default behavior: ignore.
829 break;
830
831 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000832 if (!TypeOffsets.empty()) {
833 Error("Duplicate TYPE_OFFSET record in PCH file");
834 return Failure;
835 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000836 TypeOffsets.swap(Record);
837 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
838 break;
839
840 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000841 if (!DeclOffsets.empty()) {
842 Error("Duplicate DECL_OFFSET record in PCH file");
843 return Failure;
844 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000845 DeclOffsets.swap(Record);
846 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
847 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000848
849 case pch::LANGUAGE_OPTIONS:
850 if (ParseLanguageOptions(Record))
851 return IgnorePCH;
852 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000853
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000854 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000855 std::string TargetTriple(BlobStart, BlobLen);
856 if (TargetTriple != Context.Target.getTargetTriple()) {
857 Diag(diag::warn_pch_target_triple)
858 << TargetTriple << Context.Target.getTargetTriple();
859 Diag(diag::note_ignoring_pch) << FileName;
860 return IgnorePCH;
861 }
862 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000863 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000864
865 case pch::IDENTIFIER_TABLE:
866 IdentifierTable = BlobStart;
867 break;
868
869 case pch::IDENTIFIER_OFFSET:
870 if (!IdentifierData.empty()) {
871 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
872 return Failure;
873 }
874 IdentifierData.swap(Record);
875#ifndef NDEBUG
876 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
877 if ((IdentifierData[I] & 0x01) == 0) {
878 Error("Malformed identifier table in the precompiled header");
879 return Failure;
880 }
881 }
882#endif
883 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000884
885 case pch::EXTERNAL_DEFINITIONS:
886 if (!ExternalDefinitions.empty()) {
887 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
888 return Failure;
889 }
890 ExternalDefinitions.swap(Record);
891 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000892 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000893 }
894
Douglas Gregor179cfb12009-04-10 20:39:37 +0000895 Error("Premature end of bitstream");
896 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000897}
898
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000899PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000900 // Set the PCH file name.
901 this->FileName = FileName;
902
Douglas Gregorc34897d2009-04-09 22:27:44 +0000903 // Open the PCH file.
904 std::string ErrStr;
905 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000906 if (!Buffer) {
907 Error(ErrStr.c_str());
908 return IgnorePCH;
909 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000910
911 // Initialize the stream
912 Stream.init((const unsigned char *)Buffer->getBufferStart(),
913 (const unsigned char *)Buffer->getBufferEnd());
914
915 // Sniff for the signature.
916 if (Stream.Read(8) != 'C' ||
917 Stream.Read(8) != 'P' ||
918 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000919 Stream.Read(8) != 'H') {
920 Error("Not a PCH file");
921 return IgnorePCH;
922 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000923
924 // We expect a number of well-defined blocks, though we don't necessarily
925 // need to understand them all.
926 while (!Stream.AtEndOfStream()) {
927 unsigned Code = Stream.ReadCode();
928
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000929 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
930 Error("Invalid record at top-level");
931 return Failure;
932 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000933
934 unsigned BlockID = Stream.ReadSubBlockID();
935
936 // We only know the PCH subblock ID.
937 switch (BlockID) {
938 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000939 if (Stream.ReadBlockInfoBlock()) {
940 Error("Malformed BlockInfoBlock");
941 return Failure;
942 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000943 break;
944 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000945 switch (ReadPCHBlock()) {
946 case Success:
947 break;
948
949 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000950 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000951
952 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000953 // FIXME: We could consider reading through to the end of this
954 // PCH block, skipping subblocks, to see if there are other
955 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000956 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000957 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000958 break;
959 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000960 if (Stream.SkipBlock()) {
961 Error("Malformed block record");
962 return Failure;
963 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000964 break;
965 }
966 }
967
968 // Load the translation unit declaration
969 ReadDeclRecord(DeclOffsets[0], 0);
970
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000971 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000972}
973
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000974namespace {
975 /// \brief Helper class that saves the current stream position and
976 /// then restores it when destroyed.
977 struct VISIBILITY_HIDDEN SavedStreamPosition {
978 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000979 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000980
981 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000982 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000983 }
984
985 private:
986 llvm::BitstreamReader &Stream;
987 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000988 };
989}
990
Douglas Gregor179cfb12009-04-10 20:39:37 +0000991/// \brief Parse the record that corresponds to a LangOptions data
992/// structure.
993///
994/// This routine compares the language options used to generate the
995/// PCH file against the language options set for the current
996/// compilation. For each option, we classify differences between the
997/// two compiler states as either "benign" or "important". Benign
998/// differences don't matter, and we accept them without complaint
999/// (and without modifying the language options). Differences between
1000/// the states for important options cause the PCH file to be
1001/// unusable, so we emit a warning and return true to indicate that
1002/// there was an error.
1003///
1004/// \returns true if the PCH file is unacceptable, false otherwise.
1005bool PCHReader::ParseLanguageOptions(
1006 const llvm::SmallVectorImpl<uint64_t> &Record) {
1007 const LangOptions &LangOpts = Context.getLangOptions();
1008#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1009#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1010 if (Record[Idx] != LangOpts.Option) { \
1011 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1012 Diag(diag::note_ignoring_pch) << FileName; \
1013 return true; \
1014 } \
1015 ++Idx
1016
1017 unsigned Idx = 0;
1018 PARSE_LANGOPT_BENIGN(Trigraphs);
1019 PARSE_LANGOPT_BENIGN(BCPLComment);
1020 PARSE_LANGOPT_BENIGN(DollarIdents);
1021 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1022 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1023 PARSE_LANGOPT_BENIGN(ImplicitInt);
1024 PARSE_LANGOPT_BENIGN(Digraphs);
1025 PARSE_LANGOPT_BENIGN(HexFloats);
1026 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1027 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1028 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1029 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1030 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1031 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1032 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1033 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1034 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1035 PARSE_LANGOPT_BENIGN(PascalStrings);
1036 PARSE_LANGOPT_BENIGN(Boolean);
1037 PARSE_LANGOPT_BENIGN(WritableStrings);
1038 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1039 diag::warn_pch_lax_vector_conversions);
1040 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1041 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1042 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1043 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1044 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1045 diag::warn_pch_thread_safe_statics);
1046 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1047 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1048 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1049 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1050 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1051 diag::warn_pch_heinous_extensions);
1052 // FIXME: Most of the options below are benign if the macro wasn't
1053 // used. Unfortunately, this means that a PCH compiled without
1054 // optimization can't be used with optimization turned on, even
1055 // though the only thing that changes is whether __OPTIMIZE__ was
1056 // defined... but if __OPTIMIZE__ never showed up in the header, it
1057 // doesn't matter. We could consider making this some special kind
1058 // of check.
1059 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1060 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1061 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1062 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1063 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1064 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1065 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1066 Diag(diag::warn_pch_gc_mode)
1067 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1068 Diag(diag::note_ignoring_pch) << FileName;
1069 return true;
1070 }
1071 ++Idx;
1072 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1073 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1074#undef PARSE_LANGOPT_IRRELEVANT
1075#undef PARSE_LANGOPT_BENIGN
1076
1077 return false;
1078}
1079
Douglas Gregorc34897d2009-04-09 22:27:44 +00001080/// \brief Read and return the type at the given offset.
1081///
1082/// This routine actually reads the record corresponding to the type
1083/// at the given offset in the bitstream. It is a helper routine for
1084/// GetType, which deals with reading type IDs.
1085QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001086 // Keep track of where we are in the stream, then jump back there
1087 // after reading this type.
1088 SavedStreamPosition SavedPosition(Stream);
1089
Douglas Gregorc34897d2009-04-09 22:27:44 +00001090 Stream.JumpToBit(Offset);
1091 RecordData Record;
1092 unsigned Code = Stream.ReadCode();
1093 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001094 case pch::TYPE_ATTR:
1095 assert(false && "Should never jump to an attribute block");
1096 return QualType();
1097
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001098 case pch::TYPE_EXT_QUAL: {
1099 assert(Record.size() == 3 &&
1100 "Incorrect encoding of extended qualifier type");
1101 QualType Base = GetType(Record[0]);
1102 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1103 unsigned AddressSpace = Record[2];
1104
1105 QualType T = Base;
1106 if (GCAttr != QualType::GCNone)
1107 T = Context.getObjCGCQualType(T, GCAttr);
1108 if (AddressSpace)
1109 T = Context.getAddrSpaceQualType(T, AddressSpace);
1110 return T;
1111 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001112
Douglas Gregorc34897d2009-04-09 22:27:44 +00001113 case pch::TYPE_FIXED_WIDTH_INT: {
1114 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1115 return Context.getFixedWidthIntType(Record[0], Record[1]);
1116 }
1117
1118 case pch::TYPE_COMPLEX: {
1119 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1120 QualType ElemType = GetType(Record[0]);
1121 return Context.getComplexType(ElemType);
1122 }
1123
1124 case pch::TYPE_POINTER: {
1125 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1126 QualType PointeeType = GetType(Record[0]);
1127 return Context.getPointerType(PointeeType);
1128 }
1129
1130 case pch::TYPE_BLOCK_POINTER: {
1131 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1132 QualType PointeeType = GetType(Record[0]);
1133 return Context.getBlockPointerType(PointeeType);
1134 }
1135
1136 case pch::TYPE_LVALUE_REFERENCE: {
1137 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1138 QualType PointeeType = GetType(Record[0]);
1139 return Context.getLValueReferenceType(PointeeType);
1140 }
1141
1142 case pch::TYPE_RVALUE_REFERENCE: {
1143 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1144 QualType PointeeType = GetType(Record[0]);
1145 return Context.getRValueReferenceType(PointeeType);
1146 }
1147
1148 case pch::TYPE_MEMBER_POINTER: {
1149 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1150 QualType PointeeType = GetType(Record[0]);
1151 QualType ClassType = GetType(Record[1]);
1152 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1153 }
1154
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001155 case pch::TYPE_CONSTANT_ARRAY: {
1156 QualType ElementType = GetType(Record[0]);
1157 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1158 unsigned IndexTypeQuals = Record[2];
1159 unsigned Idx = 3;
1160 llvm::APInt Size = ReadAPInt(Record, Idx);
1161 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1162 }
1163
1164 case pch::TYPE_INCOMPLETE_ARRAY: {
1165 QualType ElementType = GetType(Record[0]);
1166 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1167 unsigned IndexTypeQuals = Record[2];
1168 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1169 }
1170
1171 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001172 QualType ElementType = GetType(Record[0]);
1173 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1174 unsigned IndexTypeQuals = Record[2];
1175 return Context.getVariableArrayType(ElementType, ReadExpr(),
1176 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001177 }
1178
1179 case pch::TYPE_VECTOR: {
1180 if (Record.size() != 2) {
1181 Error("Incorrect encoding of vector type in PCH file");
1182 return QualType();
1183 }
1184
1185 QualType ElementType = GetType(Record[0]);
1186 unsigned NumElements = Record[1];
1187 return Context.getVectorType(ElementType, NumElements);
1188 }
1189
1190 case pch::TYPE_EXT_VECTOR: {
1191 if (Record.size() != 2) {
1192 Error("Incorrect encoding of extended vector type in PCH file");
1193 return QualType();
1194 }
1195
1196 QualType ElementType = GetType(Record[0]);
1197 unsigned NumElements = Record[1];
1198 return Context.getExtVectorType(ElementType, NumElements);
1199 }
1200
1201 case pch::TYPE_FUNCTION_NO_PROTO: {
1202 if (Record.size() != 1) {
1203 Error("Incorrect encoding of no-proto function type");
1204 return QualType();
1205 }
1206 QualType ResultType = GetType(Record[0]);
1207 return Context.getFunctionNoProtoType(ResultType);
1208 }
1209
1210 case pch::TYPE_FUNCTION_PROTO: {
1211 QualType ResultType = GetType(Record[0]);
1212 unsigned Idx = 1;
1213 unsigned NumParams = Record[Idx++];
1214 llvm::SmallVector<QualType, 16> ParamTypes;
1215 for (unsigned I = 0; I != NumParams; ++I)
1216 ParamTypes.push_back(GetType(Record[Idx++]));
1217 bool isVariadic = Record[Idx++];
1218 unsigned Quals = Record[Idx++];
1219 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1220 isVariadic, Quals);
1221 }
1222
1223 case pch::TYPE_TYPEDEF:
1224 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1225 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1226
1227 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001228 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001229
1230 case pch::TYPE_TYPEOF: {
1231 if (Record.size() != 1) {
1232 Error("Incorrect encoding of typeof(type) in PCH file");
1233 return QualType();
1234 }
1235 QualType UnderlyingType = GetType(Record[0]);
1236 return Context.getTypeOfType(UnderlyingType);
1237 }
1238
1239 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001240 assert(Record.size() == 1 && "Incorrect encoding of record type");
1241 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001242
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001243 case pch::TYPE_ENUM:
1244 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1245 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1246
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001247 case pch::TYPE_OBJC_INTERFACE:
1248 // FIXME: Deserialize ObjCInterfaceType
1249 assert(false && "Cannot de-serialize ObjC interface types yet");
1250 return QualType();
1251
1252 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1253 // FIXME: Deserialize ObjCQualifiedInterfaceType
1254 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1255 return QualType();
1256
1257 case pch::TYPE_OBJC_QUALIFIED_ID:
1258 // FIXME: Deserialize ObjCQualifiedIdType
1259 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1260 return QualType();
1261
1262 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1263 // FIXME: Deserialize ObjCQualifiedClassType
1264 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1265 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001266 }
1267
1268 // Suppress a GCC warning
1269 return QualType();
1270}
1271
1272/// \brief Note that we have loaded the declaration with the given
1273/// Index.
1274///
1275/// This routine notes that this declaration has already been loaded,
1276/// so that future GetDecl calls will return this declaration rather
1277/// than trying to load a new declaration.
1278inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1279 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1280 DeclAlreadyLoaded[Index] = true;
1281 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1282}
1283
1284/// \brief Read the declaration at the given offset from the PCH file.
1285Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001286 // Keep track of where we are in the stream, then jump back there
1287 // after reading this declaration.
1288 SavedStreamPosition SavedPosition(Stream);
1289
Douglas Gregorc34897d2009-04-09 22:27:44 +00001290 Decl *D = 0;
1291 Stream.JumpToBit(Offset);
1292 RecordData Record;
1293 unsigned Code = Stream.ReadCode();
1294 unsigned Idx = 0;
1295 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001296
Douglas Gregorc34897d2009-04-09 22:27:44 +00001297 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001298 case pch::DECL_ATTR:
1299 case pch::DECL_CONTEXT_LEXICAL:
1300 case pch::DECL_CONTEXT_VISIBLE:
1301 assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1302 break;
1303
Douglas Gregorc34897d2009-04-09 22:27:44 +00001304 case pch::DECL_TRANSLATION_UNIT:
1305 assert(Index == 0 && "Translation unit must be at index 0");
1306 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1307 D = Context.getTranslationUnitDecl();
1308 LoadedDecl(Index, D);
1309 break;
1310
1311 case pch::DECL_TYPEDEF: {
1312 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1313 0, QualType());
1314 LoadedDecl(Index, Typedef);
1315 Reader.VisitTypedefDecl(Typedef);
1316 D = Typedef;
1317 break;
1318 }
1319
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001320 case pch::DECL_ENUM: {
1321 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1322 LoadedDecl(Index, Enum);
1323 Reader.VisitEnumDecl(Enum);
1324 D = Enum;
1325 break;
1326 }
1327
Douglas Gregor982365e2009-04-13 21:20:57 +00001328 case pch::DECL_RECORD: {
1329 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1330 0, SourceLocation(), 0, 0);
1331 LoadedDecl(Index, Record);
1332 Reader.VisitRecordDecl(Record);
1333 D = Record;
1334 break;
1335 }
1336
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001337 case pch::DECL_ENUM_CONSTANT: {
1338 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1339 SourceLocation(), 0,
1340 QualType(), 0,
1341 llvm::APSInt());
1342 LoadedDecl(Index, ECD);
1343 Reader.VisitEnumConstantDecl(ECD);
1344 D = ECD;
1345 break;
1346 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001347
1348 case pch::DECL_FUNCTION: {
1349 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1350 DeclarationName(),
1351 QualType());
1352 LoadedDecl(Index, Function);
1353 Reader.VisitFunctionDecl(Function);
1354 D = Function;
1355 break;
1356 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001357
Douglas Gregor982365e2009-04-13 21:20:57 +00001358 case pch::DECL_FIELD: {
1359 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1360 QualType(), 0, false);
1361 LoadedDecl(Index, Field);
1362 Reader.VisitFieldDecl(Field);
1363 D = Field;
1364 break;
1365 }
1366
Douglas Gregorc34897d2009-04-09 22:27:44 +00001367 case pch::DECL_VAR: {
1368 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1369 VarDecl::None, SourceLocation());
1370 LoadedDecl(Index, Var);
1371 Reader.VisitVarDecl(Var);
1372 D = Var;
1373 break;
1374 }
1375
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001376 case pch::DECL_PARM_VAR: {
1377 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1378 QualType(), VarDecl::None, 0);
1379 LoadedDecl(Index, Parm);
1380 Reader.VisitParmVarDecl(Parm);
1381 D = Parm;
1382 break;
1383 }
1384
1385 case pch::DECL_ORIGINAL_PARM_VAR: {
1386 OriginalParmVarDecl *Parm
1387 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1388 QualType(), QualType(), VarDecl::None,
1389 0);
1390 LoadedDecl(Index, Parm);
1391 Reader.VisitOriginalParmVarDecl(Parm);
1392 D = Parm;
1393 break;
1394 }
1395
Douglas Gregor2a491792009-04-13 22:49:25 +00001396 case pch::DECL_FILE_SCOPE_ASM: {
1397 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1398 SourceLocation(), 0);
1399 LoadedDecl(Index, Asm);
1400 Reader.VisitFileScopeAsmDecl(Asm);
1401 D = Asm;
1402 break;
1403 }
1404
1405 case pch::DECL_BLOCK: {
1406 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1407 LoadedDecl(Index, Block);
1408 Reader.VisitBlockDecl(Block);
1409 D = Block;
1410 break;
1411 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001412 }
1413
1414 // If this declaration is also a declaration context, get the
1415 // offsets for its tables of lexical and visible declarations.
1416 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1417 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1418 if (Offsets.first || Offsets.second) {
1419 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1420 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1421 DeclContextOffsets[DC] = Offsets;
1422 }
1423 }
1424 assert(Idx == Record.size());
1425
1426 return D;
1427}
1428
Douglas Gregorac8f2802009-04-10 17:25:41 +00001429QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001430 unsigned Quals = ID & 0x07;
1431 unsigned Index = ID >> 3;
1432
1433 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1434 QualType T;
1435 switch ((pch::PredefinedTypeIDs)Index) {
1436 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1437 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1438 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1439
1440 case pch::PREDEF_TYPE_CHAR_U_ID:
1441 case pch::PREDEF_TYPE_CHAR_S_ID:
1442 // FIXME: Check that the signedness of CharTy is correct!
1443 T = Context.CharTy;
1444 break;
1445
1446 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1447 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1448 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1449 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1450 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1451 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1452 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1453 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1454 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1455 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1456 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1457 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1458 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1459 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1460 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1461 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1462 }
1463
1464 assert(!T.isNull() && "Unknown predefined type");
1465 return T.getQualifiedType(Quals);
1466 }
1467
1468 Index -= pch::NUM_PREDEF_TYPE_IDS;
1469 if (!TypeAlreadyLoaded[Index]) {
1470 // Load the type from the PCH file.
1471 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1472 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1473 TypeAlreadyLoaded[Index] = true;
1474 }
1475
1476 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1477}
1478
Douglas Gregorac8f2802009-04-10 17:25:41 +00001479Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001480 if (ID == 0)
1481 return 0;
1482
1483 unsigned Index = ID - 1;
1484 if (DeclAlreadyLoaded[Index])
1485 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1486
1487 // Load the declaration from the PCH file.
1488 return ReadDeclRecord(DeclOffsets[Index], Index);
1489}
1490
1491bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001492 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001493 assert(DC->hasExternalLexicalStorage() &&
1494 "DeclContext has no lexical decls in storage");
1495 uint64_t Offset = DeclContextOffsets[DC].first;
1496 assert(Offset && "DeclContext has no lexical decls in storage");
1497
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001498 // Keep track of where we are in the stream, then jump back there
1499 // after reading this context.
1500 SavedStreamPosition SavedPosition(Stream);
1501
Douglas Gregorc34897d2009-04-09 22:27:44 +00001502 // Load the record containing all of the declarations lexically in
1503 // this context.
1504 Stream.JumpToBit(Offset);
1505 RecordData Record;
1506 unsigned Code = Stream.ReadCode();
1507 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001508 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001509 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1510
1511 // Load all of the declaration IDs
1512 Decls.clear();
1513 Decls.insert(Decls.end(), Record.begin(), Record.end());
1514 return false;
1515}
1516
1517bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1518 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1519 assert(DC->hasExternalVisibleStorage() &&
1520 "DeclContext has no visible decls in storage");
1521 uint64_t Offset = DeclContextOffsets[DC].second;
1522 assert(Offset && "DeclContext has no visible decls in storage");
1523
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001524 // Keep track of where we are in the stream, then jump back there
1525 // after reading this context.
1526 SavedStreamPosition SavedPosition(Stream);
1527
Douglas Gregorc34897d2009-04-09 22:27:44 +00001528 // Load the record containing all of the declarations visible in
1529 // this context.
1530 Stream.JumpToBit(Offset);
1531 RecordData Record;
1532 unsigned Code = Stream.ReadCode();
1533 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001534 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001535 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1536 if (Record.size() == 0)
1537 return false;
1538
1539 Decls.clear();
1540
1541 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001542 while (Idx < Record.size()) {
1543 Decls.push_back(VisibleDeclaration());
1544 Decls.back().Name = ReadDeclarationName(Record, Idx);
1545
Douglas Gregorc34897d2009-04-09 22:27:44 +00001546 unsigned Size = Record[Idx++];
1547 llvm::SmallVector<unsigned, 4> & LoadedDecls
1548 = Decls.back().Declarations;
1549 LoadedDecls.reserve(Size);
1550 for (unsigned I = 0; I < Size; ++I)
1551 LoadedDecls.push_back(Record[Idx++]);
1552 }
1553
1554 return false;
1555}
1556
Douglas Gregor631f6c62009-04-14 00:24:19 +00001557void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1558 if (!Consumer)
1559 return;
1560
1561 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1562 Decl *D = GetDecl(ExternalDefinitions[I]);
1563 DeclGroupRef DG(D);
1564 Consumer->HandleTopLevelDecl(DG);
1565 }
1566}
1567
Douglas Gregorc34897d2009-04-09 22:27:44 +00001568void PCHReader::PrintStats() {
1569 std::fprintf(stderr, "*** PCH Statistics:\n");
1570
1571 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1572 TypeAlreadyLoaded.end(),
1573 true);
1574 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1575 DeclAlreadyLoaded.end(),
1576 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001577 unsigned NumIdentifiersLoaded = 0;
1578 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1579 if ((IdentifierData[I] & 0x01) == 0)
1580 ++NumIdentifiersLoaded;
1581 }
1582
Douglas Gregorc34897d2009-04-09 22:27:44 +00001583 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1584 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001585 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001586 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1587 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001588 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1589 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1590 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1591 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001592 std::fprintf(stderr, "\n");
1593}
1594
Chris Lattner29241862009-04-11 21:15:38 +00001595IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001596 if (ID == 0)
1597 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001598
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001599 if (!IdentifierTable || IdentifierData.empty()) {
1600 Error("No identifier table in PCH file");
1601 return 0;
1602 }
Chris Lattner29241862009-04-11 21:15:38 +00001603
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001604 if (IdentifierData[ID - 1] & 0x01) {
1605 uint64_t Offset = IdentifierData[ID - 1];
1606 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001607 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001608 }
Chris Lattner29241862009-04-11 21:15:38 +00001609
1610 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001611}
1612
1613DeclarationName
1614PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1615 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1616 switch (Kind) {
1617 case DeclarationName::Identifier:
1618 return DeclarationName(GetIdentifierInfo(Record, Idx));
1619
1620 case DeclarationName::ObjCZeroArgSelector:
1621 case DeclarationName::ObjCOneArgSelector:
1622 case DeclarationName::ObjCMultiArgSelector:
1623 assert(false && "Unable to de-serialize Objective-C selectors");
1624 break;
1625
1626 case DeclarationName::CXXConstructorName:
1627 return Context.DeclarationNames.getCXXConstructorName(
1628 GetType(Record[Idx++]));
1629
1630 case DeclarationName::CXXDestructorName:
1631 return Context.DeclarationNames.getCXXDestructorName(
1632 GetType(Record[Idx++]));
1633
1634 case DeclarationName::CXXConversionFunctionName:
1635 return Context.DeclarationNames.getCXXConversionFunctionName(
1636 GetType(Record[Idx++]));
1637
1638 case DeclarationName::CXXOperatorName:
1639 return Context.DeclarationNames.getCXXOperatorName(
1640 (OverloadedOperatorKind)Record[Idx++]);
1641
1642 case DeclarationName::CXXUsingDirective:
1643 return DeclarationName::getUsingDirectiveName();
1644 }
1645
1646 // Required to silence GCC warning
1647 return DeclarationName();
1648}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001649
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001650/// \brief Read an integral value
1651llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1652 unsigned BitWidth = Record[Idx++];
1653 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1654 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1655 Idx += NumWords;
1656 return Result;
1657}
1658
1659/// \brief Read a signed integral value
1660llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1661 bool isUnsigned = Record[Idx++];
1662 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1663}
1664
Douglas Gregore2f37202009-04-14 21:55:33 +00001665/// \brief Read a floating-point value
1666llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00001667 return llvm::APFloat(ReadAPInt(Record, Idx));
1668}
1669
Douglas Gregor1c507882009-04-15 21:30:51 +00001670// \brief Read a string
1671std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
1672 unsigned Len = Record[Idx++];
1673 std::string Result(&Record[Idx], &Record[Idx] + Len);
1674 Idx += Len;
1675 return Result;
1676}
1677
1678/// \brief Reads attributes from the current stream position.
1679Attr *PCHReader::ReadAttributes() {
1680 unsigned Code = Stream.ReadCode();
1681 assert(Code == llvm::bitc::UNABBREV_RECORD &&
1682 "Expected unabbreviated record"); (void)Code;
1683
1684 RecordData Record;
1685 unsigned Idx = 0;
1686 unsigned RecCode = Stream.ReadRecord(Code, Record);
1687 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
1688 (void)RecCode;
1689
1690#define SIMPLE_ATTR(Name) \
1691 case Attr::Name: \
1692 New = ::new (Context) Name##Attr(); \
1693 break
1694
1695#define STRING_ATTR(Name) \
1696 case Attr::Name: \
1697 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
1698 break
1699
1700#define UNSIGNED_ATTR(Name) \
1701 case Attr::Name: \
1702 New = ::new (Context) Name##Attr(Record[Idx++]); \
1703 break
1704
1705 Attr *Attrs = 0;
1706 while (Idx < Record.size()) {
1707 Attr *New = 0;
1708 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
1709 bool IsInherited = Record[Idx++];
1710
1711 switch (Kind) {
1712 STRING_ATTR(Alias);
1713 UNSIGNED_ATTR(Aligned);
1714 SIMPLE_ATTR(AlwaysInline);
1715 SIMPLE_ATTR(AnalyzerNoReturn);
1716 STRING_ATTR(Annotate);
1717 STRING_ATTR(AsmLabel);
1718
1719 case Attr::Blocks:
1720 New = ::new (Context) BlocksAttr(
1721 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
1722 break;
1723
1724 case Attr::Cleanup:
1725 New = ::new (Context) CleanupAttr(
1726 cast<FunctionDecl>(GetDecl(Record[Idx++])));
1727 break;
1728
1729 SIMPLE_ATTR(Const);
1730 UNSIGNED_ATTR(Constructor);
1731 SIMPLE_ATTR(DLLExport);
1732 SIMPLE_ATTR(DLLImport);
1733 SIMPLE_ATTR(Deprecated);
1734 UNSIGNED_ATTR(Destructor);
1735 SIMPLE_ATTR(FastCall);
1736
1737 case Attr::Format: {
1738 std::string Type = ReadString(Record, Idx);
1739 unsigned FormatIdx = Record[Idx++];
1740 unsigned FirstArg = Record[Idx++];
1741 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
1742 break;
1743 }
1744
1745 SIMPLE_ATTR(GNUCInline);
1746
1747 case Attr::IBOutletKind:
1748 New = ::new (Context) IBOutletAttr();
1749 break;
1750
1751 SIMPLE_ATTR(NoReturn);
1752 SIMPLE_ATTR(NoThrow);
1753 SIMPLE_ATTR(Nodebug);
1754 SIMPLE_ATTR(Noinline);
1755
1756 case Attr::NonNull: {
1757 unsigned Size = Record[Idx++];
1758 llvm::SmallVector<unsigned, 16> ArgNums;
1759 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
1760 Idx += Size;
1761 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
1762 break;
1763 }
1764
1765 SIMPLE_ATTR(ObjCException);
1766 SIMPLE_ATTR(ObjCNSObject);
1767 SIMPLE_ATTR(Overloadable);
1768 UNSIGNED_ATTR(Packed);
1769 SIMPLE_ATTR(Pure);
1770 UNSIGNED_ATTR(Regparm);
1771 STRING_ATTR(Section);
1772 SIMPLE_ATTR(StdCall);
1773 SIMPLE_ATTR(TransparentUnion);
1774 SIMPLE_ATTR(Unavailable);
1775 SIMPLE_ATTR(Unused);
1776 SIMPLE_ATTR(Used);
1777
1778 case Attr::Visibility:
1779 New = ::new (Context) VisibilityAttr(
1780 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
1781 break;
1782
1783 SIMPLE_ATTR(WarnUnusedResult);
1784 SIMPLE_ATTR(Weak);
1785 SIMPLE_ATTR(WeakImport);
1786 }
1787
1788 assert(New && "Unable to decode attribute?");
1789 New->setInherited(IsInherited);
1790 New->setNext(Attrs);
1791 Attrs = New;
1792 }
1793#undef UNSIGNED_ATTR
1794#undef STRING_ATTR
1795#undef SIMPLE_ATTR
1796
1797 // The list of attributes was built backwards. Reverse the list
1798 // before returning it.
1799 Attr *PrevAttr = 0, *NextAttr = 0;
1800 while (Attrs) {
1801 NextAttr = Attrs->getNext();
1802 Attrs->setNext(PrevAttr);
1803 PrevAttr = Attrs;
1804 Attrs = NextAttr;
1805 }
1806
1807 return PrevAttr;
1808}
1809
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001810Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001811 // Within the bitstream, expressions are stored in Reverse Polish
1812 // Notation, with each of the subexpressions preceding the
1813 // expression they are stored in. To evaluate expressions, we
1814 // continue reading expressions and placing them on the stack, with
1815 // expressions having operands removing those operands from the
1816 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1817 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001818 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001819 unsigned Idx;
1820 llvm::SmallVector<Expr *, 16> ExprStack;
1821 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001822 Stmt::EmptyShell Empty;
1823
Douglas Gregora151ba42009-04-14 23:32:43 +00001824 while (true) {
1825 unsigned Code = Stream.ReadCode();
1826 if (Code == llvm::bitc::END_BLOCK) {
1827 if (Stream.ReadBlockEnd()) {
1828 Error("Error at end of Source Manager block");
1829 return 0;
1830 }
1831 break;
1832 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001833
Douglas Gregora151ba42009-04-14 23:32:43 +00001834 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1835 // No known subblocks, always skip them.
1836 Stream.ReadSubBlockID();
1837 if (Stream.SkipBlock()) {
1838 Error("Malformed block record");
1839 return 0;
1840 }
1841 continue;
1842 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001843
Douglas Gregora151ba42009-04-14 23:32:43 +00001844 if (Code == llvm::bitc::DEFINE_ABBREV) {
1845 Stream.ReadAbbrevRecord();
1846 continue;
1847 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001848
Douglas Gregora151ba42009-04-14 23:32:43 +00001849 Expr *E = 0;
1850 Idx = 0;
1851 Record.clear();
1852 bool Finished = false;
1853 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1854 case pch::EXPR_STOP:
1855 Finished = true;
1856 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001857
Douglas Gregora151ba42009-04-14 23:32:43 +00001858 case pch::EXPR_NULL:
1859 E = 0;
1860 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001861
Douglas Gregora151ba42009-04-14 23:32:43 +00001862 case pch::EXPR_PREDEFINED:
1863 // FIXME: untested (until we can serialize function bodies).
1864 E = new (Context) PredefinedExpr(Empty);
1865 break;
1866
1867 case pch::EXPR_DECL_REF:
1868 E = new (Context) DeclRefExpr(Empty);
1869 break;
1870
1871 case pch::EXPR_INTEGER_LITERAL:
1872 E = new (Context) IntegerLiteral(Empty);
1873 break;
1874
1875 case pch::EXPR_FLOATING_LITERAL:
1876 E = new (Context) FloatingLiteral(Empty);
1877 break;
1878
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00001879 case pch::EXPR_IMAGINARY_LITERAL:
1880 E = new (Context) ImaginaryLiteral(Empty);
1881 break;
1882
Douglas Gregor596e0932009-04-15 16:35:07 +00001883 case pch::EXPR_STRING_LITERAL:
1884 E = StringLiteral::CreateEmpty(Context,
1885 Record[PCHStmtReader::NumExprFields + 1]);
1886 break;
1887
Douglas Gregora151ba42009-04-14 23:32:43 +00001888 case pch::EXPR_CHARACTER_LITERAL:
1889 E = new (Context) CharacterLiteral(Empty);
1890 break;
1891
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001892 case pch::EXPR_PAREN:
1893 E = new (Context) ParenExpr(Empty);
1894 break;
1895
Douglas Gregor12d74052009-04-15 15:58:59 +00001896 case pch::EXPR_UNARY_OPERATOR:
1897 E = new (Context) UnaryOperator(Empty);
1898 break;
1899
1900 case pch::EXPR_SIZEOF_ALIGN_OF:
1901 E = new (Context) SizeOfAlignOfExpr(Empty);
1902 break;
1903
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00001904 case pch::EXPR_ARRAY_SUBSCRIPT:
1905 E = new (Context) ArraySubscriptExpr(Empty);
1906 break;
1907
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00001908 case pch::EXPR_CALL:
1909 E = new (Context) CallExpr(Context, Empty);
1910 break;
1911
1912 case pch::EXPR_MEMBER:
1913 E = new (Context) MemberExpr(Empty);
1914 break;
1915
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001916 case pch::EXPR_BINARY_OPERATOR:
1917 E = new (Context) BinaryOperator(Empty);
1918 break;
1919
Douglas Gregora151ba42009-04-14 23:32:43 +00001920 case pch::EXPR_IMPLICIT_CAST:
1921 E = new (Context) ImplicitCastExpr(Empty);
1922 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001923
1924 case pch::EXPR_CSTYLE_CAST:
1925 E = new (Context) CStyleCastExpr(Empty);
1926 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001927 }
1928
1929 // We hit an EXPR_STOP, so we're done with this expression.
1930 if (Finished)
1931 break;
1932
1933 if (E) {
1934 unsigned NumSubExprs = Reader.Visit(E);
1935 while (NumSubExprs > 0) {
1936 ExprStack.pop_back();
1937 --NumSubExprs;
1938 }
1939 }
1940
1941 assert(Idx == Record.size() && "Invalid deserialization of expression");
1942 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001943 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001944 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1945 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001946}
1947
Douglas Gregor179cfb12009-04-10 20:39:37 +00001948DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001949 return Diag(SourceLocation(), DiagID);
1950}
1951
1952DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1953 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001954 Context.getSourceManager()),
1955 DiagID);
1956}