blob: 2da35a09d64bef3e84bc0f008194a988c9542819 [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 Gregorc599bbf2009-04-15 22:40:36 +0000255 unsigned VisitCompoundAssignOperator(CompoundAssignOperator *E);
256 unsigned VisitConditionalOperator(ConditionalOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000257 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000258 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
259 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorec0b8292009-04-15 23:02:49 +0000260 unsigned VisitExtVectorElementExpr(ExtVectorElementExpr *E);
Douglas Gregor6710a3c2009-04-16 00:55:48 +0000261 unsigned VisitInitListExpr(InitListExpr *E);
262 unsigned VisitDesignatedInitExpr(DesignatedInitExpr *E);
263 unsigned VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Douglas Gregorec0b8292009-04-15 23:02:49 +0000264 unsigned VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor209d4622009-04-15 23:33:31 +0000265 unsigned VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
266 unsigned VisitChooseExpr(ChooseExpr *E);
267 unsigned VisitGNUNullExpr(GNUNullExpr *E);
Douglas Gregor725e94b2009-04-16 00:01:45 +0000268 unsigned VisitShuffleVectorExpr(ShuffleVectorExpr *E);
269 unsigned VisitBlockDeclRefExpr(BlockDeclRefExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000270 };
271}
272
Douglas Gregora151ba42009-04-14 23:32:43 +0000273unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000274 E->setType(Reader.GetType(Record[Idx++]));
275 E->setTypeDependent(Record[Idx++]);
276 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000277 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000278 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000279}
280
Douglas Gregora151ba42009-04-14 23:32:43 +0000281unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000282 VisitExpr(E);
283 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
284 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000285 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000286}
287
Douglas Gregora151ba42009-04-14 23:32:43 +0000288unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000289 VisitExpr(E);
290 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
291 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000292 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000293}
294
Douglas Gregora151ba42009-04-14 23:32:43 +0000295unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000296 VisitExpr(E);
297 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
298 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000299 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000300}
301
Douglas Gregora151ba42009-04-14 23:32:43 +0000302unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000303 VisitExpr(E);
304 E->setValue(Reader.ReadAPFloat(Record, Idx));
305 E->setExact(Record[Idx++]);
306 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000307 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000308}
309
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000310unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) {
311 VisitExpr(E);
312 E->setSubExpr(ExprStack.back());
313 return 1;
314}
315
Douglas Gregor596e0932009-04-15 16:35:07 +0000316unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
317 VisitExpr(E);
318 unsigned Len = Record[Idx++];
319 assert(Record[Idx] == E->getNumConcatenated() &&
320 "Wrong number of concatenated tokens!");
321 ++Idx;
322 E->setWide(Record[Idx++]);
323
324 // Read string data
325 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
326 E->setStrData(Reader.getContext(), &Str[0], Len);
327 Idx += Len;
328
329 // Read source locations
330 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
331 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
332
333 return 0;
334}
335
Douglas Gregora151ba42009-04-14 23:32:43 +0000336unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000337 VisitExpr(E);
338 E->setValue(Record[Idx++]);
339 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
340 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000341 return 0;
342}
343
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000344unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
345 VisitExpr(E);
346 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
347 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
348 E->setSubExpr(ExprStack.back());
349 return 1;
350}
351
Douglas Gregor12d74052009-04-15 15:58:59 +0000352unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
353 VisitExpr(E);
354 E->setSubExpr(ExprStack.back());
355 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
356 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
357 return 1;
358}
359
360unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
361 VisitExpr(E);
362 E->setSizeof(Record[Idx++]);
363 if (Record[Idx] == 0) {
364 E->setArgument(ExprStack.back());
365 ++Idx;
366 } else {
367 E->setArgument(Reader.GetType(Record[Idx++]));
368 }
369 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
370 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
371 return E->isArgumentType()? 0 : 1;
372}
373
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000374unsigned PCHStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
375 VisitExpr(E);
376 E->setLHS(ExprStack[ExprStack.size() - 2]);
377 E->setRHS(ExprStack[ExprStack.size() - 2]);
378 E->setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
379 return 2;
380}
381
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000382unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
383 VisitExpr(E);
384 E->setNumArgs(Reader.getContext(), Record[Idx++]);
385 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
386 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
387 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
388 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
389 return E->getNumArgs() + 1;
390}
391
392unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
393 VisitExpr(E);
394 E->setBase(ExprStack.back());
395 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
396 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
397 E->setArrow(Record[Idx++]);
398 return 1;
399}
400
Douglas Gregora151ba42009-04-14 23:32:43 +0000401unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
402 VisitExpr(E);
403 E->setSubExpr(ExprStack.back());
404 return 1;
405}
406
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000407unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
408 VisitExpr(E);
409 E->setLHS(ExprStack.end()[-2]);
410 E->setRHS(ExprStack.end()[-1]);
411 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
412 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
413 return 2;
414}
415
Douglas Gregorc599bbf2009-04-15 22:40:36 +0000416unsigned PCHStmtReader::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
417 VisitBinaryOperator(E);
418 E->setComputationLHSType(Reader.GetType(Record[Idx++]));
419 E->setComputationResultType(Reader.GetType(Record[Idx++]));
420 return 2;
421}
422
423unsigned PCHStmtReader::VisitConditionalOperator(ConditionalOperator *E) {
424 VisitExpr(E);
425 E->setCond(ExprStack[ExprStack.size() - 3]);
426 E->setLHS(ExprStack[ExprStack.size() - 2]);
427 E->setRHS(ExprStack[ExprStack.size() - 1]);
428 return 3;
429}
430
Douglas Gregora151ba42009-04-14 23:32:43 +0000431unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
432 VisitCastExpr(E);
433 E->setLvalueCast(Record[Idx++]);
434 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000435}
436
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000437unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
438 VisitCastExpr(E);
439 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
440 return 1;
441}
442
443unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
444 VisitExplicitCastExpr(E);
445 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
446 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
447 return 1;
448}
449
Douglas Gregorec0b8292009-04-15 23:02:49 +0000450unsigned PCHStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) {
451 VisitExpr(E);
452 E->setBase(ExprStack.back());
453 E->setAccessor(Reader.GetIdentifierInfo(Record, Idx));
454 E->setAccessorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
455 return 1;
456}
457
Douglas Gregor6710a3c2009-04-16 00:55:48 +0000458unsigned PCHStmtReader::VisitInitListExpr(InitListExpr *E) {
459 VisitExpr(E);
460 unsigned NumInits = Record[Idx++];
461 E->reserveInits(NumInits);
462 for (unsigned I = 0; I != NumInits; ++I)
463 E->updateInit(I, ExprStack[ExprStack.size() - NumInits - 1 + I]);
464 E->setSyntacticForm(cast_or_null<InitListExpr>(ExprStack.back()));
465 E->setLBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
466 E->setRBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
467 E->setInitializedFieldInUnion(
468 cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++])));
469 E->sawArrayRangeDesignator(Record[Idx++]);
470 return NumInits + 1;
471}
472
473unsigned PCHStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
474 typedef DesignatedInitExpr::Designator Designator;
475
476 VisitExpr(E);
477 unsigned NumSubExprs = Record[Idx++];
478 assert(NumSubExprs == E->getNumSubExprs() && "Wrong number of subexprs");
479 for (unsigned I = 0; I != NumSubExprs; ++I)
480 E->setSubExpr(I, ExprStack[ExprStack.size() - NumSubExprs + I]);
481 E->setEqualOrColonLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
482 E->setGNUSyntax(Record[Idx++]);
483
484 llvm::SmallVector<Designator, 4> Designators;
485 while (Idx < Record.size()) {
486 switch ((pch::DesignatorTypes)Record[Idx++]) {
487 case pch::DESIG_FIELD_DECL: {
488 FieldDecl *Field = cast<FieldDecl>(Reader.GetDecl(Record[Idx++]));
489 SourceLocation DotLoc
490 = SourceLocation::getFromRawEncoding(Record[Idx++]);
491 SourceLocation FieldLoc
492 = SourceLocation::getFromRawEncoding(Record[Idx++]);
493 Designators.push_back(Designator(Field->getIdentifier(), DotLoc,
494 FieldLoc));
495 Designators.back().setField(Field);
496 break;
497 }
498
499 case pch::DESIG_FIELD_NAME: {
500 const IdentifierInfo *Name = Reader.GetIdentifierInfo(Record, Idx);
501 SourceLocation DotLoc
502 = SourceLocation::getFromRawEncoding(Record[Idx++]);
503 SourceLocation FieldLoc
504 = SourceLocation::getFromRawEncoding(Record[Idx++]);
505 Designators.push_back(Designator(Name, DotLoc, FieldLoc));
506 break;
507 }
508
509 case pch::DESIG_ARRAY: {
510 unsigned Index = Record[Idx++];
511 SourceLocation LBracketLoc
512 = SourceLocation::getFromRawEncoding(Record[Idx++]);
513 SourceLocation RBracketLoc
514 = SourceLocation::getFromRawEncoding(Record[Idx++]);
515 Designators.push_back(Designator(Index, LBracketLoc, RBracketLoc));
516 break;
517 }
518
519 case pch::DESIG_ARRAY_RANGE: {
520 unsigned Index = Record[Idx++];
521 SourceLocation LBracketLoc
522 = SourceLocation::getFromRawEncoding(Record[Idx++]);
523 SourceLocation EllipsisLoc
524 = SourceLocation::getFromRawEncoding(Record[Idx++]);
525 SourceLocation RBracketLoc
526 = SourceLocation::getFromRawEncoding(Record[Idx++]);
527 Designators.push_back(Designator(Index, LBracketLoc, EllipsisLoc,
528 RBracketLoc));
529 break;
530 }
531 }
532 }
533 E->setDesignators(&Designators[0], Designators.size());
534
535 return NumSubExprs;
536}
537
538unsigned PCHStmtReader::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
539 VisitExpr(E);
540 return 0;
541}
542
Douglas Gregorec0b8292009-04-15 23:02:49 +0000543unsigned PCHStmtReader::VisitVAArgExpr(VAArgExpr *E) {
544 VisitExpr(E);
545 E->setSubExpr(ExprStack.back());
546 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
547 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
548 return 1;
549}
550
Douglas Gregor209d4622009-04-15 23:33:31 +0000551unsigned PCHStmtReader::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
552 VisitExpr(E);
553 E->setArgType1(Reader.GetType(Record[Idx++]));
554 E->setArgType2(Reader.GetType(Record[Idx++]));
555 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
556 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
557 return 0;
558}
559
560unsigned PCHStmtReader::VisitChooseExpr(ChooseExpr *E) {
561 VisitExpr(E);
562 E->setCond(ExprStack[ExprStack.size() - 3]);
563 E->setLHS(ExprStack[ExprStack.size() - 2]);
564 E->setRHS(ExprStack[ExprStack.size() - 1]);
565 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
566 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
567 return 3;
568}
569
570unsigned PCHStmtReader::VisitGNUNullExpr(GNUNullExpr *E) {
571 VisitExpr(E);
572 E->setTokenLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
573 return 0;
574}
Douglas Gregorec0b8292009-04-15 23:02:49 +0000575
Douglas Gregor725e94b2009-04-16 00:01:45 +0000576unsigned PCHStmtReader::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
577 VisitExpr(E);
578 unsigned NumExprs = Record[Idx++];
579 E->setExprs(&ExprStack[ExprStack.size() - NumExprs], NumExprs);
580 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
581 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
582 return NumExprs;
583}
584
585unsigned PCHStmtReader::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
586 VisitExpr(E);
587 E->setDecl(cast<ValueDecl>(Reader.GetDecl(Record[Idx++])));
588 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
589 E->setByRef(Record[Idx++]);
590 return 0;
591}
592
Douglas Gregorc34897d2009-04-09 22:27:44 +0000593// FIXME: use the diagnostics machinery
594static bool Error(const char *Str) {
595 std::fprintf(stderr, "%s\n", Str);
596 return true;
597}
598
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000599/// \brief Check the contents of the predefines buffer against the
600/// contents of the predefines buffer used to build the PCH file.
601///
602/// The contents of the two predefines buffers should be the same. If
603/// not, then some command-line option changed the preprocessor state
604/// and we must reject the PCH file.
605///
606/// \param PCHPredef The start of the predefines buffer in the PCH
607/// file.
608///
609/// \param PCHPredefLen The length of the predefines buffer in the PCH
610/// file.
611///
612/// \param PCHBufferID The FileID for the PCH predefines buffer.
613///
614/// \returns true if there was a mismatch (in which case the PCH file
615/// should be ignored), or false otherwise.
616bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
617 unsigned PCHPredefLen,
618 FileID PCHBufferID) {
619 const char *Predef = PP.getPredefines().c_str();
620 unsigned PredefLen = PP.getPredefines().size();
621
622 // If the two predefines buffers compare equal, we're done!.
623 if (PredefLen == PCHPredefLen &&
624 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
625 return false;
626
627 // The predefines buffers are different. Produce a reasonable
628 // diagnostic showing where they are different.
629
630 // The source locations (potentially in the two different predefines
631 // buffers)
632 SourceLocation Loc1, Loc2;
633 SourceManager &SourceMgr = PP.getSourceManager();
634
635 // Create a source buffer for our predefines string, so
636 // that we can build a diagnostic that points into that
637 // source buffer.
638 FileID BufferID;
639 if (Predef && Predef[0]) {
640 llvm::MemoryBuffer *Buffer
641 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
642 "<built-in>");
643 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
644 }
645
646 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
647 std::pair<const char *, const char *> Locations
648 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
649
650 if (Locations.first != Predef + MinLen) {
651 // We found the location in the two buffers where there is a
652 // difference. Form source locations to point there (in both
653 // buffers).
654 unsigned Offset = Locations.first - Predef;
655 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
656 .getFileLocWithOffset(Offset);
657 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
658 .getFileLocWithOffset(Offset);
659 } else if (PredefLen > PCHPredefLen) {
660 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
661 .getFileLocWithOffset(MinLen);
662 } else {
663 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
664 .getFileLocWithOffset(MinLen);
665 }
666
667 Diag(Loc1, diag::warn_pch_preprocessor);
668 if (Loc2.isValid())
669 Diag(Loc2, diag::note_predef_in_pch);
670 Diag(diag::note_ignoring_pch) << FileName;
671 return true;
672}
673
Douglas Gregor635f97f2009-04-13 16:31:14 +0000674/// \brief Read the line table in the source manager block.
675/// \returns true if ther was an error.
676static bool ParseLineTable(SourceManager &SourceMgr,
677 llvm::SmallVectorImpl<uint64_t> &Record) {
678 unsigned Idx = 0;
679 LineTableInfo &LineTable = SourceMgr.getLineTable();
680
681 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000682 std::map<int, int> FileIDs;
683 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000684 // Extract the file name
685 unsigned FilenameLen = Record[Idx++];
686 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
687 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000688 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
689 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000690 }
691
692 // Parse the line entries
693 std::vector<LineEntry> Entries;
694 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000695 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000696
697 // Extract the line entries
698 unsigned NumEntries = Record[Idx++];
699 Entries.clear();
700 Entries.reserve(NumEntries);
701 for (unsigned I = 0; I != NumEntries; ++I) {
702 unsigned FileOffset = Record[Idx++];
703 unsigned LineNo = Record[Idx++];
704 int FilenameID = Record[Idx++];
705 SrcMgr::CharacteristicKind FileKind
706 = (SrcMgr::CharacteristicKind)Record[Idx++];
707 unsigned IncludeOffset = Record[Idx++];
708 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
709 FileKind, IncludeOffset));
710 }
711 LineTable.AddEntry(FID, Entries);
712 }
713
714 return false;
715}
716
Douglas Gregorab1cef72009-04-10 03:52:48 +0000717/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000718PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000719 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000720 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
721 Error("Malformed source manager block record");
722 return Failure;
723 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000724
725 SourceManager &SourceMgr = Context.getSourceManager();
726 RecordData Record;
727 while (true) {
728 unsigned Code = Stream.ReadCode();
729 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000730 if (Stream.ReadBlockEnd()) {
731 Error("Error at end of Source Manager block");
732 return Failure;
733 }
734
735 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000736 }
737
738 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
739 // No known subblocks, always skip them.
740 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000741 if (Stream.SkipBlock()) {
742 Error("Malformed block record");
743 return Failure;
744 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000745 continue;
746 }
747
748 if (Code == llvm::bitc::DEFINE_ABBREV) {
749 Stream.ReadAbbrevRecord();
750 continue;
751 }
752
753 // Read a record.
754 const char *BlobStart;
755 unsigned BlobLen;
756 Record.clear();
757 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
758 default: // Default behavior: ignore.
759 break;
760
761 case pch::SM_SLOC_FILE_ENTRY: {
762 // FIXME: We would really like to delay the creation of this
763 // FileEntry until it is actually required, e.g., when producing
764 // a diagnostic with a source location in this file.
765 const FileEntry *File
766 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
767 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000768 FileID ID = SourceMgr.createFileID(File,
769 SourceLocation::getFromRawEncoding(Record[1]),
770 (CharacteristicKind)Record[2]);
771 if (Record[3])
772 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
773 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000774 break;
775 }
776
777 case pch::SM_SLOC_BUFFER_ENTRY: {
778 const char *Name = BlobStart;
779 unsigned Code = Stream.ReadCode();
780 Record.clear();
781 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
782 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000783 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000784 llvm::MemoryBuffer *Buffer
785 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
786 BlobStart + BlobLen - 1,
787 Name);
788 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
789
790 if (strcmp(Name, "<built-in>") == 0
791 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
792 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000793 break;
794 }
795
796 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
797 SourceLocation SpellingLoc
798 = SourceLocation::getFromRawEncoding(Record[1]);
799 SourceMgr.createInstantiationLoc(
800 SpellingLoc,
801 SourceLocation::getFromRawEncoding(Record[2]),
802 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000803 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000804 break;
805 }
806
Chris Lattnere1be6022009-04-14 23:22:57 +0000807 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000808 if (ParseLineTable(SourceMgr, Record))
809 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000810 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000811 }
812 }
813}
814
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000815bool PCHReader::ReadPreprocessorBlock() {
816 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
817 return Error("Malformed preprocessor block record");
818
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000819 RecordData Record;
820 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
821 MacroInfo *LastMacro = 0;
822
823 while (true) {
824 unsigned Code = Stream.ReadCode();
825 switch (Code) {
826 case llvm::bitc::END_BLOCK:
827 if (Stream.ReadBlockEnd())
828 return Error("Error at end of preprocessor block");
829 return false;
830
831 case llvm::bitc::ENTER_SUBBLOCK:
832 // No known subblocks, always skip them.
833 Stream.ReadSubBlockID();
834 if (Stream.SkipBlock())
835 return Error("Malformed block record");
836 continue;
837
838 case llvm::bitc::DEFINE_ABBREV:
839 Stream.ReadAbbrevRecord();
840 continue;
841 default: break;
842 }
843
844 // Read a record.
845 Record.clear();
846 pch::PreprocessorRecordTypes RecType =
847 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
848 switch (RecType) {
849 default: // Default behavior: ignore unknown records.
850 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000851 case pch::PP_COUNTER_VALUE:
852 if (!Record.empty())
853 PP.setCounterValue(Record[0]);
854 break;
855
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000856 case pch::PP_MACRO_OBJECT_LIKE:
857 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000858 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
859 if (II == 0)
860 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000861 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
862 bool isUsed = Record[2];
863
864 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
865 MI->setIsUsed(isUsed);
866
867 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
868 // Decode function-like macro info.
869 bool isC99VarArgs = Record[3];
870 bool isGNUVarArgs = Record[4];
871 MacroArgs.clear();
872 unsigned NumArgs = Record[5];
873 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000874 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000875
876 // Install function-like macro info.
877 MI->setIsFunctionLike();
878 if (isC99VarArgs) MI->setIsC99Varargs();
879 if (isGNUVarArgs) MI->setIsGNUVarargs();
880 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
881 PP.getPreprocessorAllocator());
882 }
883
884 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000885 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000886
887 // Remember that we saw this macro last so that we add the tokens that
888 // form its body to it.
889 LastMacro = MI;
890 break;
891 }
892
893 case pch::PP_TOKEN: {
894 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
895 // pretend we didn't see this.
896 if (LastMacro == 0) break;
897
898 Token Tok;
899 Tok.startToken();
900 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
901 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000902 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
903 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000904 Tok.setKind((tok::TokenKind)Record[3]);
905 Tok.setFlag((Token::TokenFlags)Record[4]);
906 LastMacro->AddTokenToBody(Tok);
907 break;
908 }
909 }
910 }
911}
912
Douglas Gregor179cfb12009-04-10 20:39:37 +0000913PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
914 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
915 Error("Malformed block record");
916 return Failure;
917 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000918
Chris Lattner29241862009-04-11 21:15:38 +0000919 uint64_t PreprocessorBlockBit = 0;
920
Douglas Gregorc34897d2009-04-09 22:27:44 +0000921 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000922 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000923 while (!Stream.AtEndOfStream()) {
924 unsigned Code = Stream.ReadCode();
925 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000926 // If we saw the preprocessor block, read it now.
927 if (PreprocessorBlockBit) {
928 uint64_t SavedPos = Stream.GetCurrentBitNo();
929 Stream.JumpToBit(PreprocessorBlockBit);
930 if (ReadPreprocessorBlock()) {
931 Error("Malformed preprocessor block");
932 return Failure;
933 }
934 Stream.JumpToBit(SavedPos);
935 }
936
Douglas Gregor179cfb12009-04-10 20:39:37 +0000937 if (Stream.ReadBlockEnd()) {
938 Error("Error at end of module block");
939 return Failure;
940 }
Chris Lattner29241862009-04-11 21:15:38 +0000941
Douglas Gregor179cfb12009-04-10 20:39:37 +0000942 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000943 }
944
945 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
946 switch (Stream.ReadSubBlockID()) {
947 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
948 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
949 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000950 if (Stream.SkipBlock()) {
951 Error("Malformed block record");
952 return Failure;
953 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000954 break;
955
Chris Lattner29241862009-04-11 21:15:38 +0000956 case pch::PREPROCESSOR_BLOCK_ID:
957 // Skip the preprocessor block for now, but remember where it is. We
958 // want to read it in after the identifier table.
959 if (PreprocessorBlockBit) {
960 Error("Multiple preprocessor blocks found.");
961 return Failure;
962 }
963 PreprocessorBlockBit = Stream.GetCurrentBitNo();
964 if (Stream.SkipBlock()) {
965 Error("Malformed block record");
966 return Failure;
967 }
968 break;
969
Douglas Gregorab1cef72009-04-10 03:52:48 +0000970 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000971 switch (ReadSourceManagerBlock()) {
972 case Success:
973 break;
974
975 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000976 Error("Malformed source manager block");
977 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000978
979 case IgnorePCH:
980 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000981 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000982 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000983 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000984 continue;
985 }
986
987 if (Code == llvm::bitc::DEFINE_ABBREV) {
988 Stream.ReadAbbrevRecord();
989 continue;
990 }
991
992 // Read and process a record.
993 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000994 const char *BlobStart = 0;
995 unsigned BlobLen = 0;
996 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
997 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000998 default: // Default behavior: ignore.
999 break;
1000
1001 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001002 if (!TypeOffsets.empty()) {
1003 Error("Duplicate TYPE_OFFSET record in PCH file");
1004 return Failure;
1005 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001006 TypeOffsets.swap(Record);
1007 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
1008 break;
1009
1010 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001011 if (!DeclOffsets.empty()) {
1012 Error("Duplicate DECL_OFFSET record in PCH file");
1013 return Failure;
1014 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001015 DeclOffsets.swap(Record);
1016 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
1017 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001018
1019 case pch::LANGUAGE_OPTIONS:
1020 if (ParseLanguageOptions(Record))
1021 return IgnorePCH;
1022 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001023
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001024 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +00001025 std::string TargetTriple(BlobStart, BlobLen);
1026 if (TargetTriple != Context.Target.getTargetTriple()) {
1027 Diag(diag::warn_pch_target_triple)
1028 << TargetTriple << Context.Target.getTargetTriple();
1029 Diag(diag::note_ignoring_pch) << FileName;
1030 return IgnorePCH;
1031 }
1032 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001033 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001034
1035 case pch::IDENTIFIER_TABLE:
1036 IdentifierTable = BlobStart;
1037 break;
1038
1039 case pch::IDENTIFIER_OFFSET:
1040 if (!IdentifierData.empty()) {
1041 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1042 return Failure;
1043 }
1044 IdentifierData.swap(Record);
1045#ifndef NDEBUG
1046 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
1047 if ((IdentifierData[I] & 0x01) == 0) {
1048 Error("Malformed identifier table in the precompiled header");
1049 return Failure;
1050 }
1051 }
1052#endif
1053 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001054
1055 case pch::EXTERNAL_DEFINITIONS:
1056 if (!ExternalDefinitions.empty()) {
1057 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1058 return Failure;
1059 }
1060 ExternalDefinitions.swap(Record);
1061 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001062 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001063 }
1064
Douglas Gregor179cfb12009-04-10 20:39:37 +00001065 Error("Premature end of bitstream");
1066 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001067}
1068
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001069PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001070 // Set the PCH file name.
1071 this->FileName = FileName;
1072
Douglas Gregorc34897d2009-04-09 22:27:44 +00001073 // Open the PCH file.
1074 std::string ErrStr;
1075 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001076 if (!Buffer) {
1077 Error(ErrStr.c_str());
1078 return IgnorePCH;
1079 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001080
1081 // Initialize the stream
1082 Stream.init((const unsigned char *)Buffer->getBufferStart(),
1083 (const unsigned char *)Buffer->getBufferEnd());
1084
1085 // Sniff for the signature.
1086 if (Stream.Read(8) != 'C' ||
1087 Stream.Read(8) != 'P' ||
1088 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001089 Stream.Read(8) != 'H') {
1090 Error("Not a PCH file");
1091 return IgnorePCH;
1092 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001093
1094 // We expect a number of well-defined blocks, though we don't necessarily
1095 // need to understand them all.
1096 while (!Stream.AtEndOfStream()) {
1097 unsigned Code = Stream.ReadCode();
1098
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001099 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1100 Error("Invalid record at top-level");
1101 return Failure;
1102 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001103
1104 unsigned BlockID = Stream.ReadSubBlockID();
1105
1106 // We only know the PCH subblock ID.
1107 switch (BlockID) {
1108 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001109 if (Stream.ReadBlockInfoBlock()) {
1110 Error("Malformed BlockInfoBlock");
1111 return Failure;
1112 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001113 break;
1114 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001115 switch (ReadPCHBlock()) {
1116 case Success:
1117 break;
1118
1119 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001120 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001121
1122 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001123 // FIXME: We could consider reading through to the end of this
1124 // PCH block, skipping subblocks, to see if there are other
1125 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001126 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001127 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001128 break;
1129 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001130 if (Stream.SkipBlock()) {
1131 Error("Malformed block record");
1132 return Failure;
1133 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001134 break;
1135 }
1136 }
1137
1138 // Load the translation unit declaration
1139 ReadDeclRecord(DeclOffsets[0], 0);
1140
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001141 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001142}
1143
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001144namespace {
1145 /// \brief Helper class that saves the current stream position and
1146 /// then restores it when destroyed.
1147 struct VISIBILITY_HIDDEN SavedStreamPosition {
1148 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001149 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001150
1151 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001152 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001153 }
1154
1155 private:
1156 llvm::BitstreamReader &Stream;
1157 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001158 };
1159}
1160
Douglas Gregor179cfb12009-04-10 20:39:37 +00001161/// \brief Parse the record that corresponds to a LangOptions data
1162/// structure.
1163///
1164/// This routine compares the language options used to generate the
1165/// PCH file against the language options set for the current
1166/// compilation. For each option, we classify differences between the
1167/// two compiler states as either "benign" or "important". Benign
1168/// differences don't matter, and we accept them without complaint
1169/// (and without modifying the language options). Differences between
1170/// the states for important options cause the PCH file to be
1171/// unusable, so we emit a warning and return true to indicate that
1172/// there was an error.
1173///
1174/// \returns true if the PCH file is unacceptable, false otherwise.
1175bool PCHReader::ParseLanguageOptions(
1176 const llvm::SmallVectorImpl<uint64_t> &Record) {
1177 const LangOptions &LangOpts = Context.getLangOptions();
1178#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1179#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1180 if (Record[Idx] != LangOpts.Option) { \
1181 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1182 Diag(diag::note_ignoring_pch) << FileName; \
1183 return true; \
1184 } \
1185 ++Idx
1186
1187 unsigned Idx = 0;
1188 PARSE_LANGOPT_BENIGN(Trigraphs);
1189 PARSE_LANGOPT_BENIGN(BCPLComment);
1190 PARSE_LANGOPT_BENIGN(DollarIdents);
1191 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1192 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1193 PARSE_LANGOPT_BENIGN(ImplicitInt);
1194 PARSE_LANGOPT_BENIGN(Digraphs);
1195 PARSE_LANGOPT_BENIGN(HexFloats);
1196 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1197 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1198 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1199 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1200 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1201 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1202 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1203 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1204 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1205 PARSE_LANGOPT_BENIGN(PascalStrings);
1206 PARSE_LANGOPT_BENIGN(Boolean);
1207 PARSE_LANGOPT_BENIGN(WritableStrings);
1208 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1209 diag::warn_pch_lax_vector_conversions);
1210 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1211 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1212 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1213 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1214 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1215 diag::warn_pch_thread_safe_statics);
1216 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1217 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1218 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1219 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1220 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1221 diag::warn_pch_heinous_extensions);
1222 // FIXME: Most of the options below are benign if the macro wasn't
1223 // used. Unfortunately, this means that a PCH compiled without
1224 // optimization can't be used with optimization turned on, even
1225 // though the only thing that changes is whether __OPTIMIZE__ was
1226 // defined... but if __OPTIMIZE__ never showed up in the header, it
1227 // doesn't matter. We could consider making this some special kind
1228 // of check.
1229 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1230 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1231 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1232 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1233 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1234 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1235 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1236 Diag(diag::warn_pch_gc_mode)
1237 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1238 Diag(diag::note_ignoring_pch) << FileName;
1239 return true;
1240 }
1241 ++Idx;
1242 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1243 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1244#undef PARSE_LANGOPT_IRRELEVANT
1245#undef PARSE_LANGOPT_BENIGN
1246
1247 return false;
1248}
1249
Douglas Gregorc34897d2009-04-09 22:27:44 +00001250/// \brief Read and return the type at the given offset.
1251///
1252/// This routine actually reads the record corresponding to the type
1253/// at the given offset in the bitstream. It is a helper routine for
1254/// GetType, which deals with reading type IDs.
1255QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
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 type.
1258 SavedStreamPosition SavedPosition(Stream);
1259
Douglas Gregorc34897d2009-04-09 22:27:44 +00001260 Stream.JumpToBit(Offset);
1261 RecordData Record;
1262 unsigned Code = Stream.ReadCode();
1263 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001264 case pch::TYPE_ATTR:
1265 assert(false && "Should never jump to an attribute block");
1266 return QualType();
1267
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001268 case pch::TYPE_EXT_QUAL: {
1269 assert(Record.size() == 3 &&
1270 "Incorrect encoding of extended qualifier type");
1271 QualType Base = GetType(Record[0]);
1272 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1273 unsigned AddressSpace = Record[2];
1274
1275 QualType T = Base;
1276 if (GCAttr != QualType::GCNone)
1277 T = Context.getObjCGCQualType(T, GCAttr);
1278 if (AddressSpace)
1279 T = Context.getAddrSpaceQualType(T, AddressSpace);
1280 return T;
1281 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001282
Douglas Gregorc34897d2009-04-09 22:27:44 +00001283 case pch::TYPE_FIXED_WIDTH_INT: {
1284 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1285 return Context.getFixedWidthIntType(Record[0], Record[1]);
1286 }
1287
1288 case pch::TYPE_COMPLEX: {
1289 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1290 QualType ElemType = GetType(Record[0]);
1291 return Context.getComplexType(ElemType);
1292 }
1293
1294 case pch::TYPE_POINTER: {
1295 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1296 QualType PointeeType = GetType(Record[0]);
1297 return Context.getPointerType(PointeeType);
1298 }
1299
1300 case pch::TYPE_BLOCK_POINTER: {
1301 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1302 QualType PointeeType = GetType(Record[0]);
1303 return Context.getBlockPointerType(PointeeType);
1304 }
1305
1306 case pch::TYPE_LVALUE_REFERENCE: {
1307 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1308 QualType PointeeType = GetType(Record[0]);
1309 return Context.getLValueReferenceType(PointeeType);
1310 }
1311
1312 case pch::TYPE_RVALUE_REFERENCE: {
1313 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1314 QualType PointeeType = GetType(Record[0]);
1315 return Context.getRValueReferenceType(PointeeType);
1316 }
1317
1318 case pch::TYPE_MEMBER_POINTER: {
1319 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1320 QualType PointeeType = GetType(Record[0]);
1321 QualType ClassType = GetType(Record[1]);
1322 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1323 }
1324
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001325 case pch::TYPE_CONSTANT_ARRAY: {
1326 QualType ElementType = GetType(Record[0]);
1327 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1328 unsigned IndexTypeQuals = Record[2];
1329 unsigned Idx = 3;
1330 llvm::APInt Size = ReadAPInt(Record, Idx);
1331 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1332 }
1333
1334 case pch::TYPE_INCOMPLETE_ARRAY: {
1335 QualType ElementType = GetType(Record[0]);
1336 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1337 unsigned IndexTypeQuals = Record[2];
1338 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1339 }
1340
1341 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001342 QualType ElementType = GetType(Record[0]);
1343 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1344 unsigned IndexTypeQuals = Record[2];
1345 return Context.getVariableArrayType(ElementType, ReadExpr(),
1346 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001347 }
1348
1349 case pch::TYPE_VECTOR: {
1350 if (Record.size() != 2) {
1351 Error("Incorrect encoding of vector type in PCH file");
1352 return QualType();
1353 }
1354
1355 QualType ElementType = GetType(Record[0]);
1356 unsigned NumElements = Record[1];
1357 return Context.getVectorType(ElementType, NumElements);
1358 }
1359
1360 case pch::TYPE_EXT_VECTOR: {
1361 if (Record.size() != 2) {
1362 Error("Incorrect encoding of extended vector type in PCH file");
1363 return QualType();
1364 }
1365
1366 QualType ElementType = GetType(Record[0]);
1367 unsigned NumElements = Record[1];
1368 return Context.getExtVectorType(ElementType, NumElements);
1369 }
1370
1371 case pch::TYPE_FUNCTION_NO_PROTO: {
1372 if (Record.size() != 1) {
1373 Error("Incorrect encoding of no-proto function type");
1374 return QualType();
1375 }
1376 QualType ResultType = GetType(Record[0]);
1377 return Context.getFunctionNoProtoType(ResultType);
1378 }
1379
1380 case pch::TYPE_FUNCTION_PROTO: {
1381 QualType ResultType = GetType(Record[0]);
1382 unsigned Idx = 1;
1383 unsigned NumParams = Record[Idx++];
1384 llvm::SmallVector<QualType, 16> ParamTypes;
1385 for (unsigned I = 0; I != NumParams; ++I)
1386 ParamTypes.push_back(GetType(Record[Idx++]));
1387 bool isVariadic = Record[Idx++];
1388 unsigned Quals = Record[Idx++];
1389 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1390 isVariadic, Quals);
1391 }
1392
1393 case pch::TYPE_TYPEDEF:
1394 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1395 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1396
1397 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001398 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001399
1400 case pch::TYPE_TYPEOF: {
1401 if (Record.size() != 1) {
1402 Error("Incorrect encoding of typeof(type) in PCH file");
1403 return QualType();
1404 }
1405 QualType UnderlyingType = GetType(Record[0]);
1406 return Context.getTypeOfType(UnderlyingType);
1407 }
1408
1409 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001410 assert(Record.size() == 1 && "Incorrect encoding of record type");
1411 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001412
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001413 case pch::TYPE_ENUM:
1414 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1415 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1416
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001417 case pch::TYPE_OBJC_INTERFACE:
1418 // FIXME: Deserialize ObjCInterfaceType
1419 assert(false && "Cannot de-serialize ObjC interface types yet");
1420 return QualType();
1421
1422 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1423 // FIXME: Deserialize ObjCQualifiedInterfaceType
1424 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1425 return QualType();
1426
1427 case pch::TYPE_OBJC_QUALIFIED_ID:
1428 // FIXME: Deserialize ObjCQualifiedIdType
1429 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1430 return QualType();
1431
1432 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1433 // FIXME: Deserialize ObjCQualifiedClassType
1434 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1435 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001436 }
1437
1438 // Suppress a GCC warning
1439 return QualType();
1440}
1441
1442/// \brief Note that we have loaded the declaration with the given
1443/// Index.
1444///
1445/// This routine notes that this declaration has already been loaded,
1446/// so that future GetDecl calls will return this declaration rather
1447/// than trying to load a new declaration.
1448inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1449 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1450 DeclAlreadyLoaded[Index] = true;
1451 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1452}
1453
1454/// \brief Read the declaration at the given offset from the PCH file.
1455Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001456 // Keep track of where we are in the stream, then jump back there
1457 // after reading this declaration.
1458 SavedStreamPosition SavedPosition(Stream);
1459
Douglas Gregorc34897d2009-04-09 22:27:44 +00001460 Decl *D = 0;
1461 Stream.JumpToBit(Offset);
1462 RecordData Record;
1463 unsigned Code = Stream.ReadCode();
1464 unsigned Idx = 0;
1465 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001466
Douglas Gregorc34897d2009-04-09 22:27:44 +00001467 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001468 case pch::DECL_ATTR:
1469 case pch::DECL_CONTEXT_LEXICAL:
1470 case pch::DECL_CONTEXT_VISIBLE:
1471 assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1472 break;
1473
Douglas Gregorc34897d2009-04-09 22:27:44 +00001474 case pch::DECL_TRANSLATION_UNIT:
1475 assert(Index == 0 && "Translation unit must be at index 0");
1476 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1477 D = Context.getTranslationUnitDecl();
1478 LoadedDecl(Index, D);
1479 break;
1480
1481 case pch::DECL_TYPEDEF: {
1482 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1483 0, QualType());
1484 LoadedDecl(Index, Typedef);
1485 Reader.VisitTypedefDecl(Typedef);
1486 D = Typedef;
1487 break;
1488 }
1489
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001490 case pch::DECL_ENUM: {
1491 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1492 LoadedDecl(Index, Enum);
1493 Reader.VisitEnumDecl(Enum);
1494 D = Enum;
1495 break;
1496 }
1497
Douglas Gregor982365e2009-04-13 21:20:57 +00001498 case pch::DECL_RECORD: {
1499 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1500 0, SourceLocation(), 0, 0);
1501 LoadedDecl(Index, Record);
1502 Reader.VisitRecordDecl(Record);
1503 D = Record;
1504 break;
1505 }
1506
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001507 case pch::DECL_ENUM_CONSTANT: {
1508 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1509 SourceLocation(), 0,
1510 QualType(), 0,
1511 llvm::APSInt());
1512 LoadedDecl(Index, ECD);
1513 Reader.VisitEnumConstantDecl(ECD);
1514 D = ECD;
1515 break;
1516 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001517
1518 case pch::DECL_FUNCTION: {
1519 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1520 DeclarationName(),
1521 QualType());
1522 LoadedDecl(Index, Function);
1523 Reader.VisitFunctionDecl(Function);
1524 D = Function;
1525 break;
1526 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001527
Douglas Gregor982365e2009-04-13 21:20:57 +00001528 case pch::DECL_FIELD: {
1529 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1530 QualType(), 0, false);
1531 LoadedDecl(Index, Field);
1532 Reader.VisitFieldDecl(Field);
1533 D = Field;
1534 break;
1535 }
1536
Douglas Gregorc34897d2009-04-09 22:27:44 +00001537 case pch::DECL_VAR: {
1538 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1539 VarDecl::None, SourceLocation());
1540 LoadedDecl(Index, Var);
1541 Reader.VisitVarDecl(Var);
1542 D = Var;
1543 break;
1544 }
1545
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001546 case pch::DECL_PARM_VAR: {
1547 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1548 QualType(), VarDecl::None, 0);
1549 LoadedDecl(Index, Parm);
1550 Reader.VisitParmVarDecl(Parm);
1551 D = Parm;
1552 break;
1553 }
1554
1555 case pch::DECL_ORIGINAL_PARM_VAR: {
1556 OriginalParmVarDecl *Parm
1557 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1558 QualType(), QualType(), VarDecl::None,
1559 0);
1560 LoadedDecl(Index, Parm);
1561 Reader.VisitOriginalParmVarDecl(Parm);
1562 D = Parm;
1563 break;
1564 }
1565
Douglas Gregor2a491792009-04-13 22:49:25 +00001566 case pch::DECL_FILE_SCOPE_ASM: {
1567 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1568 SourceLocation(), 0);
1569 LoadedDecl(Index, Asm);
1570 Reader.VisitFileScopeAsmDecl(Asm);
1571 D = Asm;
1572 break;
1573 }
1574
1575 case pch::DECL_BLOCK: {
1576 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1577 LoadedDecl(Index, Block);
1578 Reader.VisitBlockDecl(Block);
1579 D = Block;
1580 break;
1581 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001582 }
1583
1584 // If this declaration is also a declaration context, get the
1585 // offsets for its tables of lexical and visible declarations.
1586 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1587 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1588 if (Offsets.first || Offsets.second) {
1589 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1590 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1591 DeclContextOffsets[DC] = Offsets;
1592 }
1593 }
1594 assert(Idx == Record.size());
1595
1596 return D;
1597}
1598
Douglas Gregorac8f2802009-04-10 17:25:41 +00001599QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001600 unsigned Quals = ID & 0x07;
1601 unsigned Index = ID >> 3;
1602
1603 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1604 QualType T;
1605 switch ((pch::PredefinedTypeIDs)Index) {
1606 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1607 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1608 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1609
1610 case pch::PREDEF_TYPE_CHAR_U_ID:
1611 case pch::PREDEF_TYPE_CHAR_S_ID:
1612 // FIXME: Check that the signedness of CharTy is correct!
1613 T = Context.CharTy;
1614 break;
1615
1616 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1617 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1618 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1619 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1620 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1621 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1622 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1623 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1624 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1625 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1626 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1627 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1628 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1629 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1630 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1631 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1632 }
1633
1634 assert(!T.isNull() && "Unknown predefined type");
1635 return T.getQualifiedType(Quals);
1636 }
1637
1638 Index -= pch::NUM_PREDEF_TYPE_IDS;
1639 if (!TypeAlreadyLoaded[Index]) {
1640 // Load the type from the PCH file.
1641 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1642 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1643 TypeAlreadyLoaded[Index] = true;
1644 }
1645
1646 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1647}
1648
Douglas Gregorac8f2802009-04-10 17:25:41 +00001649Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001650 if (ID == 0)
1651 return 0;
1652
1653 unsigned Index = ID - 1;
1654 if (DeclAlreadyLoaded[Index])
1655 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1656
1657 // Load the declaration from the PCH file.
1658 return ReadDeclRecord(DeclOffsets[Index], Index);
1659}
1660
1661bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001662 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001663 assert(DC->hasExternalLexicalStorage() &&
1664 "DeclContext has no lexical decls in storage");
1665 uint64_t Offset = DeclContextOffsets[DC].first;
1666 assert(Offset && "DeclContext has no lexical decls in storage");
1667
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001668 // Keep track of where we are in the stream, then jump back there
1669 // after reading this context.
1670 SavedStreamPosition SavedPosition(Stream);
1671
Douglas Gregorc34897d2009-04-09 22:27:44 +00001672 // Load the record containing all of the declarations lexically in
1673 // this context.
1674 Stream.JumpToBit(Offset);
1675 RecordData Record;
1676 unsigned Code = Stream.ReadCode();
1677 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001678 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001679 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1680
1681 // Load all of the declaration IDs
1682 Decls.clear();
1683 Decls.insert(Decls.end(), Record.begin(), Record.end());
1684 return false;
1685}
1686
1687bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1688 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1689 assert(DC->hasExternalVisibleStorage() &&
1690 "DeclContext has no visible decls in storage");
1691 uint64_t Offset = DeclContextOffsets[DC].second;
1692 assert(Offset && "DeclContext has no visible decls in storage");
1693
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001694 // Keep track of where we are in the stream, then jump back there
1695 // after reading this context.
1696 SavedStreamPosition SavedPosition(Stream);
1697
Douglas Gregorc34897d2009-04-09 22:27:44 +00001698 // Load the record containing all of the declarations visible in
1699 // this context.
1700 Stream.JumpToBit(Offset);
1701 RecordData Record;
1702 unsigned Code = Stream.ReadCode();
1703 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001704 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001705 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1706 if (Record.size() == 0)
1707 return false;
1708
1709 Decls.clear();
1710
1711 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001712 while (Idx < Record.size()) {
1713 Decls.push_back(VisibleDeclaration());
1714 Decls.back().Name = ReadDeclarationName(Record, Idx);
1715
Douglas Gregorc34897d2009-04-09 22:27:44 +00001716 unsigned Size = Record[Idx++];
1717 llvm::SmallVector<unsigned, 4> & LoadedDecls
1718 = Decls.back().Declarations;
1719 LoadedDecls.reserve(Size);
1720 for (unsigned I = 0; I < Size; ++I)
1721 LoadedDecls.push_back(Record[Idx++]);
1722 }
1723
1724 return false;
1725}
1726
Douglas Gregor631f6c62009-04-14 00:24:19 +00001727void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1728 if (!Consumer)
1729 return;
1730
1731 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1732 Decl *D = GetDecl(ExternalDefinitions[I]);
1733 DeclGroupRef DG(D);
1734 Consumer->HandleTopLevelDecl(DG);
1735 }
1736}
1737
Douglas Gregorc34897d2009-04-09 22:27:44 +00001738void PCHReader::PrintStats() {
1739 std::fprintf(stderr, "*** PCH Statistics:\n");
1740
1741 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1742 TypeAlreadyLoaded.end(),
1743 true);
1744 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1745 DeclAlreadyLoaded.end(),
1746 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001747 unsigned NumIdentifiersLoaded = 0;
1748 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1749 if ((IdentifierData[I] & 0x01) == 0)
1750 ++NumIdentifiersLoaded;
1751 }
1752
Douglas Gregorc34897d2009-04-09 22:27:44 +00001753 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1754 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001755 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001756 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1757 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001758 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1759 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1760 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1761 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001762 std::fprintf(stderr, "\n");
1763}
1764
Chris Lattner29241862009-04-11 21:15:38 +00001765IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001766 if (ID == 0)
1767 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001768
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001769 if (!IdentifierTable || IdentifierData.empty()) {
1770 Error("No identifier table in PCH file");
1771 return 0;
1772 }
Chris Lattner29241862009-04-11 21:15:38 +00001773
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001774 if (IdentifierData[ID - 1] & 0x01) {
1775 uint64_t Offset = IdentifierData[ID - 1];
1776 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001777 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001778 }
Chris Lattner29241862009-04-11 21:15:38 +00001779
1780 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001781}
1782
1783DeclarationName
1784PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1785 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1786 switch (Kind) {
1787 case DeclarationName::Identifier:
1788 return DeclarationName(GetIdentifierInfo(Record, Idx));
1789
1790 case DeclarationName::ObjCZeroArgSelector:
1791 case DeclarationName::ObjCOneArgSelector:
1792 case DeclarationName::ObjCMultiArgSelector:
1793 assert(false && "Unable to de-serialize Objective-C selectors");
1794 break;
1795
1796 case DeclarationName::CXXConstructorName:
1797 return Context.DeclarationNames.getCXXConstructorName(
1798 GetType(Record[Idx++]));
1799
1800 case DeclarationName::CXXDestructorName:
1801 return Context.DeclarationNames.getCXXDestructorName(
1802 GetType(Record[Idx++]));
1803
1804 case DeclarationName::CXXConversionFunctionName:
1805 return Context.DeclarationNames.getCXXConversionFunctionName(
1806 GetType(Record[Idx++]));
1807
1808 case DeclarationName::CXXOperatorName:
1809 return Context.DeclarationNames.getCXXOperatorName(
1810 (OverloadedOperatorKind)Record[Idx++]);
1811
1812 case DeclarationName::CXXUsingDirective:
1813 return DeclarationName::getUsingDirectiveName();
1814 }
1815
1816 // Required to silence GCC warning
1817 return DeclarationName();
1818}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001819
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001820/// \brief Read an integral value
1821llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1822 unsigned BitWidth = Record[Idx++];
1823 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1824 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1825 Idx += NumWords;
1826 return Result;
1827}
1828
1829/// \brief Read a signed integral value
1830llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1831 bool isUnsigned = Record[Idx++];
1832 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1833}
1834
Douglas Gregore2f37202009-04-14 21:55:33 +00001835/// \brief Read a floating-point value
1836llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00001837 return llvm::APFloat(ReadAPInt(Record, Idx));
1838}
1839
Douglas Gregor1c507882009-04-15 21:30:51 +00001840// \brief Read a string
1841std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
1842 unsigned Len = Record[Idx++];
1843 std::string Result(&Record[Idx], &Record[Idx] + Len);
1844 Idx += Len;
1845 return Result;
1846}
1847
1848/// \brief Reads attributes from the current stream position.
1849Attr *PCHReader::ReadAttributes() {
1850 unsigned Code = Stream.ReadCode();
1851 assert(Code == llvm::bitc::UNABBREV_RECORD &&
1852 "Expected unabbreviated record"); (void)Code;
1853
1854 RecordData Record;
1855 unsigned Idx = 0;
1856 unsigned RecCode = Stream.ReadRecord(Code, Record);
1857 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
1858 (void)RecCode;
1859
1860#define SIMPLE_ATTR(Name) \
1861 case Attr::Name: \
1862 New = ::new (Context) Name##Attr(); \
1863 break
1864
1865#define STRING_ATTR(Name) \
1866 case Attr::Name: \
1867 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
1868 break
1869
1870#define UNSIGNED_ATTR(Name) \
1871 case Attr::Name: \
1872 New = ::new (Context) Name##Attr(Record[Idx++]); \
1873 break
1874
1875 Attr *Attrs = 0;
1876 while (Idx < Record.size()) {
1877 Attr *New = 0;
1878 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
1879 bool IsInherited = Record[Idx++];
1880
1881 switch (Kind) {
1882 STRING_ATTR(Alias);
1883 UNSIGNED_ATTR(Aligned);
1884 SIMPLE_ATTR(AlwaysInline);
1885 SIMPLE_ATTR(AnalyzerNoReturn);
1886 STRING_ATTR(Annotate);
1887 STRING_ATTR(AsmLabel);
1888
1889 case Attr::Blocks:
1890 New = ::new (Context) BlocksAttr(
1891 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
1892 break;
1893
1894 case Attr::Cleanup:
1895 New = ::new (Context) CleanupAttr(
1896 cast<FunctionDecl>(GetDecl(Record[Idx++])));
1897 break;
1898
1899 SIMPLE_ATTR(Const);
1900 UNSIGNED_ATTR(Constructor);
1901 SIMPLE_ATTR(DLLExport);
1902 SIMPLE_ATTR(DLLImport);
1903 SIMPLE_ATTR(Deprecated);
1904 UNSIGNED_ATTR(Destructor);
1905 SIMPLE_ATTR(FastCall);
1906
1907 case Attr::Format: {
1908 std::string Type = ReadString(Record, Idx);
1909 unsigned FormatIdx = Record[Idx++];
1910 unsigned FirstArg = Record[Idx++];
1911 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
1912 break;
1913 }
1914
1915 SIMPLE_ATTR(GNUCInline);
1916
1917 case Attr::IBOutletKind:
1918 New = ::new (Context) IBOutletAttr();
1919 break;
1920
1921 SIMPLE_ATTR(NoReturn);
1922 SIMPLE_ATTR(NoThrow);
1923 SIMPLE_ATTR(Nodebug);
1924 SIMPLE_ATTR(Noinline);
1925
1926 case Attr::NonNull: {
1927 unsigned Size = Record[Idx++];
1928 llvm::SmallVector<unsigned, 16> ArgNums;
1929 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
1930 Idx += Size;
1931 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
1932 break;
1933 }
1934
1935 SIMPLE_ATTR(ObjCException);
1936 SIMPLE_ATTR(ObjCNSObject);
1937 SIMPLE_ATTR(Overloadable);
1938 UNSIGNED_ATTR(Packed);
1939 SIMPLE_ATTR(Pure);
1940 UNSIGNED_ATTR(Regparm);
1941 STRING_ATTR(Section);
1942 SIMPLE_ATTR(StdCall);
1943 SIMPLE_ATTR(TransparentUnion);
1944 SIMPLE_ATTR(Unavailable);
1945 SIMPLE_ATTR(Unused);
1946 SIMPLE_ATTR(Used);
1947
1948 case Attr::Visibility:
1949 New = ::new (Context) VisibilityAttr(
1950 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
1951 break;
1952
1953 SIMPLE_ATTR(WarnUnusedResult);
1954 SIMPLE_ATTR(Weak);
1955 SIMPLE_ATTR(WeakImport);
1956 }
1957
1958 assert(New && "Unable to decode attribute?");
1959 New->setInherited(IsInherited);
1960 New->setNext(Attrs);
1961 Attrs = New;
1962 }
1963#undef UNSIGNED_ATTR
1964#undef STRING_ATTR
1965#undef SIMPLE_ATTR
1966
1967 // The list of attributes was built backwards. Reverse the list
1968 // before returning it.
1969 Attr *PrevAttr = 0, *NextAttr = 0;
1970 while (Attrs) {
1971 NextAttr = Attrs->getNext();
1972 Attrs->setNext(PrevAttr);
1973 PrevAttr = Attrs;
1974 Attrs = NextAttr;
1975 }
1976
1977 return PrevAttr;
1978}
1979
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001980Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001981 // Within the bitstream, expressions are stored in Reverse Polish
1982 // Notation, with each of the subexpressions preceding the
1983 // expression they are stored in. To evaluate expressions, we
1984 // continue reading expressions and placing them on the stack, with
1985 // expressions having operands removing those operands from the
1986 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1987 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001988 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001989 unsigned Idx;
1990 llvm::SmallVector<Expr *, 16> ExprStack;
1991 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001992 Stmt::EmptyShell Empty;
1993
Douglas Gregora151ba42009-04-14 23:32:43 +00001994 while (true) {
1995 unsigned Code = Stream.ReadCode();
1996 if (Code == llvm::bitc::END_BLOCK) {
1997 if (Stream.ReadBlockEnd()) {
1998 Error("Error at end of Source Manager block");
1999 return 0;
2000 }
2001 break;
2002 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002003
Douglas Gregora151ba42009-04-14 23:32:43 +00002004 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2005 // No known subblocks, always skip them.
2006 Stream.ReadSubBlockID();
2007 if (Stream.SkipBlock()) {
2008 Error("Malformed block record");
2009 return 0;
2010 }
2011 continue;
2012 }
Douglas Gregore2f37202009-04-14 21:55:33 +00002013
Douglas Gregora151ba42009-04-14 23:32:43 +00002014 if (Code == llvm::bitc::DEFINE_ABBREV) {
2015 Stream.ReadAbbrevRecord();
2016 continue;
2017 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002018
Douglas Gregora151ba42009-04-14 23:32:43 +00002019 Expr *E = 0;
2020 Idx = 0;
2021 Record.clear();
2022 bool Finished = false;
2023 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
2024 case pch::EXPR_STOP:
2025 Finished = true;
2026 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002027
Douglas Gregora151ba42009-04-14 23:32:43 +00002028 case pch::EXPR_NULL:
2029 E = 0;
2030 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002031
Douglas Gregora151ba42009-04-14 23:32:43 +00002032 case pch::EXPR_PREDEFINED:
2033 // FIXME: untested (until we can serialize function bodies).
2034 E = new (Context) PredefinedExpr(Empty);
2035 break;
2036
2037 case pch::EXPR_DECL_REF:
2038 E = new (Context) DeclRefExpr(Empty);
2039 break;
2040
2041 case pch::EXPR_INTEGER_LITERAL:
2042 E = new (Context) IntegerLiteral(Empty);
2043 break;
2044
2045 case pch::EXPR_FLOATING_LITERAL:
2046 E = new (Context) FloatingLiteral(Empty);
2047 break;
2048
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00002049 case pch::EXPR_IMAGINARY_LITERAL:
2050 E = new (Context) ImaginaryLiteral(Empty);
2051 break;
2052
Douglas Gregor596e0932009-04-15 16:35:07 +00002053 case pch::EXPR_STRING_LITERAL:
2054 E = StringLiteral::CreateEmpty(Context,
2055 Record[PCHStmtReader::NumExprFields + 1]);
2056 break;
2057
Douglas Gregora151ba42009-04-14 23:32:43 +00002058 case pch::EXPR_CHARACTER_LITERAL:
2059 E = new (Context) CharacterLiteral(Empty);
2060 break;
2061
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00002062 case pch::EXPR_PAREN:
2063 E = new (Context) ParenExpr(Empty);
2064 break;
2065
Douglas Gregor12d74052009-04-15 15:58:59 +00002066 case pch::EXPR_UNARY_OPERATOR:
2067 E = new (Context) UnaryOperator(Empty);
2068 break;
2069
2070 case pch::EXPR_SIZEOF_ALIGN_OF:
2071 E = new (Context) SizeOfAlignOfExpr(Empty);
2072 break;
2073
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00002074 case pch::EXPR_ARRAY_SUBSCRIPT:
2075 E = new (Context) ArraySubscriptExpr(Empty);
2076 break;
2077
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00002078 case pch::EXPR_CALL:
2079 E = new (Context) CallExpr(Context, Empty);
2080 break;
2081
2082 case pch::EXPR_MEMBER:
2083 E = new (Context) MemberExpr(Empty);
2084 break;
2085
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00002086 case pch::EXPR_BINARY_OPERATOR:
2087 E = new (Context) BinaryOperator(Empty);
2088 break;
2089
Douglas Gregorc599bbf2009-04-15 22:40:36 +00002090 case pch::EXPR_COMPOUND_ASSIGN_OPERATOR:
2091 E = new (Context) CompoundAssignOperator(Empty);
2092 break;
2093
2094 case pch::EXPR_CONDITIONAL_OPERATOR:
2095 E = new (Context) ConditionalOperator(Empty);
2096 break;
2097
Douglas Gregora151ba42009-04-14 23:32:43 +00002098 case pch::EXPR_IMPLICIT_CAST:
2099 E = new (Context) ImplicitCastExpr(Empty);
2100 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00002101
2102 case pch::EXPR_CSTYLE_CAST:
2103 E = new (Context) CStyleCastExpr(Empty);
2104 break;
Douglas Gregorec0b8292009-04-15 23:02:49 +00002105
2106 case pch::EXPR_EXT_VECTOR_ELEMENT:
2107 E = new (Context) ExtVectorElementExpr(Empty);
2108 break;
2109
Douglas Gregor6710a3c2009-04-16 00:55:48 +00002110 case pch::EXPR_INIT_LIST:
2111 E = new (Context) InitListExpr(Empty);
2112 break;
2113
2114 case pch::EXPR_DESIGNATED_INIT:
2115 E = DesignatedInitExpr::CreateEmpty(Context,
2116 Record[PCHStmtReader::NumExprFields] - 1);
2117
2118 break;
2119
2120 case pch::EXPR_IMPLICIT_VALUE_INIT:
2121 E = new (Context) ImplicitValueInitExpr(Empty);
2122 break;
2123
Douglas Gregorec0b8292009-04-15 23:02:49 +00002124 case pch::EXPR_VA_ARG:
2125 // FIXME: untested; we need function bodies first
2126 E = new (Context) VAArgExpr(Empty);
2127 break;
Douglas Gregor209d4622009-04-15 23:33:31 +00002128
2129 case pch::EXPR_TYPES_COMPATIBLE:
2130 E = new (Context) TypesCompatibleExpr(Empty);
2131 break;
2132
2133 case pch::EXPR_CHOOSE:
2134 E = new (Context) ChooseExpr(Empty);
2135 break;
2136
2137 case pch::EXPR_GNU_NULL:
2138 E = new (Context) GNUNullExpr(Empty);
2139 break;
Douglas Gregor725e94b2009-04-16 00:01:45 +00002140
2141 case pch::EXPR_SHUFFLE_VECTOR:
2142 E = new (Context) ShuffleVectorExpr(Empty);
2143 break;
2144
2145 case pch::EXPR_BLOCK_DECL_REF:
2146 // FIXME: untested until we have statement and block support
2147 E = new (Context) BlockDeclRefExpr(Empty);
2148 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00002149 }
2150
2151 // We hit an EXPR_STOP, so we're done with this expression.
2152 if (Finished)
2153 break;
2154
2155 if (E) {
2156 unsigned NumSubExprs = Reader.Visit(E);
2157 while (NumSubExprs > 0) {
2158 ExprStack.pop_back();
2159 --NumSubExprs;
2160 }
2161 }
2162
2163 assert(Idx == Record.size() && "Invalid deserialization of expression");
2164 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002165 }
Douglas Gregora151ba42009-04-14 23:32:43 +00002166 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
2167 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002168}
2169
Douglas Gregor179cfb12009-04-10 20:39:37 +00002170DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002171 return Diag(SourceLocation(), DiagID);
2172}
2173
2174DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2175 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00002176 Context.getSourceManager()),
2177 DiagID);
2178}