blob: 52afd2db7209fce6cf8e09bb740ec7035509485b [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//===----------------------------------------------------------------------===//
Chris Lattner09547942009-04-27 05:14:47 +000013
Douglas Gregorc34897d2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor631f6c62009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
Douglas Gregor631f6c62009-04-14 00:24:19 +000020#include "clang/AST/DeclGroup.h"
Douglas Gregorddf4d092009-04-16 22:29:51 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000022#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000023#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000026#include "clang/Lex/HeaderSearch.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000031#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include <algorithm>
36#include <cstdio>
37
38using namespace clang;
39
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000040namespace {
41 /// \brief Helper class that saves the current stream position and
42 /// then restores it when destroyed.
43 struct VISIBILITY_HIDDEN SavedStreamPosition {
Chris Lattner587788a2009-04-26 20:59:20 +000044 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
45 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000046
47 ~SavedStreamPosition() {
Chris Lattner587788a2009-04-26 20:59:20 +000048 Cursor.JumpToBit(Offset);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000049 }
50
51 private:
Chris Lattner587788a2009-04-26 20:59:20 +000052 llvm::BitstreamCursor &Cursor;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000053 uint64_t Offset;
54 };
55}
56
Douglas Gregorc34897d2009-04-09 22:27:44 +000057//===----------------------------------------------------------------------===//
58// Declaration deserialization
59//===----------------------------------------------------------------------===//
60namespace {
Douglas Gregorddf4d092009-04-16 22:29:51 +000061 class VISIBILITY_HIDDEN PCHDeclReader
62 : public DeclVisitor<PCHDeclReader, void> {
Douglas Gregorc34897d2009-04-09 22:27:44 +000063 PCHReader &Reader;
64 const PCHReader::RecordData &Record;
65 unsigned &Idx;
66
67 public:
68 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
69 unsigned &Idx)
70 : Reader(Reader), Record(Record), Idx(Idx) { }
71
72 void VisitDecl(Decl *D);
73 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
74 void VisitNamedDecl(NamedDecl *ND);
75 void VisitTypeDecl(TypeDecl *TD);
76 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000077 void VisitTagDecl(TagDecl *TD);
78 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000079 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000080 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000081 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000082 void VisitFunctionDecl(FunctionDecl *FD);
Douglas Gregor982365e2009-04-13 21:20:57 +000083 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000084 void VisitVarDecl(VarDecl *VD);
Douglas Gregorce066712009-04-26 22:20:50 +000085 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000086 void VisitParmVarDecl(ParmVarDecl *PD);
87 void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD);
Douglas Gregor2a491792009-04-13 22:49:25 +000088 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
89 void VisitBlockDecl(BlockDecl *BD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000090 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
Steve Naroff79ea0e02009-04-20 15:06:07 +000091 void VisitObjCMethodDecl(ObjCMethodDecl *D);
Steve Naroff7333b492009-04-20 20:09:33 +000092 void VisitObjCContainerDecl(ObjCContainerDecl *D);
93 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
94 void VisitObjCIvarDecl(ObjCIvarDecl *D);
Steve Naroff97b53bd2009-04-21 15:12:33 +000095 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
96 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
97 void VisitObjCClassDecl(ObjCClassDecl *D);
98 void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
99 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
100 void VisitObjCImplDecl(ObjCImplDecl *D);
101 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
102 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
103 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
104 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
105 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000106 };
107}
108
109void PCHDeclReader::VisitDecl(Decl *D) {
110 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
111 D->setLexicalDeclContext(
112 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
113 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
114 D->setInvalidDecl(Record[Idx++]);
Douglas Gregor1c507882009-04-15 21:30:51 +0000115 if (Record[Idx++])
116 D->addAttr(Reader.ReadAttributes());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000117 D->setImplicit(Record[Idx++]);
118 D->setAccess((AccessSpecifier)Record[Idx++]);
119}
120
121void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
122 VisitDecl(TU);
123}
124
125void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
126 VisitDecl(ND);
127 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
128}
129
130void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
131 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000132 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
133}
134
135void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000136 // Note that we cannot use VisitTypeDecl here, because we need to
137 // set the underlying type of the typedef *before* we try to read
138 // the type associated with the TypedefDecl.
139 VisitNamedDecl(TD);
140 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
141 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
142 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000143}
144
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000145void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
146 VisitTypeDecl(TD);
147 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
148 TD->setDefinition(Record[Idx++]);
149 TD->setTypedefForAnonDecl(
150 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
151}
152
153void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
154 VisitTagDecl(ED);
155 ED->setIntegerType(Reader.GetType(Record[Idx++]));
156}
157
Douglas Gregor982365e2009-04-13 21:20:57 +0000158void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
159 VisitTagDecl(RD);
160 RD->setHasFlexibleArrayMember(Record[Idx++]);
161 RD->setAnonymousStructOrUnion(Record[Idx++]);
162}
163
Douglas Gregorc34897d2009-04-09 22:27:44 +0000164void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
165 VisitNamedDecl(VD);
166 VD->setType(Reader.GetType(Record[Idx++]));
167}
168
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000169void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
170 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000171 if (Record[Idx++])
172 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000173 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
174}
175
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000176void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
177 VisitValueDecl(FD);
Douglas Gregor9c4782a2009-04-17 00:04:06 +0000178 if (Record[Idx++])
Douglas Gregor3b9a7c82009-04-18 00:07:54 +0000179 FD->setLazyBody(Reader.getStream().GetCurrentBitNo());
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000180 FD->setPreviousDeclaration(
181 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
182 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
183 FD->setInline(Record[Idx++]);
Douglas Gregor9b6348d2009-04-23 18:22:55 +0000184 FD->setC99InlineDefinition(Record[Idx++]);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000185 FD->setVirtual(Record[Idx++]);
186 FD->setPure(Record[Idx++]);
187 FD->setInheritedPrototype(Record[Idx++]);
188 FD->setHasPrototype(Record[Idx++]);
189 FD->setDeleted(Record[Idx++]);
190 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
191 unsigned NumParams = Record[Idx++];
192 llvm::SmallVector<ParmVarDecl *, 16> Params;
193 Params.reserve(NumParams);
194 for (unsigned I = 0; I != NumParams; ++I)
195 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
196 FD->setParams(Reader.getContext(), &Params[0], NumParams);
197}
198
Steve Naroff79ea0e02009-04-20 15:06:07 +0000199void PCHDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
200 VisitNamedDecl(MD);
201 if (Record[Idx++]) {
202 // In practice, this won't be executed (since method definitions
203 // don't occur in header files).
Douglas Gregorce066712009-04-26 22:20:50 +0000204 MD->setBody(cast<CompoundStmt>(Reader.ReadStmt()));
Steve Naroff79ea0e02009-04-20 15:06:07 +0000205 MD->setSelfDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
206 MD->setCmdDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
207 }
208 MD->setInstanceMethod(Record[Idx++]);
209 MD->setVariadic(Record[Idx++]);
210 MD->setSynthesized(Record[Idx++]);
211 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
212 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
213 MD->setResultType(Reader.GetType(Record[Idx++]));
214 MD->setEndLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
215 unsigned NumParams = Record[Idx++];
216 llvm::SmallVector<ParmVarDecl *, 16> Params;
217 Params.reserve(NumParams);
218 for (unsigned I = 0; I != NumParams; ++I)
219 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
220 MD->setMethodParams(Reader.getContext(), &Params[0], NumParams);
221}
222
Steve Naroff7333b492009-04-20 20:09:33 +0000223void PCHDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
224 VisitNamedDecl(CD);
225 CD->setAtEndLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
226}
227
228void PCHDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
229 VisitObjCContainerDecl(ID);
230 ID->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
Chris Lattner80f83c62009-04-22 05:57:30 +0000231 ID->setSuperClass(cast_or_null<ObjCInterfaceDecl>
232 (Reader.GetDecl(Record[Idx++])));
Douglas Gregor37a54fd2009-04-23 03:59:07 +0000233 unsigned NumProtocols = Record[Idx++];
234 llvm::SmallVector<ObjCProtocolDecl *, 16> Protocols;
235 Protocols.reserve(NumProtocols);
236 for (unsigned I = 0; I != NumProtocols; ++I)
237 Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
Douglas Gregor5efc1052009-04-24 22:01:00 +0000238 ID->setProtocolList(&Protocols[0], NumProtocols, Reader.getContext());
Steve Naroff7333b492009-04-20 20:09:33 +0000239 unsigned NumIvars = Record[Idx++];
240 llvm::SmallVector<ObjCIvarDecl *, 16> IVars;
241 IVars.reserve(NumIvars);
242 for (unsigned I = 0; I != NumIvars; ++I)
243 IVars.push_back(cast<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
244 ID->setIVarList(&IVars[0], NumIvars, Reader.getContext());
Douglas Gregorae660c72009-04-23 22:34:55 +0000245 ID->setCategoryList(
246 cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
Steve Naroff7333b492009-04-20 20:09:33 +0000247 ID->setForwardDecl(Record[Idx++]);
248 ID->setImplicitInterfaceDecl(Record[Idx++]);
249 ID->setClassLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
250 ID->setSuperClassLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Chris Lattner80f83c62009-04-22 05:57:30 +0000251 ID->setAtEndLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Steve Naroff7333b492009-04-20 20:09:33 +0000252}
253
254void PCHDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
255 VisitFieldDecl(IVD);
256 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
257}
258
Steve Naroff97b53bd2009-04-21 15:12:33 +0000259void PCHDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
260 VisitObjCContainerDecl(PD);
261 PD->setForwardDecl(Record[Idx++]);
262 PD->setLocEnd(SourceLocation::getFromRawEncoding(Record[Idx++]));
263 unsigned NumProtoRefs = Record[Idx++];
264 llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
265 ProtoRefs.reserve(NumProtoRefs);
266 for (unsigned I = 0; I != NumProtoRefs; ++I)
267 ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
268 PD->setProtocolList(&ProtoRefs[0], NumProtoRefs, Reader.getContext());
269}
270
271void PCHDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
272 VisitFieldDecl(FD);
273}
274
275void PCHDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
276 VisitDecl(CD);
277 unsigned NumClassRefs = Record[Idx++];
278 llvm::SmallVector<ObjCInterfaceDecl *, 16> ClassRefs;
279 ClassRefs.reserve(NumClassRefs);
280 for (unsigned I = 0; I != NumClassRefs; ++I)
281 ClassRefs.push_back(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
282 CD->setClassList(Reader.getContext(), &ClassRefs[0], NumClassRefs);
283}
284
285void PCHDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
286 VisitDecl(FPD);
287 unsigned NumProtoRefs = Record[Idx++];
288 llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
289 ProtoRefs.reserve(NumProtoRefs);
290 for (unsigned I = 0; I != NumProtoRefs; ++I)
291 ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
292 FPD->setProtocolList(&ProtoRefs[0], NumProtoRefs, Reader.getContext());
293}
294
295void PCHDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
296 VisitObjCContainerDecl(CD);
297 CD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
298 unsigned NumProtoRefs = Record[Idx++];
299 llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
300 ProtoRefs.reserve(NumProtoRefs);
301 for (unsigned I = 0; I != NumProtoRefs; ++I)
302 ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
303 CD->setProtocolList(&ProtoRefs[0], NumProtoRefs, Reader.getContext());
Steve Naroffbac01db2009-04-24 16:59:10 +0000304 CD->setNextClassCategory(cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000305 CD->setLocEnd(SourceLocation::getFromRawEncoding(Record[Idx++]));
306}
307
308void PCHDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
309 VisitNamedDecl(CAD);
310 CAD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
311}
312
313void PCHDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
314 VisitNamedDecl(D);
Douglas Gregor3839f1c2009-04-22 23:20:34 +0000315 D->setType(Reader.GetType(Record[Idx++]));
316 // FIXME: stable encoding
317 D->setPropertyAttributes(
318 (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
319 // FIXME: stable encoding
320 D->setPropertyImplementation(
321 (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
322 D->setGetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
323 D->setSetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
324 D->setGetterMethodDecl(
325 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
326 D->setSetterMethodDecl(
327 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
328 D->setPropertyIvarDecl(
329 cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000330}
331
332void PCHDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000333 VisitNamedDecl(D);
Douglas Gregorbd336c52009-04-23 02:42:49 +0000334 D->setClassInterface(
335 cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
336 D->setLocEnd(SourceLocation::getFromRawEncoding(Record[Idx++]));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000337}
338
339void PCHDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
340 VisitObjCImplDecl(D);
Douglas Gregor58e7ce42009-04-23 02:53:57 +0000341 D->setIdentifier(Reader.GetIdentifierInfo(Record, Idx));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000342}
343
344void PCHDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
345 VisitObjCImplDecl(D);
Douglas Gregor087dbf32009-04-23 03:23:08 +0000346 D->setSuperClass(
347 cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000348}
349
350
351void PCHDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
352 VisitDecl(D);
Douglas Gregor3f2c5052009-04-23 03:43:53 +0000353 D->setAtLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
354 D->setPropertyDecl(
355 cast_or_null<ObjCPropertyDecl>(Reader.GetDecl(Record[Idx++])));
356 D->setPropertyIvarDecl(
357 cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
Steve Naroff97b53bd2009-04-21 15:12:33 +0000358}
359
Douglas Gregor982365e2009-04-13 21:20:57 +0000360void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
361 VisitValueDecl(FD);
362 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000363 if (Record[Idx++])
364 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000365}
366
Douglas Gregorc34897d2009-04-09 22:27:44 +0000367void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
368 VisitValueDecl(VD);
369 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
370 VD->setThreadSpecified(Record[Idx++]);
371 VD->setCXXDirectInitializer(Record[Idx++]);
372 VD->setDeclaredInCondition(Record[Idx++]);
373 VD->setPreviousDeclaration(
374 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
375 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000376 if (Record[Idx++])
377 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000378}
379
Douglas Gregorce066712009-04-26 22:20:50 +0000380void PCHDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
381 VisitVarDecl(PD);
382}
383
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000384void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
385 VisitVarDecl(PD);
386 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000387 // FIXME: default argument (C++ only)
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000388}
389
390void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
391 VisitParmVarDecl(PD);
392 PD->setOriginalType(Reader.GetType(Record[Idx++]));
393}
394
Douglas Gregor2a491792009-04-13 22:49:25 +0000395void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
396 VisitDecl(AD);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000397 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000398}
399
400void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
401 VisitDecl(BD);
Douglas Gregore246b742009-04-17 19:21:43 +0000402 BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000403 unsigned NumParams = Record[Idx++];
404 llvm::SmallVector<ParmVarDecl *, 16> Params;
405 Params.reserve(NumParams);
406 for (unsigned I = 0; I != NumParams; ++I)
407 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
408 BD->setParams(Reader.getContext(), &Params[0], NumParams);
409}
410
Douglas Gregorc34897d2009-04-09 22:27:44 +0000411std::pair<uint64_t, uint64_t>
412PCHDeclReader::VisitDeclContext(DeclContext *DC) {
413 uint64_t LexicalOffset = Record[Idx++];
Douglas Gregor405b6432009-04-22 19:09:20 +0000414 uint64_t VisibleOffset = Record[Idx++];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000415 return std::make_pair(LexicalOffset, VisibleOffset);
416}
417
Steve Naroff79762bd2009-04-26 18:52:16 +0000418
Douglas Gregorc713da92009-04-21 22:25:48 +0000419//===----------------------------------------------------------------------===//
420// PCH reader implementation
421//===----------------------------------------------------------------------===//
422
Chris Lattner09547942009-04-27 05:14:47 +0000423PCHReader::PCHReader(Preprocessor &PP, ASTContext &Context)
424 : SemaObj(0), PP(PP), Context(Context), Consumer(0),
425 IdentifierTableData(0), IdentifierLookupTable(0),
426 IdentifierOffsets(0),
427 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
428 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
429 TotalNumSelectors(0), NumStatementsRead(0), NumMacrosRead(0),
430 NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
431 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
432
433PCHReader::~PCHReader() {}
434
435Expr *PCHReader::ReadExpr() {
436 return dyn_cast_or_null<Expr>(ReadStmt());
437}
438
439
Douglas Gregorc713da92009-04-21 22:25:48 +0000440namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000441class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
442 PCHReader &Reader;
443
444public:
445 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
446
447 typedef Selector external_key_type;
448 typedef external_key_type internal_key_type;
449
450 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
451
452 static bool EqualKey(const internal_key_type& a,
453 const internal_key_type& b) {
454 return a == b;
455 }
456
457 static unsigned ComputeHash(Selector Sel) {
458 unsigned N = Sel.getNumArgs();
459 if (N == 0)
460 ++N;
461 unsigned R = 5381;
462 for (unsigned I = 0; I != N; ++I)
463 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
464 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
465 return R;
466 }
467
468 // This hopefully will just get inlined and removed by the optimizer.
469 static const internal_key_type&
470 GetInternalKey(const external_key_type& x) { return x; }
471
472 static std::pair<unsigned, unsigned>
473 ReadKeyDataLength(const unsigned char*& d) {
474 using namespace clang::io;
475 unsigned KeyLen = ReadUnalignedLE16(d);
476 unsigned DataLen = ReadUnalignedLE16(d);
477 return std::make_pair(KeyLen, DataLen);
478 }
479
Douglas Gregor2d711832009-04-25 17:48:32 +0000480 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000481 using namespace clang::io;
482 SelectorTable &SelTable = Reader.getContext().Selectors;
483 unsigned N = ReadUnalignedLE16(d);
484 IdentifierInfo *FirstII
485 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
486 if (N == 0)
487 return SelTable.getNullarySelector(FirstII);
488 else if (N == 1)
489 return SelTable.getUnarySelector(FirstII);
490
491 llvm::SmallVector<IdentifierInfo *, 16> Args;
492 Args.push_back(FirstII);
493 for (unsigned I = 1; I != N; ++I)
494 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
495
496 return SelTable.getSelector(N, &Args[0]);
497 }
498
499 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
500 using namespace clang::io;
501 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
502 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
503
504 data_type Result;
505
506 // Load instance methods
507 ObjCMethodList *Prev = 0;
508 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
509 ObjCMethodDecl *Method
510 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
511 if (!Result.first.Method) {
512 // This is the first method, which is the easy case.
513 Result.first.Method = Method;
514 Prev = &Result.first;
515 continue;
516 }
517
518 Prev->Next = new ObjCMethodList(Method, 0);
519 Prev = Prev->Next;
520 }
521
522 // Load factory methods
523 Prev = 0;
524 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
525 ObjCMethodDecl *Method
526 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
527 if (!Result.second.Method) {
528 // This is the first method, which is the easy case.
529 Result.second.Method = Method;
530 Prev = &Result.second;
531 continue;
532 }
533
534 Prev->Next = new ObjCMethodList(Method, 0);
535 Prev = Prev->Next;
536 }
537
538 return Result;
539 }
540};
541
542} // end anonymous namespace
543
544/// \brief The on-disk hash table used for the global method pool.
545typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
546 PCHMethodPoolLookupTable;
547
548namespace {
Douglas Gregorc713da92009-04-21 22:25:48 +0000549class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
550 PCHReader &Reader;
551
552 // If we know the IdentifierInfo in advance, it is here and we will
553 // not build a new one. Used when deserializing information about an
554 // identifier that was constructed before the PCH file was read.
555 IdentifierInfo *KnownII;
556
557public:
558 typedef IdentifierInfo * data_type;
559
560 typedef const std::pair<const char*, unsigned> external_key_type;
561
562 typedef external_key_type internal_key_type;
563
564 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
565 : Reader(Reader), KnownII(II) { }
566
567 static bool EqualKey(const internal_key_type& a,
568 const internal_key_type& b) {
569 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
570 : false;
571 }
572
573 static unsigned ComputeHash(const internal_key_type& a) {
574 return BernsteinHash(a.first, a.second);
575 }
576
577 // This hopefully will just get inlined and removed by the optimizer.
578 static const internal_key_type&
579 GetInternalKey(const external_key_type& x) { return x; }
580
581 static std::pair<unsigned, unsigned>
582 ReadKeyDataLength(const unsigned char*& d) {
583 using namespace clang::io;
Douglas Gregor4bb24882009-04-25 20:26:24 +0000584 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor85c4a872009-04-25 21:04:17 +0000585 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregorc713da92009-04-21 22:25:48 +0000586 return std::make_pair(KeyLen, DataLen);
587 }
588
589 static std::pair<const char*, unsigned>
590 ReadKey(const unsigned char* d, unsigned n) {
591 assert(n >= 2 && d[n-1] == '\0');
592 return std::make_pair((const char*) d, n-1);
593 }
594
595 IdentifierInfo *ReadData(const internal_key_type& k,
596 const unsigned char* d,
597 unsigned DataLen) {
598 using namespace clang::io;
Douglas Gregor2554cf22009-04-22 21:15:06 +0000599 uint32_t Bits = ReadUnalignedLE32(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000600 bool CPlusPlusOperatorKeyword = Bits & 0x01;
601 Bits >>= 1;
602 bool Poisoned = Bits & 0x01;
603 Bits >>= 1;
604 bool ExtensionToken = Bits & 0x01;
605 Bits >>= 1;
606 bool hasMacroDefinition = Bits & 0x01;
607 Bits >>= 1;
608 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
609 Bits >>= 10;
610 unsigned TokenID = Bits & 0xFF;
611 Bits >>= 8;
612
Douglas Gregorc713da92009-04-21 22:25:48 +0000613 pch::IdentID ID = ReadUnalignedLE32(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000614 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorc713da92009-04-21 22:25:48 +0000615 DataLen -= 8;
616
617 // Build the IdentifierInfo itself and link the identifier ID with
618 // the new IdentifierInfo.
619 IdentifierInfo *II = KnownII;
620 if (!II)
Douglas Gregor4bb24882009-04-25 20:26:24 +0000621 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
622 k.first, k.first + k.second);
Douglas Gregorc713da92009-04-21 22:25:48 +0000623 Reader.SetIdentifierInfo(ID, II);
624
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000625 // Set or check the various bits in the IdentifierInfo structure.
626 // FIXME: Load token IDs lazily, too?
627 assert((unsigned)II->getTokenID() == TokenID &&
628 "Incorrect token ID loaded");
629 (void)TokenID;
630 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
631 assert(II->isExtensionToken() == ExtensionToken &&
632 "Incorrect extension token flag");
633 (void)ExtensionToken;
634 II->setIsPoisoned(Poisoned);
635 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
636 "Incorrect C++ operator keyword flag");
637 (void)CPlusPlusOperatorKeyword;
638
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000639 // If this identifier is a macro, deserialize the macro
640 // definition.
641 if (hasMacroDefinition) {
642 uint32_t Offset = ReadUnalignedLE64(d);
643 Reader.ReadMacroRecord(Offset);
644 DataLen -= 8;
645 }
Douglas Gregorc713da92009-04-21 22:25:48 +0000646
647 // Read all of the declarations visible at global scope with this
648 // name.
649 Sema *SemaObj = Reader.getSema();
650 while (DataLen > 0) {
651 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregorc713da92009-04-21 22:25:48 +0000652 if (SemaObj) {
653 // Introduce this declaration into the translation-unit scope
654 // and add it to the declaration chain for this identifier, so
655 // that (unqualified) name lookup will find it.
656 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
657 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
658 } else {
659 // Queue this declaration so that it will be added to the
660 // translation unit scope and identifier's declaration chain
661 // once a Sema object is known.
Douglas Gregor2554cf22009-04-22 21:15:06 +0000662 Reader.PreloadedDecls.push_back(D);
Douglas Gregorc713da92009-04-21 22:25:48 +0000663 }
664
665 DataLen -= 4;
666 }
667 return II;
668 }
669};
670
671} // end anonymous namespace
672
673/// \brief The on-disk hash table used to contain information about
674/// all of the identifiers in the program.
675typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
676 PCHIdentifierLookupTable;
677
Douglas Gregorc34897d2009-04-09 22:27:44 +0000678// FIXME: use the diagnostics machinery
679static bool Error(const char *Str) {
680 std::fprintf(stderr, "%s\n", Str);
681 return true;
682}
683
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000684/// \brief Check the contents of the predefines buffer against the
685/// contents of the predefines buffer used to build the PCH file.
686///
687/// The contents of the two predefines buffers should be the same. If
688/// not, then some command-line option changed the preprocessor state
689/// and we must reject the PCH file.
690///
691/// \param PCHPredef The start of the predefines buffer in the PCH
692/// file.
693///
694/// \param PCHPredefLen The length of the predefines buffer in the PCH
695/// file.
696///
697/// \param PCHBufferID The FileID for the PCH predefines buffer.
698///
699/// \returns true if there was a mismatch (in which case the PCH file
700/// should be ignored), or false otherwise.
701bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
702 unsigned PCHPredefLen,
703 FileID PCHBufferID) {
704 const char *Predef = PP.getPredefines().c_str();
705 unsigned PredefLen = PP.getPredefines().size();
706
707 // If the two predefines buffers compare equal, we're done!.
708 if (PredefLen == PCHPredefLen &&
709 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
710 return false;
711
712 // The predefines buffers are different. Produce a reasonable
713 // diagnostic showing where they are different.
714
715 // The source locations (potentially in the two different predefines
716 // buffers)
717 SourceLocation Loc1, Loc2;
718 SourceManager &SourceMgr = PP.getSourceManager();
719
720 // Create a source buffer for our predefines string, so
721 // that we can build a diagnostic that points into that
722 // source buffer.
723 FileID BufferID;
724 if (Predef && Predef[0]) {
725 llvm::MemoryBuffer *Buffer
726 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
727 "<built-in>");
728 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
729 }
730
731 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
732 std::pair<const char *, const char *> Locations
733 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
734
735 if (Locations.first != Predef + MinLen) {
736 // We found the location in the two buffers where there is a
737 // difference. Form source locations to point there (in both
738 // buffers).
739 unsigned Offset = Locations.first - Predef;
740 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
741 .getFileLocWithOffset(Offset);
742 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
743 .getFileLocWithOffset(Offset);
744 } else if (PredefLen > PCHPredefLen) {
745 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
746 .getFileLocWithOffset(MinLen);
747 } else {
748 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
749 .getFileLocWithOffset(MinLen);
750 }
751
752 Diag(Loc1, diag::warn_pch_preprocessor);
753 if (Loc2.isValid())
754 Diag(Loc2, diag::note_predef_in_pch);
755 Diag(diag::note_ignoring_pch) << FileName;
756 return true;
757}
758
Douglas Gregor635f97f2009-04-13 16:31:14 +0000759/// \brief Read the line table in the source manager block.
760/// \returns true if ther was an error.
761static bool ParseLineTable(SourceManager &SourceMgr,
762 llvm::SmallVectorImpl<uint64_t> &Record) {
763 unsigned Idx = 0;
764 LineTableInfo &LineTable = SourceMgr.getLineTable();
765
766 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000767 std::map<int, int> FileIDs;
768 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000769 // Extract the file name
770 unsigned FilenameLen = Record[Idx++];
771 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
772 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000773 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
774 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000775 }
776
777 // Parse the line entries
778 std::vector<LineEntry> Entries;
779 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000780 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000781
782 // Extract the line entries
783 unsigned NumEntries = Record[Idx++];
784 Entries.clear();
785 Entries.reserve(NumEntries);
786 for (unsigned I = 0; I != NumEntries; ++I) {
787 unsigned FileOffset = Record[Idx++];
788 unsigned LineNo = Record[Idx++];
789 int FilenameID = Record[Idx++];
790 SrcMgr::CharacteristicKind FileKind
791 = (SrcMgr::CharacteristicKind)Record[Idx++];
792 unsigned IncludeOffset = Record[Idx++];
793 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
794 FileKind, IncludeOffset));
795 }
796 LineTable.AddEntry(FID, Entries);
797 }
798
799 return false;
800}
801
Douglas Gregorab1cef72009-04-10 03:52:48 +0000802/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000803PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000804 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000805 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
806 Error("Malformed source manager block record");
807 return Failure;
808 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000809
810 SourceManager &SourceMgr = Context.getSourceManager();
811 RecordData Record;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000812 unsigned NumHeaderInfos = 0;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000813 while (true) {
814 unsigned Code = Stream.ReadCode();
815 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000816 if (Stream.ReadBlockEnd()) {
817 Error("Error at end of Source Manager block");
818 return Failure;
819 }
820
821 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000822 }
823
824 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
825 // No known subblocks, always skip them.
826 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000827 if (Stream.SkipBlock()) {
828 Error("Malformed block record");
829 return Failure;
830 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000831 continue;
832 }
833
834 if (Code == llvm::bitc::DEFINE_ABBREV) {
835 Stream.ReadAbbrevRecord();
836 continue;
837 }
838
839 // Read a record.
840 const char *BlobStart;
841 unsigned BlobLen;
842 Record.clear();
843 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
844 default: // Default behavior: ignore.
845 break;
846
847 case pch::SM_SLOC_FILE_ENTRY: {
848 // FIXME: We would really like to delay the creation of this
849 // FileEntry until it is actually required, e.g., when producing
850 // a diagnostic with a source location in this file.
851 const FileEntry *File
852 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
853 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000854 FileID ID = SourceMgr.createFileID(File,
855 SourceLocation::getFromRawEncoding(Record[1]),
856 (CharacteristicKind)Record[2]);
857 if (Record[3])
858 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
859 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000860 break;
861 }
862
863 case pch::SM_SLOC_BUFFER_ENTRY: {
864 const char *Name = BlobStart;
865 unsigned Code = Stream.ReadCode();
866 Record.clear();
867 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
868 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000869 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000870 llvm::MemoryBuffer *Buffer
871 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
872 BlobStart + BlobLen - 1,
873 Name);
874 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
875
876 if (strcmp(Name, "<built-in>") == 0
877 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
878 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000879 break;
880 }
881
882 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
883 SourceLocation SpellingLoc
884 = SourceLocation::getFromRawEncoding(Record[1]);
885 SourceMgr.createInstantiationLoc(
886 SpellingLoc,
887 SourceLocation::getFromRawEncoding(Record[2]),
888 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000889 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000890 break;
891 }
892
Chris Lattnere1be6022009-04-14 23:22:57 +0000893 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000894 if (ParseLineTable(SourceMgr, Record))
895 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000896 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000897
898 case pch::SM_HEADER_FILE_INFO: {
899 HeaderFileInfo HFI;
900 HFI.isImport = Record[0];
901 HFI.DirInfo = Record[1];
902 HFI.NumIncludes = Record[2];
903 HFI.ControllingMacroID = Record[3];
904 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
905 break;
906 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000907 }
908 }
909}
910
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000911/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
912/// specified cursor. Read the abbreviations that are at the top of the block
913/// and then leave the cursor pointing into the block.
914bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
915 unsigned BlockID) {
916 if (Cursor.EnterSubBlock(BlockID)) {
917 Error("Malformed block record");
918 return Failure;
919 }
920
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000921 while (true) {
922 unsigned Code = Cursor.ReadCode();
923
924 // We expect all abbrevs to be at the start of the block.
925 if (Code != llvm::bitc::DEFINE_ABBREV)
926 return false;
927 Cursor.ReadAbbrevRecord();
928 }
929}
930
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000931void PCHReader::ReadMacroRecord(uint64_t Offset) {
932 // Keep track of where we are in the stream, then jump back there
933 // after reading this macro.
934 SavedStreamPosition SavedPosition(Stream);
935
936 Stream.JumpToBit(Offset);
937 RecordData Record;
938 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
939 MacroInfo *Macro = 0;
Steve Naroffcda68f22009-04-24 20:03:17 +0000940
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000941 while (true) {
942 unsigned Code = Stream.ReadCode();
943 switch (Code) {
944 case llvm::bitc::END_BLOCK:
945 return;
946
947 case llvm::bitc::ENTER_SUBBLOCK:
948 // No known subblocks, always skip them.
949 Stream.ReadSubBlockID();
950 if (Stream.SkipBlock()) {
951 Error("Malformed block record");
952 return;
953 }
954 continue;
955
956 case llvm::bitc::DEFINE_ABBREV:
957 Stream.ReadAbbrevRecord();
958 continue;
959 default: break;
960 }
961
962 // Read a record.
963 Record.clear();
964 pch::PreprocessorRecordTypes RecType =
965 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
966 switch (RecType) {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000967 case pch::PP_MACRO_OBJECT_LIKE:
968 case pch::PP_MACRO_FUNCTION_LIKE: {
969 // If we already have a macro, that means that we've hit the end
970 // of the definition of the macro we were looking for. We're
971 // done.
972 if (Macro)
973 return;
974
975 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
976 if (II == 0) {
977 Error("Macro must have a name");
978 return;
979 }
980 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
981 bool isUsed = Record[2];
982
983 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
984 MI->setIsUsed(isUsed);
985
986 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
987 // Decode function-like macro info.
988 bool isC99VarArgs = Record[3];
989 bool isGNUVarArgs = Record[4];
990 MacroArgs.clear();
991 unsigned NumArgs = Record[5];
992 for (unsigned i = 0; i != NumArgs; ++i)
993 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
994
995 // Install function-like macro info.
996 MI->setIsFunctionLike();
997 if (isC99VarArgs) MI->setIsC99Varargs();
998 if (isGNUVarArgs) MI->setIsGNUVarargs();
999 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
1000 PP.getPreprocessorAllocator());
1001 }
1002
1003 // Finally, install the macro.
1004 PP.setMacroInfo(II, MI);
1005
1006 // Remember that we saw this macro last so that we add the tokens that
1007 // form its body to it.
1008 Macro = MI;
1009 ++NumMacrosRead;
1010 break;
1011 }
1012
1013 case pch::PP_TOKEN: {
1014 // If we see a TOKEN before a PP_MACRO_*, then the file is
1015 // erroneous, just pretend we didn't see this.
1016 if (Macro == 0) break;
1017
1018 Token Tok;
1019 Tok.startToken();
1020 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1021 Tok.setLength(Record[1]);
1022 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1023 Tok.setIdentifierInfo(II);
1024 Tok.setKind((tok::TokenKind)Record[3]);
1025 Tok.setFlag((Token::TokenFlags)Record[4]);
1026 Macro->AddTokenToBody(Tok);
1027 break;
1028 }
Steve Naroffcda68f22009-04-24 20:03:17 +00001029 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001030 }
1031}
1032
Douglas Gregorc713da92009-04-21 22:25:48 +00001033PCHReader::PCHReadResult
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001034PCHReader::ReadPCHBlock() {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001035 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1036 Error("Malformed block record");
1037 return Failure;
1038 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001039
1040 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +00001041 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001042 while (!Stream.AtEndOfStream()) {
1043 unsigned Code = Stream.ReadCode();
1044 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001045 if (Stream.ReadBlockEnd()) {
1046 Error("Error at end of module block");
1047 return Failure;
1048 }
Chris Lattner29241862009-04-11 21:15:38 +00001049
Douglas Gregor179cfb12009-04-10 20:39:37 +00001050 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001051 }
1052
1053 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1054 switch (Stream.ReadSubBlockID()) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001055 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1056 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +00001057 if (Stream.SkipBlock()) {
1058 Error("Malformed block record");
1059 return Failure;
1060 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001061 break;
1062
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001063 case pch::DECLS_BLOCK_ID:
1064 // We lazily load the decls block, but we want to set up the
1065 // DeclsCursor cursor to point into it. Clone our current bitcode
1066 // cursor to it, enter the block and read the abbrevs in that block.
1067 // With the main cursor, we just skip over it.
1068 DeclsCursor = Stream;
1069 if (Stream.SkipBlock() || // Skip with the main cursor.
1070 // Read the abbrevs.
1071 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
1072 Error("Malformed block record");
1073 return Failure;
1074 }
1075 break;
1076
Chris Lattner29241862009-04-11 21:15:38 +00001077 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner29241862009-04-11 21:15:38 +00001078 if (Stream.SkipBlock()) {
1079 Error("Malformed block record");
1080 return Failure;
1081 }
1082 break;
Steve Naroff9e84d782009-04-23 10:39:46 +00001083
Douglas Gregorab1cef72009-04-10 03:52:48 +00001084 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001085 switch (ReadSourceManagerBlock()) {
1086 case Success:
1087 break;
1088
1089 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001090 Error("Malformed source manager block");
1091 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001092
1093 case IgnorePCH:
1094 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001095 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001096 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001097 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001098 continue;
1099 }
1100
1101 if (Code == llvm::bitc::DEFINE_ABBREV) {
1102 Stream.ReadAbbrevRecord();
1103 continue;
1104 }
1105
1106 // Read and process a record.
1107 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +00001108 const char *BlobStart = 0;
1109 unsigned BlobLen = 0;
1110 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1111 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001112 default: // Default behavior: ignore.
1113 break;
1114
1115 case pch::TYPE_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001116 if (!TypesLoaded.empty()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001117 Error("Duplicate TYPE_OFFSET record in PCH file");
1118 return Failure;
1119 }
Douglas Gregor24a224c2009-04-25 18:35:21 +00001120 TypeOffsets = (const uint64_t *)BlobStart;
1121 TypesLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001122 break;
1123
1124 case pch::DECL_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001125 if (!DeclsLoaded.empty()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001126 Error("Duplicate DECL_OFFSET record in PCH file");
1127 return Failure;
1128 }
Douglas Gregor24a224c2009-04-25 18:35:21 +00001129 DeclOffsets = (const uint64_t *)BlobStart;
1130 DeclsLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001131 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001132
1133 case pch::LANGUAGE_OPTIONS:
1134 if (ParseLanguageOptions(Record))
1135 return IgnorePCH;
1136 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001137
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001138 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +00001139 std::string TargetTriple(BlobStart, BlobLen);
1140 if (TargetTriple != Context.Target.getTargetTriple()) {
1141 Diag(diag::warn_pch_target_triple)
1142 << TargetTriple << Context.Target.getTargetTriple();
1143 Diag(diag::note_ignoring_pch) << FileName;
1144 return IgnorePCH;
1145 }
1146 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001147 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001148
1149 case pch::IDENTIFIER_TABLE:
Douglas Gregorc713da92009-04-21 22:25:48 +00001150 IdentifierTableData = BlobStart;
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001151 if (Record[0]) {
1152 IdentifierLookupTable
1153 = PCHIdentifierLookupTable::Create(
Douglas Gregorc713da92009-04-21 22:25:48 +00001154 (const unsigned char *)IdentifierTableData + Record[0],
1155 (const unsigned char *)IdentifierTableData,
1156 PCHIdentifierLookupTrait(*this));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001157 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1158 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001159 break;
1160
1161 case pch::IDENTIFIER_OFFSET:
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001162 if (!IdentifiersLoaded.empty()) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001163 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1164 return Failure;
1165 }
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001166 IdentifierOffsets = (const uint32_t *)BlobStart;
1167 IdentifiersLoaded.resize(Record[0]);
Douglas Gregoreccb51d2009-04-25 23:30:02 +00001168 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001169 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001170
1171 case pch::EXTERNAL_DEFINITIONS:
1172 if (!ExternalDefinitions.empty()) {
1173 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1174 return Failure;
1175 }
1176 ExternalDefinitions.swap(Record);
1177 break;
Douglas Gregor456e0952009-04-17 22:13:46 +00001178
Douglas Gregore01ad442009-04-18 05:55:16 +00001179 case pch::SPECIAL_TYPES:
1180 SpecialTypes.swap(Record);
1181 break;
1182
Douglas Gregor456e0952009-04-17 22:13:46 +00001183 case pch::STATISTICS:
1184 TotalNumStatements = Record[0];
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001185 TotalNumMacros = Record[1];
Douglas Gregoraf136d92009-04-22 22:34:57 +00001186 TotalLexicalDeclContexts = Record[2];
1187 TotalVisibleDeclContexts = Record[3];
Douglas Gregor456e0952009-04-17 22:13:46 +00001188 break;
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001189 case pch::TENTATIVE_DEFINITIONS:
1190 if (!TentativeDefinitions.empty()) {
1191 Error("Duplicate TENTATIVE_DEFINITIONS record in PCH file");
1192 return Failure;
1193 }
1194 TentativeDefinitions.swap(Record);
1195 break;
Douglas Gregor062d9482009-04-22 22:18:58 +00001196
1197 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1198 if (!LocallyScopedExternalDecls.empty()) {
1199 Error("Duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1200 return Failure;
1201 }
1202 LocallyScopedExternalDecls.swap(Record);
1203 break;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001204
Douglas Gregor2d711832009-04-25 17:48:32 +00001205 case pch::SELECTOR_OFFSETS:
1206 SelectorOffsets = (const uint32_t *)BlobStart;
1207 TotalNumSelectors = Record[0];
1208 SelectorsLoaded.resize(TotalNumSelectors);
1209 break;
1210
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001211 case pch::METHOD_POOL:
Douglas Gregor2d711832009-04-25 17:48:32 +00001212 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1213 if (Record[0])
1214 MethodPoolLookupTable
1215 = PCHMethodPoolLookupTable::Create(
1216 MethodPoolLookupTableData + Record[0],
1217 MethodPoolLookupTableData,
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001218 PCHMethodPoolLookupTrait(*this));
Douglas Gregor2d711832009-04-25 17:48:32 +00001219 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001220 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001221
1222 case pch::PP_COUNTER_VALUE:
1223 if (!Record.empty())
1224 PP.setCounterValue(Record[0]);
1225 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001226 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001227 }
Douglas Gregor179cfb12009-04-10 20:39:37 +00001228 Error("Premature end of bitstream");
1229 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001230}
1231
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001232PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001233 // Set the PCH file name.
1234 this->FileName = FileName;
1235
Douglas Gregorc34897d2009-04-09 22:27:44 +00001236 // Open the PCH file.
1237 std::string ErrStr;
1238 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001239 if (!Buffer) {
1240 Error(ErrStr.c_str());
1241 return IgnorePCH;
1242 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001243
1244 // Initialize the stream
Chris Lattner587788a2009-04-26 20:59:20 +00001245 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1246 (const unsigned char *)Buffer->getBufferEnd());
1247 Stream.init(StreamFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001248
1249 // Sniff for the signature.
1250 if (Stream.Read(8) != 'C' ||
1251 Stream.Read(8) != 'P' ||
1252 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001253 Stream.Read(8) != 'H') {
1254 Error("Not a PCH file");
1255 return IgnorePCH;
1256 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001257
Douglas Gregorc34897d2009-04-09 22:27:44 +00001258 while (!Stream.AtEndOfStream()) {
1259 unsigned Code = Stream.ReadCode();
1260
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001261 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1262 Error("Invalid record at top-level");
1263 return Failure;
1264 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001265
1266 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregorc713da92009-04-21 22:25:48 +00001267
Douglas Gregorc34897d2009-04-09 22:27:44 +00001268 // We only know the PCH subblock ID.
1269 switch (BlockID) {
1270 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001271 if (Stream.ReadBlockInfoBlock()) {
1272 Error("Malformed BlockInfoBlock");
1273 return Failure;
1274 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001275 break;
1276 case pch::PCH_BLOCK_ID:
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001277 switch (ReadPCHBlock()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001278 case Success:
1279 break;
1280
1281 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001282 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001283
1284 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001285 // FIXME: We could consider reading through to the end of this
1286 // PCH block, skipping subblocks, to see if there are other
1287 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001288 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001289 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001290 break;
1291 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001292 if (Stream.SkipBlock()) {
1293 Error("Malformed block record");
1294 return Failure;
1295 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001296 break;
1297 }
1298 }
1299
1300 // Load the translation unit declaration
1301 ReadDeclRecord(DeclOffsets[0], 0);
1302
Douglas Gregorc713da92009-04-21 22:25:48 +00001303 // Initialization of builtins and library builtins occurs before the
1304 // PCH file is read, so there may be some identifiers that were
1305 // loaded into the IdentifierTable before we intercepted the
1306 // creation of identifiers. Iterate through the list of known
1307 // identifiers and determine whether we have to establish
1308 // preprocessor definitions or top-level identifier declaration
1309 // chains for those identifiers.
1310 //
1311 // We copy the IdentifierInfo pointers to a small vector first,
1312 // since de-serializing declarations or macro definitions can add
1313 // new entries into the identifier table, invalidating the
1314 // iterators.
1315 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1316 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1317 IdEnd = PP.getIdentifierTable().end();
1318 Id != IdEnd; ++Id)
1319 Identifiers.push_back(Id->second);
1320 PCHIdentifierLookupTable *IdTable
1321 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1322 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1323 IdentifierInfo *II = Identifiers[I];
1324 // Look in the on-disk hash table for an entry for
1325 PCHIdentifierLookupTrait Info(*this, II);
1326 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1327 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1328 if (Pos == IdTable->end())
1329 continue;
1330
1331 // Dereferencing the iterator has the effect of populating the
1332 // IdentifierInfo node with the various declarations it needs.
1333 (void)*Pos;
1334 }
1335
Douglas Gregore01ad442009-04-18 05:55:16 +00001336 // Load the special types.
1337 Context.setBuiltinVaListType(
1338 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001339 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1340 Context.setObjCIdType(GetType(Id));
1341 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1342 Context.setObjCSelType(GetType(Sel));
1343 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1344 Context.setObjCProtoType(GetType(Proto));
1345 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1346 Context.setObjCClassType(GetType(Class));
1347 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1348 Context.setCFConstantStringType(GetType(String));
1349 if (unsigned FastEnum
1350 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1351 Context.setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001352
Douglas Gregorc713da92009-04-21 22:25:48 +00001353 return Success;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001354}
1355
Douglas Gregor179cfb12009-04-10 20:39:37 +00001356/// \brief Parse the record that corresponds to a LangOptions data
1357/// structure.
1358///
1359/// This routine compares the language options used to generate the
1360/// PCH file against the language options set for the current
1361/// compilation. For each option, we classify differences between the
1362/// two compiler states as either "benign" or "important". Benign
1363/// differences don't matter, and we accept them without complaint
1364/// (and without modifying the language options). Differences between
1365/// the states for important options cause the PCH file to be
1366/// unusable, so we emit a warning and return true to indicate that
1367/// there was an error.
1368///
1369/// \returns true if the PCH file is unacceptable, false otherwise.
1370bool PCHReader::ParseLanguageOptions(
1371 const llvm::SmallVectorImpl<uint64_t> &Record) {
1372 const LangOptions &LangOpts = Context.getLangOptions();
1373#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1374#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1375 if (Record[Idx] != LangOpts.Option) { \
1376 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1377 Diag(diag::note_ignoring_pch) << FileName; \
1378 return true; \
1379 } \
1380 ++Idx
1381
1382 unsigned Idx = 0;
1383 PARSE_LANGOPT_BENIGN(Trigraphs);
1384 PARSE_LANGOPT_BENIGN(BCPLComment);
1385 PARSE_LANGOPT_BENIGN(DollarIdents);
1386 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1387 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1388 PARSE_LANGOPT_BENIGN(ImplicitInt);
1389 PARSE_LANGOPT_BENIGN(Digraphs);
1390 PARSE_LANGOPT_BENIGN(HexFloats);
1391 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1392 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1393 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1394 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1395 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1396 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1397 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1398 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1399 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1400 PARSE_LANGOPT_BENIGN(PascalStrings);
1401 PARSE_LANGOPT_BENIGN(Boolean);
1402 PARSE_LANGOPT_BENIGN(WritableStrings);
1403 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1404 diag::warn_pch_lax_vector_conversions);
1405 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1406 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1407 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1408 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1409 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1410 diag::warn_pch_thread_safe_statics);
1411 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1412 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1413 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1414 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1415 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1416 diag::warn_pch_heinous_extensions);
1417 // FIXME: Most of the options below are benign if the macro wasn't
1418 // used. Unfortunately, this means that a PCH compiled without
1419 // optimization can't be used with optimization turned on, even
1420 // though the only thing that changes is whether __OPTIMIZE__ was
1421 // defined... but if __OPTIMIZE__ never showed up in the header, it
1422 // doesn't matter. We could consider making this some special kind
1423 // of check.
1424 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1425 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1426 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1427 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1428 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1429 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1430 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1431 Diag(diag::warn_pch_gc_mode)
1432 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1433 Diag(diag::note_ignoring_pch) << FileName;
1434 return true;
1435 }
1436 ++Idx;
1437 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1438 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1439#undef PARSE_LANGOPT_IRRELEVANT
1440#undef PARSE_LANGOPT_BENIGN
1441
1442 return false;
1443}
1444
Douglas Gregorc34897d2009-04-09 22:27:44 +00001445/// \brief Read and return the type at the given offset.
1446///
1447/// This routine actually reads the record corresponding to the type
1448/// at the given offset in the bitstream. It is a helper routine for
1449/// GetType, which deals with reading type IDs.
1450QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001451 // Keep track of where we are in the stream, then jump back there
1452 // after reading this type.
1453 SavedStreamPosition SavedPosition(Stream);
1454
Douglas Gregorc34897d2009-04-09 22:27:44 +00001455 Stream.JumpToBit(Offset);
1456 RecordData Record;
1457 unsigned Code = Stream.ReadCode();
1458 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001459 case pch::TYPE_EXT_QUAL: {
1460 assert(Record.size() == 3 &&
1461 "Incorrect encoding of extended qualifier type");
1462 QualType Base = GetType(Record[0]);
1463 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1464 unsigned AddressSpace = Record[2];
1465
1466 QualType T = Base;
1467 if (GCAttr != QualType::GCNone)
1468 T = Context.getObjCGCQualType(T, GCAttr);
1469 if (AddressSpace)
1470 T = Context.getAddrSpaceQualType(T, AddressSpace);
1471 return T;
1472 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001473
Douglas Gregorc34897d2009-04-09 22:27:44 +00001474 case pch::TYPE_FIXED_WIDTH_INT: {
1475 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1476 return Context.getFixedWidthIntType(Record[0], Record[1]);
1477 }
1478
1479 case pch::TYPE_COMPLEX: {
1480 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1481 QualType ElemType = GetType(Record[0]);
1482 return Context.getComplexType(ElemType);
1483 }
1484
1485 case pch::TYPE_POINTER: {
1486 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1487 QualType PointeeType = GetType(Record[0]);
1488 return Context.getPointerType(PointeeType);
1489 }
1490
1491 case pch::TYPE_BLOCK_POINTER: {
1492 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1493 QualType PointeeType = GetType(Record[0]);
1494 return Context.getBlockPointerType(PointeeType);
1495 }
1496
1497 case pch::TYPE_LVALUE_REFERENCE: {
1498 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1499 QualType PointeeType = GetType(Record[0]);
1500 return Context.getLValueReferenceType(PointeeType);
1501 }
1502
1503 case pch::TYPE_RVALUE_REFERENCE: {
1504 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1505 QualType PointeeType = GetType(Record[0]);
1506 return Context.getRValueReferenceType(PointeeType);
1507 }
1508
1509 case pch::TYPE_MEMBER_POINTER: {
1510 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1511 QualType PointeeType = GetType(Record[0]);
1512 QualType ClassType = GetType(Record[1]);
1513 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1514 }
1515
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001516 case pch::TYPE_CONSTANT_ARRAY: {
1517 QualType ElementType = GetType(Record[0]);
1518 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1519 unsigned IndexTypeQuals = Record[2];
1520 unsigned Idx = 3;
1521 llvm::APInt Size = ReadAPInt(Record, Idx);
1522 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1523 }
1524
1525 case pch::TYPE_INCOMPLETE_ARRAY: {
1526 QualType ElementType = GetType(Record[0]);
1527 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1528 unsigned IndexTypeQuals = Record[2];
1529 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1530 }
1531
1532 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001533 QualType ElementType = GetType(Record[0]);
1534 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1535 unsigned IndexTypeQuals = Record[2];
1536 return Context.getVariableArrayType(ElementType, ReadExpr(),
1537 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001538 }
1539
1540 case pch::TYPE_VECTOR: {
1541 if (Record.size() != 2) {
1542 Error("Incorrect encoding of vector type in PCH file");
1543 return QualType();
1544 }
1545
1546 QualType ElementType = GetType(Record[0]);
1547 unsigned NumElements = Record[1];
1548 return Context.getVectorType(ElementType, NumElements);
1549 }
1550
1551 case pch::TYPE_EXT_VECTOR: {
1552 if (Record.size() != 2) {
1553 Error("Incorrect encoding of extended vector type in PCH file");
1554 return QualType();
1555 }
1556
1557 QualType ElementType = GetType(Record[0]);
1558 unsigned NumElements = Record[1];
1559 return Context.getExtVectorType(ElementType, NumElements);
1560 }
1561
1562 case pch::TYPE_FUNCTION_NO_PROTO: {
1563 if (Record.size() != 1) {
1564 Error("Incorrect encoding of no-proto function type");
1565 return QualType();
1566 }
1567 QualType ResultType = GetType(Record[0]);
1568 return Context.getFunctionNoProtoType(ResultType);
1569 }
1570
1571 case pch::TYPE_FUNCTION_PROTO: {
1572 QualType ResultType = GetType(Record[0]);
1573 unsigned Idx = 1;
1574 unsigned NumParams = Record[Idx++];
1575 llvm::SmallVector<QualType, 16> ParamTypes;
1576 for (unsigned I = 0; I != NumParams; ++I)
1577 ParamTypes.push_back(GetType(Record[Idx++]));
1578 bool isVariadic = Record[Idx++];
1579 unsigned Quals = Record[Idx++];
1580 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1581 isVariadic, Quals);
1582 }
1583
1584 case pch::TYPE_TYPEDEF:
1585 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1586 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1587
1588 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001589 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001590
1591 case pch::TYPE_TYPEOF: {
1592 if (Record.size() != 1) {
1593 Error("Incorrect encoding of typeof(type) in PCH file");
1594 return QualType();
1595 }
1596 QualType UnderlyingType = GetType(Record[0]);
1597 return Context.getTypeOfType(UnderlyingType);
1598 }
1599
1600 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001601 assert(Record.size() == 1 && "Incorrect encoding of record type");
1602 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001603
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001604 case pch::TYPE_ENUM:
1605 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1606 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1607
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001608 case pch::TYPE_OBJC_INTERFACE:
Chris Lattner80f83c62009-04-22 05:57:30 +00001609 assert(Record.size() == 1 && "Incorrect encoding of objc interface type");
1610 return Context.getObjCInterfaceType(
1611 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001612
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001613 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1614 unsigned Idx = 0;
1615 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1616 unsigned NumProtos = Record[Idx++];
1617 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1618 for (unsigned I = 0; I != NumProtos; ++I)
1619 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1620 return Context.getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
1621 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001622
Chris Lattner9b9f2352009-04-22 06:40:03 +00001623 case pch::TYPE_OBJC_QUALIFIED_ID: {
1624 unsigned Idx = 0;
1625 unsigned NumProtos = Record[Idx++];
1626 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1627 for (unsigned I = 0; I != NumProtos; ++I)
1628 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1629 return Context.getObjCQualifiedIdType(&Protos[0], NumProtos);
1630 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001631 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001632 // Suppress a GCC warning
1633 return QualType();
1634}
1635
1636/// \brief Note that we have loaded the declaration with the given
1637/// Index.
1638///
1639/// This routine notes that this declaration has already been loaded,
1640/// so that future GetDecl calls will return this declaration rather
1641/// than trying to load a new declaration.
1642inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001643 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1644 DeclsLoaded[Index] = D;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001645}
1646
Douglas Gregorf93cfee2009-04-25 00:41:30 +00001647/// \brief Determine whether the consumer will be interested in seeing
1648/// this declaration (via HandleTopLevelDecl).
1649///
1650/// This routine should return true for anything that might affect
1651/// code generation, e.g., inline function definitions, Objective-C
1652/// declarations with metadata, etc.
1653static bool isConsumerInterestedIn(Decl *D) {
1654 if (VarDecl *Var = dyn_cast<VarDecl>(D))
1655 return Var->isFileVarDecl() && Var->getInit();
1656 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1657 return Func->isThisDeclarationADefinition();
1658 return isa<ObjCProtocolDecl>(D);
1659}
1660
Douglas Gregorc34897d2009-04-09 22:27:44 +00001661/// \brief Read the declaration at the given offset from the PCH file.
1662Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001663 // Keep track of where we are in the stream, then jump back there
1664 // after reading this declaration.
1665 SavedStreamPosition SavedPosition(Stream);
1666
Douglas Gregorc34897d2009-04-09 22:27:44 +00001667 Decl *D = 0;
1668 Stream.JumpToBit(Offset);
1669 RecordData Record;
1670 unsigned Code = Stream.ReadCode();
1671 unsigned Idx = 0;
1672 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001673
Douglas Gregorc34897d2009-04-09 22:27:44 +00001674 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001675 case pch::DECL_ATTR:
1676 case pch::DECL_CONTEXT_LEXICAL:
1677 case pch::DECL_CONTEXT_VISIBLE:
1678 assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1679 break;
1680
Douglas Gregorc34897d2009-04-09 22:27:44 +00001681 case pch::DECL_TRANSLATION_UNIT:
1682 assert(Index == 0 && "Translation unit must be at index 0");
Douglas Gregorc34897d2009-04-09 22:27:44 +00001683 D = Context.getTranslationUnitDecl();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001684 break;
1685
1686 case pch::DECL_TYPEDEF: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001687 D = TypedefDecl::Create(Context, 0, SourceLocation(), 0, QualType());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001688 break;
1689 }
1690
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001691 case pch::DECL_ENUM: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001692 D = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001693 break;
1694 }
1695
Douglas Gregor982365e2009-04-13 21:20:57 +00001696 case pch::DECL_RECORD: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001697 D = RecordDecl::Create(Context, TagDecl::TK_struct, 0, SourceLocation(),
1698 0, 0);
Douglas Gregor982365e2009-04-13 21:20:57 +00001699 break;
1700 }
1701
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001702 case pch::DECL_ENUM_CONSTANT: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001703 D = EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1704 0, llvm::APSInt());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001705 break;
1706 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001707
1708 case pch::DECL_FUNCTION: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001709 D = FunctionDecl::Create(Context, 0, SourceLocation(), DeclarationName(),
1710 QualType());
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001711 break;
1712 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001713
Steve Naroff79ea0e02009-04-20 15:06:07 +00001714 case pch::DECL_OBJC_METHOD: {
1715 D = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
1716 Selector(), QualType(), 0);
1717 break;
1718 }
1719
Steve Naroff97b53bd2009-04-21 15:12:33 +00001720 case pch::DECL_OBJC_INTERFACE: {
Steve Naroff7333b492009-04-20 20:09:33 +00001721 D = ObjCInterfaceDecl::Create(Context, 0, SourceLocation(), 0);
1722 break;
1723 }
1724
Steve Naroff97b53bd2009-04-21 15:12:33 +00001725 case pch::DECL_OBJC_IVAR: {
Steve Naroff7333b492009-04-20 20:09:33 +00001726 D = ObjCIvarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1727 ObjCIvarDecl::None);
1728 break;
1729 }
1730
Steve Naroff97b53bd2009-04-21 15:12:33 +00001731 case pch::DECL_OBJC_PROTOCOL: {
1732 D = ObjCProtocolDecl::Create(Context, 0, SourceLocation(), 0);
1733 break;
1734 }
1735
1736 case pch::DECL_OBJC_AT_DEFS_FIELD: {
1737 D = ObjCAtDefsFieldDecl::Create(Context, 0, SourceLocation(), 0,
1738 QualType(), 0);
1739 break;
1740 }
1741
1742 case pch::DECL_OBJC_CLASS: {
1743 D = ObjCClassDecl::Create(Context, 0, SourceLocation());
1744 break;
1745 }
1746
1747 case pch::DECL_OBJC_FORWARD_PROTOCOL: {
1748 D = ObjCForwardProtocolDecl::Create(Context, 0, SourceLocation());
1749 break;
1750 }
1751
1752 case pch::DECL_OBJC_CATEGORY: {
1753 D = ObjCCategoryDecl::Create(Context, 0, SourceLocation(), 0);
1754 break;
1755 }
1756
1757 case pch::DECL_OBJC_CATEGORY_IMPL: {
Douglas Gregor58e7ce42009-04-23 02:53:57 +00001758 D = ObjCCategoryImplDecl::Create(Context, 0, SourceLocation(), 0, 0);
Steve Naroff97b53bd2009-04-21 15:12:33 +00001759 break;
1760 }
1761
1762 case pch::DECL_OBJC_IMPLEMENTATION: {
Douglas Gregor087dbf32009-04-23 03:23:08 +00001763 D = ObjCImplementationDecl::Create(Context, 0, SourceLocation(), 0, 0);
Steve Naroff97b53bd2009-04-21 15:12:33 +00001764 break;
1765 }
1766
1767 case pch::DECL_OBJC_COMPATIBLE_ALIAS: {
Douglas Gregorf4936c72009-04-23 03:51:49 +00001768 D = ObjCCompatibleAliasDecl::Create(Context, 0, SourceLocation(), 0, 0);
Steve Naroff97b53bd2009-04-21 15:12:33 +00001769 break;
1770 }
1771
1772 case pch::DECL_OBJC_PROPERTY: {
Douglas Gregor3839f1c2009-04-22 23:20:34 +00001773 D = ObjCPropertyDecl::Create(Context, 0, SourceLocation(), 0, QualType());
Steve Naroff97b53bd2009-04-21 15:12:33 +00001774 break;
1775 }
1776
1777 case pch::DECL_OBJC_PROPERTY_IMPL: {
Douglas Gregor3f2c5052009-04-23 03:43:53 +00001778 D = ObjCPropertyImplDecl::Create(Context, 0, SourceLocation(),
1779 SourceLocation(), 0,
1780 ObjCPropertyImplDecl::Dynamic, 0);
Steve Naroff97b53bd2009-04-21 15:12:33 +00001781 break;
1782 }
1783
Douglas Gregor982365e2009-04-13 21:20:57 +00001784 case pch::DECL_FIELD: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001785 D = FieldDecl::Create(Context, 0, SourceLocation(), 0, QualType(), 0,
1786 false);
Douglas Gregor982365e2009-04-13 21:20:57 +00001787 break;
1788 }
1789
Douglas Gregorce066712009-04-26 22:20:50 +00001790 case pch::DECL_VAR:
Douglas Gregorddf4d092009-04-16 22:29:51 +00001791 D = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1792 VarDecl::None, SourceLocation());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001793 break;
Douglas Gregorce066712009-04-26 22:20:50 +00001794
1795 case pch::DECL_IMPLICIT_PARAM:
1796 D = ImplicitParamDecl::Create(Context, 0, SourceLocation(), 0, QualType());
1797 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001798
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001799 case pch::DECL_PARM_VAR: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001800 D = ParmVarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1801 VarDecl::None, 0);
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001802 break;
1803 }
1804
1805 case pch::DECL_ORIGINAL_PARM_VAR: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001806 D = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001807 QualType(), QualType(), VarDecl::None,
1808 0);
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001809 break;
1810 }
1811
Douglas Gregor2a491792009-04-13 22:49:25 +00001812 case pch::DECL_FILE_SCOPE_ASM: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001813 D = FileScopeAsmDecl::Create(Context, 0, SourceLocation(), 0);
Douglas Gregor2a491792009-04-13 22:49:25 +00001814 break;
1815 }
1816
1817 case pch::DECL_BLOCK: {
Douglas Gregorddf4d092009-04-16 22:29:51 +00001818 D = BlockDecl::Create(Context, 0, SourceLocation());
Douglas Gregor2a491792009-04-13 22:49:25 +00001819 break;
1820 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001821 }
1822
Douglas Gregorc713da92009-04-21 22:25:48 +00001823 assert(D && "Unknown declaration reading PCH file");
Douglas Gregorddf4d092009-04-16 22:29:51 +00001824 if (D) {
1825 LoadedDecl(Index, D);
1826 Reader.Visit(D);
1827 }
1828
Douglas Gregorc34897d2009-04-09 22:27:44 +00001829 // If this declaration is also a declaration context, get the
1830 // offsets for its tables of lexical and visible declarations.
1831 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1832 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1833 if (Offsets.first || Offsets.second) {
1834 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1835 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1836 DeclContextOffsets[DC] = Offsets;
1837 }
1838 }
1839 assert(Idx == Record.size());
1840
Douglas Gregorf93cfee2009-04-25 00:41:30 +00001841 // If we have deserialized a declaration that has a definition the
1842 // AST consumer might need to know about, notify the consumer
1843 // about that definition now or queue it for later.
1844 if (isConsumerInterestedIn(D)) {
1845 if (Consumer) {
Douglas Gregorafb99482009-04-24 23:42:14 +00001846 DeclGroupRef DG(D);
1847 Consumer->HandleTopLevelDecl(DG);
Douglas Gregorf93cfee2009-04-25 00:41:30 +00001848 } else {
1849 InterestingDecls.push_back(D);
Douglas Gregor405b6432009-04-22 19:09:20 +00001850 }
1851 }
1852
Douglas Gregorc34897d2009-04-09 22:27:44 +00001853 return D;
1854}
1855
Douglas Gregorac8f2802009-04-10 17:25:41 +00001856QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001857 unsigned Quals = ID & 0x07;
1858 unsigned Index = ID >> 3;
1859
1860 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1861 QualType T;
1862 switch ((pch::PredefinedTypeIDs)Index) {
1863 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1864 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1865 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1866
1867 case pch::PREDEF_TYPE_CHAR_U_ID:
1868 case pch::PREDEF_TYPE_CHAR_S_ID:
1869 // FIXME: Check that the signedness of CharTy is correct!
1870 T = Context.CharTy;
1871 break;
1872
1873 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1874 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1875 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1876 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1877 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1878 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1879 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1880 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1881 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1882 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1883 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1884 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1885 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1886 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1887 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1888 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1889 }
1890
1891 assert(!T.isNull() && "Unknown predefined type");
1892 return T.getQualifiedType(Quals);
1893 }
1894
1895 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregore43f0972009-04-26 03:49:13 +00001896 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001897 if (!TypesLoaded[Index])
1898 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001899
Douglas Gregor24a224c2009-04-25 18:35:21 +00001900 return QualType(TypesLoaded[Index], Quals);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001901}
1902
Douglas Gregorac8f2802009-04-10 17:25:41 +00001903Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001904 if (ID == 0)
1905 return 0;
1906
Douglas Gregor24a224c2009-04-25 18:35:21 +00001907 if (ID > DeclsLoaded.size()) {
1908 Error("Declaration ID out-of-range for PCH file");
1909 return 0;
1910 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001911
Douglas Gregor24a224c2009-04-25 18:35:21 +00001912 unsigned Index = ID - 1;
1913 if (!DeclsLoaded[Index])
1914 ReadDeclRecord(DeclOffsets[Index], Index);
1915
1916 return DeclsLoaded[Index];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001917}
1918
Douglas Gregor3b9a7c82009-04-18 00:07:54 +00001919Stmt *PCHReader::GetStmt(uint64_t Offset) {
1920 // Keep track of where we are in the stream, then jump back there
1921 // after reading this declaration.
1922 SavedStreamPosition SavedPosition(Stream);
1923
1924 Stream.JumpToBit(Offset);
1925 return ReadStmt();
1926}
1927
Douglas Gregorc34897d2009-04-09 22:27:44 +00001928bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001929 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001930 assert(DC->hasExternalLexicalStorage() &&
1931 "DeclContext has no lexical decls in storage");
1932 uint64_t Offset = DeclContextOffsets[DC].first;
1933 assert(Offset && "DeclContext has no lexical decls in storage");
1934
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001935 // Keep track of where we are in the stream, then jump back there
1936 // after reading this context.
1937 SavedStreamPosition SavedPosition(Stream);
1938
Douglas Gregorc34897d2009-04-09 22:27:44 +00001939 // Load the record containing all of the declarations lexically in
1940 // this context.
1941 Stream.JumpToBit(Offset);
1942 RecordData Record;
1943 unsigned Code = Stream.ReadCode();
1944 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001945 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001946 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1947
1948 // Load all of the declaration IDs
1949 Decls.clear();
1950 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregoraf136d92009-04-22 22:34:57 +00001951 ++NumLexicalDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001952 return false;
1953}
1954
1955bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1956 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1957 assert(DC->hasExternalVisibleStorage() &&
1958 "DeclContext has no visible decls in storage");
1959 uint64_t Offset = DeclContextOffsets[DC].second;
1960 assert(Offset && "DeclContext has no visible decls in storage");
1961
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001962 // Keep track of where we are in the stream, then jump back there
1963 // after reading this context.
1964 SavedStreamPosition SavedPosition(Stream);
1965
Douglas Gregorc34897d2009-04-09 22:27:44 +00001966 // Load the record containing all of the declarations visible in
1967 // this context.
1968 Stream.JumpToBit(Offset);
1969 RecordData Record;
1970 unsigned Code = Stream.ReadCode();
1971 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001972 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001973 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1974 if (Record.size() == 0)
1975 return false;
1976
1977 Decls.clear();
1978
1979 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001980 while (Idx < Record.size()) {
1981 Decls.push_back(VisibleDeclaration());
1982 Decls.back().Name = ReadDeclarationName(Record, Idx);
1983
Douglas Gregorc34897d2009-04-09 22:27:44 +00001984 unsigned Size = Record[Idx++];
1985 llvm::SmallVector<unsigned, 4> & LoadedDecls
1986 = Decls.back().Declarations;
1987 LoadedDecls.reserve(Size);
1988 for (unsigned I = 0; I < Size; ++I)
1989 LoadedDecls.push_back(Record[Idx++]);
1990 }
1991
Douglas Gregoraf136d92009-04-22 22:34:57 +00001992 ++NumVisibleDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001993 return false;
1994}
1995
Douglas Gregor631f6c62009-04-14 00:24:19 +00001996void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor405b6432009-04-22 19:09:20 +00001997 this->Consumer = Consumer;
1998
Douglas Gregor631f6c62009-04-14 00:24:19 +00001999 if (!Consumer)
2000 return;
2001
2002 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2003 Decl *D = GetDecl(ExternalDefinitions[I]);
2004 DeclGroupRef DG(D);
2005 Consumer->HandleTopLevelDecl(DG);
2006 }
Douglas Gregorf93cfee2009-04-25 00:41:30 +00002007
2008 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2009 DeclGroupRef DG(InterestingDecls[I]);
2010 Consumer->HandleTopLevelDecl(DG);
2011 }
Douglas Gregor631f6c62009-04-14 00:24:19 +00002012}
2013
Douglas Gregorc34897d2009-04-09 22:27:44 +00002014void PCHReader::PrintStats() {
2015 std::fprintf(stderr, "*** PCH Statistics:\n");
2016
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002017 unsigned NumTypesLoaded
2018 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2019 (Type *)0);
2020 unsigned NumDeclsLoaded
2021 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2022 (Decl *)0);
2023 unsigned NumIdentifiersLoaded
2024 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2025 IdentifiersLoaded.end(),
2026 (IdentifierInfo *)0);
2027 unsigned NumSelectorsLoaded
2028 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2029 SelectorsLoaded.end(),
2030 Selector());
Douglas Gregor9cf47422009-04-13 20:50:16 +00002031
Douglas Gregor24a224c2009-04-25 18:35:21 +00002032 if (!TypesLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002033 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002034 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2035 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2036 if (!DeclsLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002037 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00002038 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2039 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002040 if (!IdentifiersLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00002041 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002042 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2043 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor2d711832009-04-25 17:48:32 +00002044 if (TotalNumSelectors)
2045 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2046 NumSelectorsLoaded, TotalNumSelectors,
2047 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2048 if (TotalNumStatements)
2049 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2050 NumStatementsRead, TotalNumStatements,
2051 ((float)NumStatementsRead/TotalNumStatements * 100));
2052 if (TotalNumMacros)
2053 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2054 NumMacrosRead, TotalNumMacros,
2055 ((float)NumMacrosRead/TotalNumMacros * 100));
2056 if (TotalLexicalDeclContexts)
2057 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2058 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2059 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2060 * 100));
2061 if (TotalVisibleDeclContexts)
2062 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2063 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2064 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2065 * 100));
2066 if (TotalSelectorsInMethodPool) {
2067 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2068 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2069 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2070 * 100));
2071 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2072 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00002073 std::fprintf(stderr, "\n");
2074}
2075
Douglas Gregorc713da92009-04-21 22:25:48 +00002076void PCHReader::InitializeSema(Sema &S) {
2077 SemaObj = &S;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002078 S.ExternalSource = this;
2079
Douglas Gregor2554cf22009-04-22 21:15:06 +00002080 // Makes sure any declarations that were deserialized "too early"
2081 // still get added to the identifier's declaration chains.
2082 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2083 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2084 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregorc713da92009-04-21 22:25:48 +00002085 }
Douglas Gregor2554cf22009-04-22 21:15:06 +00002086 PreloadedDecls.clear();
Douglas Gregor77b2cd52009-04-22 22:02:47 +00002087
2088 // If there were any tentative definitions, deserialize them and add
2089 // them to Sema's table of tentative definitions.
2090 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2091 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2092 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2093 }
Douglas Gregor062d9482009-04-22 22:18:58 +00002094
2095 // If there were any locally-scoped external declarations,
2096 // deserialize them and add them to Sema's table of locally-scoped
2097 // external declarations.
2098 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2099 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2100 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2101 }
Douglas Gregorc713da92009-04-21 22:25:48 +00002102}
2103
2104IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2105 // Try to find this name within our on-disk hash table
2106 PCHIdentifierLookupTable *IdTable
2107 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2108 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2109 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2110 if (Pos == IdTable->end())
2111 return 0;
2112
2113 // Dereferencing the iterator has the effect of building the
2114 // IdentifierInfo node and populating it with the various
2115 // declarations it needs.
2116 return *Pos;
2117}
2118
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002119std::pair<ObjCMethodList, ObjCMethodList>
2120PCHReader::ReadMethodPool(Selector Sel) {
2121 if (!MethodPoolLookupTable)
2122 return std::pair<ObjCMethodList, ObjCMethodList>();
2123
2124 // Try to find this selector within our on-disk hash table.
2125 PCHMethodPoolLookupTable *PoolTable
2126 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2127 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor2d711832009-04-25 17:48:32 +00002128 if (Pos == PoolTable->end()) {
2129 ++NumMethodPoolMisses;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002130 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor2d711832009-04-25 17:48:32 +00002131 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002132
Douglas Gregor2d711832009-04-25 17:48:32 +00002133 ++NumMethodPoolSelectorsRead;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002134 return *Pos;
2135}
2136
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002137void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregorc713da92009-04-21 22:25:48 +00002138 assert(ID && "Non-zero identifier ID required");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002139 assert(ID <= IdentifiersLoaded.size() && "Identifier ID out of range");
2140 IdentifiersLoaded[ID - 1] = II;
Douglas Gregorc713da92009-04-21 22:25:48 +00002141}
2142
Chris Lattner29241862009-04-11 21:15:38 +00002143IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002144 if (ID == 0)
2145 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00002146
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002147 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002148 Error("No identifier table in PCH file");
2149 return 0;
2150 }
Chris Lattner29241862009-04-11 21:15:38 +00002151
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002152 if (!IdentifiersLoaded[ID - 1]) {
2153 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002154 const char *Str = IdentifierTableData + Offset;
Douglas Gregor85c4a872009-04-25 21:04:17 +00002155
2156 // If there is an identifier lookup table, but the offset of this
2157 // string is after the identifier table itself, then we know that
2158 // this string is not in the on-disk hash table. Therefore,
2159 // disable lookup into the hash table when looking for this
2160 // identifier.
2161 PCHIdentifierLookupTable *IdTable
2162 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002163 if (!IdTable ||
2164 Offset >= uint32_t(IdTable->getBuckets() - IdTable->getBase())) {
2165 // Turn off lookup into the on-disk hash table. We know that
2166 // this identifier is not there.
2167 if (IdTable)
2168 PP.getIdentifierTable().setExternalIdentifierLookup(0);
Douglas Gregor85c4a872009-04-25 21:04:17 +00002169
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002170 // All of the strings in the PCH file are preceded by a 16-bit
2171 // length. Extract that 16-bit length to avoid having to execute
2172 // strlen().
2173 const char *StrLenPtr = Str - 2;
2174 unsigned StrLen = (((unsigned) StrLenPtr[0])
2175 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2176 IdentifiersLoaded[ID - 1] = &Context.Idents.get(Str, Str + StrLen);
Douglas Gregor85c4a872009-04-25 21:04:17 +00002177
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002178 // Turn on lookup into the on-disk hash table, if we have an
2179 // on-disk hash table.
2180 if (IdTable)
2181 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2182 } else {
2183 // The identifier is a key in our on-disk hash table. Since we
2184 // know where the hash table entry starts, just read in this
2185 // (key, value) pair.
2186 PCHIdentifierLookupTrait Trait(const_cast<PCHReader &>(*this));
2187 const unsigned char *Pos = (const unsigned char *)Str - 4;
2188 std::pair<unsigned, unsigned> KeyDataLengths
2189 = Trait.ReadKeyDataLength(Pos);
Douglas Gregor85c4a872009-04-25 21:04:17 +00002190
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002191 PCHIdentifierLookupTrait::internal_key_type InternalKey
2192 = Trait.ReadKey(Pos, KeyDataLengths.first);
2193 Pos = (const unsigned char *)Str + KeyDataLengths.first;
2194 IdentifiersLoaded[ID - 1] = Trait.ReadData(InternalKey, Pos,
2195 KeyDataLengths.second);
2196 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002197 }
Chris Lattner29241862009-04-11 21:15:38 +00002198
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002199 return IdentifiersLoaded[ID - 1];
Douglas Gregorc34897d2009-04-09 22:27:44 +00002200}
2201
Steve Naroff9e84d782009-04-23 10:39:46 +00002202Selector PCHReader::DecodeSelector(unsigned ID) {
2203 if (ID == 0)
2204 return Selector();
2205
Douglas Gregor2d711832009-04-25 17:48:32 +00002206 if (!MethodPoolLookupTableData) {
Steve Naroff9e84d782009-04-23 10:39:46 +00002207 Error("No selector table in PCH file");
2208 return Selector();
2209 }
Douglas Gregor2d711832009-04-25 17:48:32 +00002210
2211 if (ID > TotalNumSelectors) {
Steve Naroff9e84d782009-04-23 10:39:46 +00002212 Error("Selector ID out of range");
2213 return Selector();
2214 }
Douglas Gregor2d711832009-04-25 17:48:32 +00002215
2216 unsigned Index = ID - 1;
2217 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2218 // Load this selector from the selector table.
2219 // FIXME: endianness portability issues with SelectorOffsets table
2220 PCHMethodPoolLookupTrait Trait(*this);
2221 SelectorsLoaded[Index]
2222 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2223 }
2224
2225 return SelectorsLoaded[Index];
Steve Naroff9e84d782009-04-23 10:39:46 +00002226}
2227
Douglas Gregorc34897d2009-04-09 22:27:44 +00002228DeclarationName
2229PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2230 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2231 switch (Kind) {
2232 case DeclarationName::Identifier:
2233 return DeclarationName(GetIdentifierInfo(Record, Idx));
2234
2235 case DeclarationName::ObjCZeroArgSelector:
2236 case DeclarationName::ObjCOneArgSelector:
2237 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff104956f2009-04-23 15:15:40 +00002238 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregorc34897d2009-04-09 22:27:44 +00002239
2240 case DeclarationName::CXXConstructorName:
2241 return Context.DeclarationNames.getCXXConstructorName(
2242 GetType(Record[Idx++]));
2243
2244 case DeclarationName::CXXDestructorName:
2245 return Context.DeclarationNames.getCXXDestructorName(
2246 GetType(Record[Idx++]));
2247
2248 case DeclarationName::CXXConversionFunctionName:
2249 return Context.DeclarationNames.getCXXConversionFunctionName(
2250 GetType(Record[Idx++]));
2251
2252 case DeclarationName::CXXOperatorName:
2253 return Context.DeclarationNames.getCXXOperatorName(
2254 (OverloadedOperatorKind)Record[Idx++]);
2255
2256 case DeclarationName::CXXUsingDirective:
2257 return DeclarationName::getUsingDirectiveName();
2258 }
2259
2260 // Required to silence GCC warning
2261 return DeclarationName();
2262}
Douglas Gregor179cfb12009-04-10 20:39:37 +00002263
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00002264/// \brief Read an integral value
2265llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2266 unsigned BitWidth = Record[Idx++];
2267 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2268 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2269 Idx += NumWords;
2270 return Result;
2271}
2272
2273/// \brief Read a signed integral value
2274llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2275 bool isUnsigned = Record[Idx++];
2276 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2277}
2278
Douglas Gregore2f37202009-04-14 21:55:33 +00002279/// \brief Read a floating-point value
2280llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00002281 return llvm::APFloat(ReadAPInt(Record, Idx));
2282}
2283
Douglas Gregor1c507882009-04-15 21:30:51 +00002284// \brief Read a string
2285std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2286 unsigned Len = Record[Idx++];
2287 std::string Result(&Record[Idx], &Record[Idx] + Len);
2288 Idx += Len;
2289 return Result;
2290}
2291
2292/// \brief Reads attributes from the current stream position.
2293Attr *PCHReader::ReadAttributes() {
2294 unsigned Code = Stream.ReadCode();
2295 assert(Code == llvm::bitc::UNABBREV_RECORD &&
2296 "Expected unabbreviated record"); (void)Code;
2297
2298 RecordData Record;
2299 unsigned Idx = 0;
2300 unsigned RecCode = Stream.ReadRecord(Code, Record);
2301 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
2302 (void)RecCode;
2303
2304#define SIMPLE_ATTR(Name) \
2305 case Attr::Name: \
2306 New = ::new (Context) Name##Attr(); \
2307 break
2308
2309#define STRING_ATTR(Name) \
2310 case Attr::Name: \
2311 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
2312 break
2313
2314#define UNSIGNED_ATTR(Name) \
2315 case Attr::Name: \
2316 New = ::new (Context) Name##Attr(Record[Idx++]); \
2317 break
2318
2319 Attr *Attrs = 0;
2320 while (Idx < Record.size()) {
2321 Attr *New = 0;
2322 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
2323 bool IsInherited = Record[Idx++];
2324
2325 switch (Kind) {
2326 STRING_ATTR(Alias);
2327 UNSIGNED_ATTR(Aligned);
2328 SIMPLE_ATTR(AlwaysInline);
2329 SIMPLE_ATTR(AnalyzerNoReturn);
2330 STRING_ATTR(Annotate);
2331 STRING_ATTR(AsmLabel);
2332
2333 case Attr::Blocks:
2334 New = ::new (Context) BlocksAttr(
2335 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
2336 break;
2337
2338 case Attr::Cleanup:
2339 New = ::new (Context) CleanupAttr(
2340 cast<FunctionDecl>(GetDecl(Record[Idx++])));
2341 break;
2342
2343 SIMPLE_ATTR(Const);
2344 UNSIGNED_ATTR(Constructor);
2345 SIMPLE_ATTR(DLLExport);
2346 SIMPLE_ATTR(DLLImport);
2347 SIMPLE_ATTR(Deprecated);
2348 UNSIGNED_ATTR(Destructor);
2349 SIMPLE_ATTR(FastCall);
2350
2351 case Attr::Format: {
2352 std::string Type = ReadString(Record, Idx);
2353 unsigned FormatIdx = Record[Idx++];
2354 unsigned FirstArg = Record[Idx++];
2355 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
2356 break;
2357 }
2358
Chris Lattner15ce6cc2009-04-20 19:12:28 +00002359 SIMPLE_ATTR(GNUInline);
Douglas Gregor1c507882009-04-15 21:30:51 +00002360
2361 case Attr::IBOutletKind:
2362 New = ::new (Context) IBOutletAttr();
2363 break;
2364
2365 SIMPLE_ATTR(NoReturn);
2366 SIMPLE_ATTR(NoThrow);
2367 SIMPLE_ATTR(Nodebug);
2368 SIMPLE_ATTR(Noinline);
2369
2370 case Attr::NonNull: {
2371 unsigned Size = Record[Idx++];
2372 llvm::SmallVector<unsigned, 16> ArgNums;
2373 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
2374 Idx += Size;
2375 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
2376 break;
2377 }
2378
2379 SIMPLE_ATTR(ObjCException);
2380 SIMPLE_ATTR(ObjCNSObject);
Ted Kremenekb98860c2009-04-25 00:17:17 +00002381 SIMPLE_ATTR(ObjCOwnershipRetain);
Ted Kremenekaa6e3182009-04-24 23:09:54 +00002382 SIMPLE_ATTR(ObjCOwnershipReturns);
Douglas Gregor1c507882009-04-15 21:30:51 +00002383 SIMPLE_ATTR(Overloadable);
2384 UNSIGNED_ATTR(Packed);
2385 SIMPLE_ATTR(Pure);
2386 UNSIGNED_ATTR(Regparm);
2387 STRING_ATTR(Section);
2388 SIMPLE_ATTR(StdCall);
2389 SIMPLE_ATTR(TransparentUnion);
2390 SIMPLE_ATTR(Unavailable);
2391 SIMPLE_ATTR(Unused);
2392 SIMPLE_ATTR(Used);
2393
2394 case Attr::Visibility:
2395 New = ::new (Context) VisibilityAttr(
2396 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
2397 break;
2398
2399 SIMPLE_ATTR(WarnUnusedResult);
2400 SIMPLE_ATTR(Weak);
2401 SIMPLE_ATTR(WeakImport);
2402 }
2403
2404 assert(New && "Unable to decode attribute?");
2405 New->setInherited(IsInherited);
2406 New->setNext(Attrs);
2407 Attrs = New;
2408 }
2409#undef UNSIGNED_ATTR
2410#undef STRING_ATTR
2411#undef SIMPLE_ATTR
2412
2413 // The list of attributes was built backwards. Reverse the list
2414 // before returning it.
2415 Attr *PrevAttr = 0, *NextAttr = 0;
2416 while (Attrs) {
2417 NextAttr = Attrs->getNext();
2418 Attrs->setNext(PrevAttr);
2419 PrevAttr = Attrs;
2420 Attrs = NextAttr;
2421 }
2422
2423 return PrevAttr;
2424}
2425
Douglas Gregor179cfb12009-04-10 20:39:37 +00002426DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002427 return Diag(SourceLocation(), DiagID);
2428}
2429
2430DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2431 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00002432 Context.getSourceManager()),
2433 DiagID);
2434}
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002435
Douglas Gregorc713da92009-04-21 22:25:48 +00002436/// \brief Retrieve the identifier table associated with the
2437/// preprocessor.
2438IdentifierTable &PCHReader::getIdentifierTable() {
2439 return PP.getIdentifierTable();
2440}
2441
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002442/// \brief Record that the given ID maps to the given switch-case
2443/// statement.
2444void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2445 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2446 SwitchCaseStmts[ID] = SC;
2447}
2448
2449/// \brief Retrieve the switch-case statement with the given ID.
2450SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2451 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2452 return SwitchCaseStmts[ID];
2453}
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002454
2455/// \brief Record that the given label statement has been
2456/// deserialized and has the given ID.
2457void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2458 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2459 "Deserialized label twice");
2460 LabelStmts[ID] = S;
2461
2462 // If we've already seen any goto statements that point to this
2463 // label, resolve them now.
2464 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2465 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2466 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2467 Goto->second->setLabel(S);
2468 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002469
2470 // If we've already seen any address-label statements that point to
2471 // this label, resolve them now.
2472 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2473 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2474 = UnresolvedAddrLabelExprs.equal_range(ID);
2475 for (AddrLabelIter AddrLabel = AddrLabels.first;
2476 AddrLabel != AddrLabels.second; ++AddrLabel)
2477 AddrLabel->second->setLabel(S);
2478 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002479}
2480
2481/// \brief Set the label of the given statement to the label
2482/// identified by ID.
2483///
2484/// Depending on the order in which the label and other statements
2485/// referencing that label occur, this operation may complete
2486/// immediately (updating the statement) or it may queue the
2487/// statement to be back-patched later.
2488void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2489 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2490 if (Label != LabelStmts.end()) {
2491 // We've already seen this label, so set the label of the goto and
2492 // we're done.
2493 S->setLabel(Label->second);
2494 } else {
2495 // We haven't seen this label yet, so add this goto to the set of
2496 // unresolved goto statements.
2497 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2498 }
2499}
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002500
2501/// \brief Set the label of the given expression to the label
2502/// identified by ID.
2503///
2504/// Depending on the order in which the label and other statements
2505/// referencing that label occur, this operation may complete
2506/// immediately (updating the statement) or it may queue the
2507/// statement to be back-patched later.
2508void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2509 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2510 if (Label != LabelStmts.end()) {
2511 // We've already seen this label, so set the label of the
2512 // label-address expression and we're done.
2513 S->setLabel(Label->second);
2514 } else {
2515 // We haven't seen this label yet, so add this label-address
2516 // expression to the set of unresolved label-address expressions.
2517 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2518 }
2519}