blob: d1f9b975e9270f9d9f88a030c798696a15e7f6d9 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- 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 PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
Sebastian Redl2767d882009-05-27 22:11:52 +0000165 Record.push_back(T->hasExceptionSpec());
166 Record.push_back(T->hasAnyExceptionSpec());
167 Record.push_back(T->getNumExceptions());
168 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
169 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_FUNCTION_PROTO;
171}
172
173void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
174 Writer.AddDeclRef(T->getDecl(), Record);
175 Code = pch::TYPE_TYPEDEF;
176}
177
178void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000180 Code = pch::TYPE_TYPEOF_EXPR;
181}
182
183void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
184 Writer.AddTypeRef(T->getUnderlyingType(), Record);
185 Code = pch::TYPE_TYPEOF;
186}
187
Anders Carlsson93ab5332009-06-24 19:06:50 +0000188void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
189 Writer.AddStmt(T->getUnderlyingExpr());
190 Code = pch::TYPE_DECLTYPE;
191}
192
Douglas Gregorc34897d2009-04-09 22:27:44 +0000193void PCHTypeWriter::VisitTagType(const TagType *T) {
194 Writer.AddDeclRef(T->getDecl(), Record);
195 assert(!T->isBeingDefined() &&
196 "Cannot serialize in the middle of a type definition");
197}
198
199void PCHTypeWriter::VisitRecordType(const RecordType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_RECORD;
202}
203
204void PCHTypeWriter::VisitEnumType(const EnumType *T) {
205 VisitTagType(T);
206 Code = pch::TYPE_ENUM;
207}
208
209void
210PCHTypeWriter::VisitTemplateSpecializationType(
211 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize template specialization types");
214}
215
216void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000217 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000218 assert(false && "Cannot serialize qualified name types");
219}
220
221void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
222 Writer.AddDeclRef(T->getDecl(), Record);
223 Code = pch::TYPE_OBJC_INTERFACE;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedInterfaceType(
228 const ObjCQualifiedInterfaceType *T) {
229 VisitObjCInterfaceType(T);
230 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000231 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
232 E = T->qual_end(); I != E; ++I)
233 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000234 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
235}
236
Steve Naroffc75c1a82009-06-17 22:40:22 +0000237void
238PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
239 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000240 Record.push_back(T->getNumProtocols());
Steve Naroffc75c1a82009-06-17 22:40:22 +0000241 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff83418522009-05-27 16:21:00 +0000242 E = T->qual_end(); I != E; ++I)
243 Writer.AddDeclRef(*I, Record);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000244 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000245}
246
Chris Lattner80f83c62009-04-22 05:57:30 +0000247//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000248// PCHWriter Implementation
249//===----------------------------------------------------------------------===//
250
Chris Lattner920673a2009-04-26 22:26:21 +0000251static void EmitBlockID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
257
258 // Emit the block name if present.
259 if (Name == 0 || Name[0] == 0) return;
260 Record.clear();
261 while (*Name)
262 Record.push_back(*Name++);
263 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
264}
265
266static void EmitRecordID(unsigned ID, const char *Name,
267 llvm::BitstreamWriter &Stream,
268 PCHWriter::RecordData &Record) {
269 Record.clear();
270 Record.push_back(ID);
271 while (*Name)
272 Record.push_back(*Name++);
273 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000274}
275
276static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
277 PCHWriter::RecordData &Record) {
278#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
279 RECORD(STMT_STOP);
280 RECORD(STMT_NULL_PTR);
281 RECORD(STMT_NULL);
282 RECORD(STMT_COMPOUND);
283 RECORD(STMT_CASE);
284 RECORD(STMT_DEFAULT);
285 RECORD(STMT_LABEL);
286 RECORD(STMT_IF);
287 RECORD(STMT_SWITCH);
288 RECORD(STMT_WHILE);
289 RECORD(STMT_DO);
290 RECORD(STMT_FOR);
291 RECORD(STMT_GOTO);
292 RECORD(STMT_INDIRECT_GOTO);
293 RECORD(STMT_CONTINUE);
294 RECORD(STMT_BREAK);
295 RECORD(STMT_RETURN);
296 RECORD(STMT_DECL);
297 RECORD(STMT_ASM);
298 RECORD(EXPR_PREDEFINED);
299 RECORD(EXPR_DECL_REF);
300 RECORD(EXPR_INTEGER_LITERAL);
301 RECORD(EXPR_FLOATING_LITERAL);
302 RECORD(EXPR_IMAGINARY_LITERAL);
303 RECORD(EXPR_STRING_LITERAL);
304 RECORD(EXPR_CHARACTER_LITERAL);
305 RECORD(EXPR_PAREN);
306 RECORD(EXPR_UNARY_OPERATOR);
307 RECORD(EXPR_SIZEOF_ALIGN_OF);
308 RECORD(EXPR_ARRAY_SUBSCRIPT);
309 RECORD(EXPR_CALL);
310 RECORD(EXPR_MEMBER);
311 RECORD(EXPR_BINARY_OPERATOR);
312 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
313 RECORD(EXPR_CONDITIONAL_OPERATOR);
314 RECORD(EXPR_IMPLICIT_CAST);
315 RECORD(EXPR_CSTYLE_CAST);
316 RECORD(EXPR_COMPOUND_LITERAL);
317 RECORD(EXPR_EXT_VECTOR_ELEMENT);
318 RECORD(EXPR_INIT_LIST);
319 RECORD(EXPR_DESIGNATED_INIT);
320 RECORD(EXPR_IMPLICIT_VALUE_INIT);
321 RECORD(EXPR_VA_ARG);
322 RECORD(EXPR_ADDR_LABEL);
323 RECORD(EXPR_STMT);
324 RECORD(EXPR_TYPES_COMPATIBLE);
325 RECORD(EXPR_CHOOSE);
326 RECORD(EXPR_GNU_NULL);
327 RECORD(EXPR_SHUFFLE_VECTOR);
328 RECORD(EXPR_BLOCK);
329 RECORD(EXPR_BLOCK_DECL_REF);
330 RECORD(EXPR_OBJC_STRING_LITERAL);
331 RECORD(EXPR_OBJC_ENCODE);
332 RECORD(EXPR_OBJC_SELECTOR_EXPR);
333 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
334 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
335 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
336 RECORD(EXPR_OBJC_KVC_REF_EXPR);
337 RECORD(EXPR_OBJC_MESSAGE_EXPR);
338 RECORD(EXPR_OBJC_SUPER_EXPR);
339 RECORD(STMT_OBJC_FOR_COLLECTION);
340 RECORD(STMT_OBJC_CATCH);
341 RECORD(STMT_OBJC_FINALLY);
342 RECORD(STMT_OBJC_AT_TRY);
343 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
344 RECORD(STMT_OBJC_AT_THROW);
345#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000346}
347
348void PCHWriter::WriteBlockInfoBlock() {
349 RecordData Record;
350 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
351
Chris Lattner880f3f72009-04-27 00:40:25 +0000352#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000353#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
354
355 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000356 BLOCK(PCH_BLOCK);
Zhongxing Xu29b61a52009-06-03 09:23:28 +0000357 RECORD(ORIGINAL_FILE_NAME);
Chris Lattner920673a2009-04-26 22:26:21 +0000358 RECORD(TYPE_OFFSET);
359 RECORD(DECL_OFFSET);
360 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000361 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000362 RECORD(IDENTIFIER_OFFSET);
363 RECORD(IDENTIFIER_TABLE);
364 RECORD(EXTERNAL_DEFINITIONS);
365 RECORD(SPECIAL_TYPES);
366 RECORD(STATISTICS);
367 RECORD(TENTATIVE_DEFINITIONS);
368 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
369 RECORD(SELECTOR_OFFSETS);
370 RECORD(METHOD_POOL);
371 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000372 RECORD(SOURCE_LOCATION_OFFSETS);
373 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000374 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000375 RECORD(EXT_VECTOR_DECLS);
376 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000377
Chris Lattner920673a2009-04-26 22:26:21 +0000378 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000379 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000380 RECORD(SM_SLOC_FILE_ENTRY);
381 RECORD(SM_SLOC_BUFFER_ENTRY);
382 RECORD(SM_SLOC_BUFFER_BLOB);
383 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
384 RECORD(SM_LINE_TABLE);
385 RECORD(SM_HEADER_FILE_INFO);
386
387 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000388 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000389 RECORD(PP_MACRO_OBJECT_LIKE);
390 RECORD(PP_MACRO_FUNCTION_LIKE);
391 RECORD(PP_TOKEN);
392
393 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000394 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000395 RECORD(TYPE_EXT_QUAL);
396 RECORD(TYPE_FIXED_WIDTH_INT);
397 RECORD(TYPE_COMPLEX);
398 RECORD(TYPE_POINTER);
399 RECORD(TYPE_BLOCK_POINTER);
400 RECORD(TYPE_LVALUE_REFERENCE);
401 RECORD(TYPE_RVALUE_REFERENCE);
402 RECORD(TYPE_MEMBER_POINTER);
403 RECORD(TYPE_CONSTANT_ARRAY);
404 RECORD(TYPE_INCOMPLETE_ARRAY);
405 RECORD(TYPE_VARIABLE_ARRAY);
406 RECORD(TYPE_VECTOR);
407 RECORD(TYPE_EXT_VECTOR);
408 RECORD(TYPE_FUNCTION_PROTO);
409 RECORD(TYPE_FUNCTION_NO_PROTO);
410 RECORD(TYPE_TYPEDEF);
411 RECORD(TYPE_TYPEOF_EXPR);
412 RECORD(TYPE_TYPEOF);
413 RECORD(TYPE_RECORD);
414 RECORD(TYPE_ENUM);
415 RECORD(TYPE_OBJC_INTERFACE);
416 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000417 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000418 // Statements and Exprs can occur in the Types block.
419 AddStmtsExprs(Stream, Record);
420
Chris Lattner920673a2009-04-26 22:26:21 +0000421 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000422 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000423 RECORD(DECL_ATTR);
424 RECORD(DECL_TRANSLATION_UNIT);
425 RECORD(DECL_TYPEDEF);
426 RECORD(DECL_ENUM);
427 RECORD(DECL_RECORD);
428 RECORD(DECL_ENUM_CONSTANT);
429 RECORD(DECL_FUNCTION);
430 RECORD(DECL_OBJC_METHOD);
431 RECORD(DECL_OBJC_INTERFACE);
432 RECORD(DECL_OBJC_PROTOCOL);
433 RECORD(DECL_OBJC_IVAR);
434 RECORD(DECL_OBJC_AT_DEFS_FIELD);
435 RECORD(DECL_OBJC_CLASS);
436 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
437 RECORD(DECL_OBJC_CATEGORY);
438 RECORD(DECL_OBJC_CATEGORY_IMPL);
439 RECORD(DECL_OBJC_IMPLEMENTATION);
440 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
441 RECORD(DECL_OBJC_PROPERTY);
442 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000443 RECORD(DECL_FIELD);
444 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000445 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000446 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000447 RECORD(DECL_ORIGINAL_PARM_VAR);
448 RECORD(DECL_FILE_SCOPE_ASM);
449 RECORD(DECL_BLOCK);
450 RECORD(DECL_CONTEXT_LEXICAL);
451 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000452 // Statements and Exprs can occur in the Decls block.
453 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000454#undef RECORD
455#undef BLOCK
456 Stream.ExitBlock();
457}
458
459
Douglas Gregorb7064742009-04-27 22:23:34 +0000460/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000461void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000462 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000463
464 // Original file name
465 SourceManager &SM = Context.getSourceManager();
466 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
467 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
468 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
469 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
470 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
471
472 llvm::sys::Path MainFilePath(MainFile->getName());
473 std::string MainFileName;
474
475 if (!MainFilePath.isAbsolute()) {
476 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
477 P.appendComponent(MainFilePath.toString());
478 MainFileName = P.toString();
479 } else {
480 MainFileName = MainFilePath.toString();
481 }
482
483 RecordData Record;
484 Record.push_back(pch::ORIGINAL_FILE_NAME);
485 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
486 MainFileName.size());
487 }
488
489 // Metadata
490 const TargetInfo &Target = Context.Target;
491 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
492 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
493 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
494 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
495 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
496 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
497 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
498 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000499
500 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000501 Record.push_back(pch::METADATA);
502 Record.push_back(pch::VERSION_MAJOR);
503 Record.push_back(pch::VERSION_MINOR);
504 Record.push_back(CLANG_VERSION_MAJOR);
505 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000506 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000507 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000508}
509
510/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000511void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
512 RecordData Record;
513 Record.push_back(LangOpts.Trigraphs);
514 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
515 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
516 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
517 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
518 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
519 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
520 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
521 Record.push_back(LangOpts.C99); // C99 Support
522 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
523 Record.push_back(LangOpts.CPlusPlus); // C++ Support
524 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000525 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
526
527 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
528 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
529 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
530
531 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000532 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
533 Record.push_back(LangOpts.LaxVectorConversions);
534 Record.push_back(LangOpts.Exceptions); // Support exception handling.
535
536 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
537 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
538 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
539
Chris Lattnercd4da472009-04-27 07:35:58 +0000540 // Whether static initializers are protected by locks.
541 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000542 Record.push_back(LangOpts.Blocks); // block extension to C
543 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
544 // they are unused.
545 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
546 // (modulo the platform support).
547
548 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
549 // signed integer arithmetic overflows.
550
551 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
552 // may be ripped out at any time.
553
554 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
555 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
556 // defined.
557 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
558 // opposed to __DYNAMIC__).
559 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
560
561 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
562 // used (instead of C99 semantics).
563 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000564 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
565 // be enabled.
Eli Friedmand9389be2009-06-05 07:05:05 +0000566 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
567 // unsigned type
Douglas Gregor179cfb12009-04-10 20:39:37 +0000568 Record.push_back(LangOpts.getGCMode());
569 Record.push_back(LangOpts.getVisibilityMode());
570 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000571 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000572}
573
Douglas Gregorab1cef72009-04-10 03:52:48 +0000574//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000575// stat cache Serialization
576//===----------------------------------------------------------------------===//
577
578namespace {
579// Trait used for the on-disk hash table of stat cache results.
580class VISIBILITY_HIDDEN PCHStatCacheTrait {
581public:
582 typedef const char * key_type;
583 typedef key_type key_type_ref;
584
585 typedef std::pair<int, struct stat> data_type;
586 typedef const data_type& data_type_ref;
587
588 static unsigned ComputeHash(const char *path) {
589 return BernsteinHash(path);
590 }
591
592 std::pair<unsigned,unsigned>
593 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
594 data_type_ref Data) {
595 unsigned StrLen = strlen(path);
596 clang::io::Emit16(Out, StrLen);
597 unsigned DataLen = 1; // result value
598 if (Data.first == 0)
599 DataLen += 4 + 4 + 2 + 8 + 8;
600 clang::io::Emit8(Out, DataLen);
601 return std::make_pair(StrLen + 1, DataLen);
602 }
603
604 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
605 Out.write(path, KeyLen);
606 }
607
608 void EmitData(llvm::raw_ostream& Out, key_type_ref,
609 data_type_ref Data, unsigned DataLen) {
610 using namespace clang::io;
611 uint64_t Start = Out.tell(); (void)Start;
612
613 // Result of stat()
614 Emit8(Out, Data.first? 1 : 0);
615
616 if (Data.first == 0) {
617 Emit32(Out, (uint32_t) Data.second.st_ino);
618 Emit32(Out, (uint32_t) Data.second.st_dev);
619 Emit16(Out, (uint16_t) Data.second.st_mode);
620 Emit64(Out, (uint64_t) Data.second.st_mtime);
621 Emit64(Out, (uint64_t) Data.second.st_size);
622 }
623
624 assert(Out.tell() - Start == DataLen && "Wrong data length");
625 }
626};
627} // end anonymous namespace
628
629/// \brief Write the stat() system call cache to the PCH file.
630void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
631 // Build the on-disk hash table containing information about every
632 // stat() call.
633 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
634 unsigned NumStatEntries = 0;
635 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
636 StatEnd = StatCalls.end();
637 Stat != StatEnd; ++Stat, ++NumStatEntries)
638 Generator.insert(Stat->first(), Stat->second);
639
640 // Create the on-disk hash table in a buffer.
641 llvm::SmallVector<char, 4096> StatCacheData;
642 uint32_t BucketOffset;
643 {
644 llvm::raw_svector_ostream Out(StatCacheData);
645 // Make sure that no bucket is at offset 0
646 clang::io::Emit32(Out, 0);
647 BucketOffset = Generator.Emit(Out);
648 }
649
650 // Create a blob abbreviation
651 using namespace llvm;
652 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
653 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
655 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
657 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
658
659 // Write the stat cache
660 RecordData Record;
661 Record.push_back(pch::STAT_CACHE);
662 Record.push_back(BucketOffset);
663 Record.push_back(NumStatEntries);
664 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
665 &StatCacheData.front(),
666 StatCacheData.size());
667}
668
669//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000670// Source Manager Serialization
671//===----------------------------------------------------------------------===//
672
673/// \brief Create an abbreviation for the SLocEntry that refers to a
674/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000675static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000676 using namespace llvm;
677 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
678 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000684 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000685}
686
687/// \brief Create an abbreviation for the SLocEntry that refers to a
688/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000689static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000690 using namespace llvm;
691 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
692 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
693 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
694 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000698 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000699}
700
701/// \brief Create an abbreviation for the SLocEntry that refers to a
702/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000703static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000704 using namespace llvm;
705 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
706 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000708 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000709}
710
711/// \brief Create an abbreviation for the SLocEntry that refers to an
712/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000713static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000714 using namespace llvm;
715 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
716 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
717 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
718 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000722 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000723}
724
725/// \brief Writes the block containing the serialized form of the
726/// source manager.
727///
728/// TODO: We should probably use an on-disk hash table (stored in a
729/// blob), indexed based on the file name, so that we only create
730/// entries for files that we actually need. In the common case (no
731/// errors), we probably won't have to create file entries for any of
732/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000733void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
734 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000735 RecordData Record;
736
Chris Lattner84b04f12009-04-10 17:16:57 +0000737 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000738 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000739
740 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000741 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
742 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
743 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
744 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000745
Douglas Gregor635f97f2009-04-13 16:31:14 +0000746 // Write the line table.
747 if (SourceMgr.hasLineTable()) {
748 LineTableInfo &LineTable = SourceMgr.getLineTable();
749
750 // Emit the file names
751 Record.push_back(LineTable.getNumFilenames());
752 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
753 // Emit the file name
754 const char *Filename = LineTable.getFilename(I);
755 unsigned FilenameLen = Filename? strlen(Filename) : 0;
756 Record.push_back(FilenameLen);
757 if (FilenameLen)
758 Record.insert(Record.end(), Filename, Filename + FilenameLen);
759 }
760
761 // Emit the line entries
762 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
763 L != LEnd; ++L) {
764 // Emit the file ID
765 Record.push_back(L->first);
766
767 // Emit the line entries
768 Record.push_back(L->second.size());
769 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
770 LEEnd = L->second.end();
771 LE != LEEnd; ++LE) {
772 Record.push_back(LE->FileOffset);
773 Record.push_back(LE->LineNo);
774 Record.push_back(LE->FilenameID);
775 Record.push_back((unsigned)LE->FileKind);
776 Record.push_back(LE->IncludeOffset);
777 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000778 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000779 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000780 }
781
Douglas Gregor32e231c2009-04-27 06:38:32 +0000782 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000783 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000784 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000785 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
786 E = HS.header_file_end();
787 I != E; ++I) {
788 Record.push_back(I->isImport);
789 Record.push_back(I->DirInfo);
790 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000791 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000792 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
793 Record.clear();
794 }
795
Douglas Gregor32e231c2009-04-27 06:38:32 +0000796 // Write out the source location entry table. We skip the first
797 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000798 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000799 RecordData PreloadSLocs;
800 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
801 for (SourceManager::sloc_entry_iterator
802 SLoc = SourceMgr.sloc_entry_begin() + 1,
803 SLocEnd = SourceMgr.sloc_entry_end();
804 SLoc != SLocEnd; ++SLoc) {
805 // Record the offset of this source-location entry.
806 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
807
808 // Figure out which record code to use.
809 unsigned Code;
810 if (SLoc->isFile()) {
811 if (SLoc->getFile().getContentCache()->Entry)
812 Code = pch::SM_SLOC_FILE_ENTRY;
813 else
814 Code = pch::SM_SLOC_BUFFER_ENTRY;
815 } else
816 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
817 Record.clear();
818 Record.push_back(Code);
819
820 Record.push_back(SLoc->getOffset());
821 if (SLoc->isFile()) {
822 const SrcMgr::FileInfo &File = SLoc->getFile();
823 Record.push_back(File.getIncludeLoc().getRawEncoding());
824 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
825 Record.push_back(File.hasLineDirectives());
826
827 const SrcMgr::ContentCache *Content = File.getContentCache();
828 if (Content->Entry) {
829 // The source location entry is a file. The blob associated
830 // with this entry is the file name.
831 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
832 Content->Entry->getName(),
833 strlen(Content->Entry->getName()));
834
835 // FIXME: For now, preload all file source locations, so that
836 // we get the appropriate File entries in the reader. This is
837 // a temporary measure.
838 PreloadSLocs.push_back(SLocEntryOffsets.size());
839 } else {
840 // The source location entry is a buffer. The blob associated
841 // with this entry contains the contents of the buffer.
842
843 // We add one to the size so that we capture the trailing NULL
844 // that is required by llvm::MemoryBuffer::getMemBuffer (on
845 // the reader side).
846 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
847 const char *Name = Buffer->getBufferIdentifier();
848 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
849 Record.clear();
850 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
851 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
852 Buffer->getBufferStart(),
853 Buffer->getBufferSize() + 1);
854
855 if (strcmp(Name, "<built-in>") == 0)
856 PreloadSLocs.push_back(SLocEntryOffsets.size());
857 }
858 } else {
859 // The source location entry is an instantiation.
860 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
861 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
862 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
863 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
864
865 // Compute the token length for this macro expansion.
866 unsigned NextOffset = SourceMgr.getNextOffset();
867 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
868 if (++NextSLoc != SLocEnd)
869 NextOffset = NextSLoc->getOffset();
870 Record.push_back(NextOffset - SLoc->getOffset() - 1);
871 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
872 }
873 }
874
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000875 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000876
877 if (SLocEntryOffsets.empty())
878 return;
879
880 // Write the source-location offsets table into the PCH block. This
881 // table is used for lazily loading source-location information.
882 using namespace llvm;
883 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
884 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
888 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
889
890 Record.clear();
891 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
892 Record.push_back(SLocEntryOffsets.size());
893 Record.push_back(SourceMgr.getNextOffset());
894 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
895 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000896 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000897
898 // Write the source location entry preloads array, telling the PCH
899 // reader which source locations entries it should load eagerly.
900 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000901}
902
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000903//===----------------------------------------------------------------------===//
904// Preprocessor Serialization
905//===----------------------------------------------------------------------===//
906
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000907/// \brief Writes the block containing the serialized form of the
908/// preprocessor.
909///
Chris Lattner850eabd2009-04-10 18:08:30 +0000910void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000911 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000912
Chris Lattner4b21c202009-04-13 01:29:17 +0000913 // If the preprocessor __COUNTER__ value has been bumped, remember it.
914 if (PP.getCounterValue() != 0) {
915 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000916 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000917 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000918 }
919
920 // Enter the preprocessor block.
921 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000922
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000923 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
924 // FIXME: use diagnostics subsystem for localization etc.
925 if (PP.SawDateOrTime())
926 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
927
Chris Lattner1b094952009-04-10 18:00:12 +0000928 // Loop over all the macro definitions that are live at the end of the file,
929 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000930 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
931 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000932 // FIXME: This emits macros in hash table order, we should do it in a stable
933 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000934 MacroInfo *MI = I->second;
935
936 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
937 // been redefined by the header (in which case they are not isBuiltinMacro).
938 if (MI->isBuiltinMacro())
939 continue;
940
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000941 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000942 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000943 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000944 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
945 Record.push_back(MI->isUsed());
946
947 unsigned Code;
948 if (MI->isObjectLike()) {
949 Code = pch::PP_MACRO_OBJECT_LIKE;
950 } else {
951 Code = pch::PP_MACRO_FUNCTION_LIKE;
952
953 Record.push_back(MI->isC99Varargs());
954 Record.push_back(MI->isGNUVarargs());
955 Record.push_back(MI->getNumArgs());
956 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
957 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000958 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000959 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000960 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000961 Record.clear();
962
Chris Lattner850eabd2009-04-10 18:08:30 +0000963 // Emit the tokens array.
964 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
965 // Note that we know that the preprocessor does not have any annotation
966 // tokens in it because they are created by the parser, and thus can't be
967 // in a macro definition.
968 const Token &Tok = MI->getReplacementToken(TokNo);
969
970 Record.push_back(Tok.getLocation().getRawEncoding());
971 Record.push_back(Tok.getLength());
972
Chris Lattner850eabd2009-04-10 18:08:30 +0000973 // FIXME: When reading literal tokens, reconstruct the literal pointer if
974 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000975 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000976
977 // FIXME: Should translate token kind to a stable encoding.
978 Record.push_back(Tok.getKind());
979 // FIXME: Should translate token flags to a stable encoding.
980 Record.push_back(Tok.getFlags());
981
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000982 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000983 Record.clear();
984 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000985 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000986 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000987 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000988}
989
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000990//===----------------------------------------------------------------------===//
991// Type Serialization
992//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000993
Douglas Gregorc34897d2009-04-09 22:27:44 +0000994/// \brief Write the representation of a type to the PCH stream.
995void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000996 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000997 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000998 ID = NextTypeID++;
999
1000 // Record the offset for this type.
1001 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001002 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001003 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1004 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001005 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001006 }
1007
1008 RecordData Record;
1009
1010 // Emit the type's representation.
1011 PCHTypeWriter W(*this, Record);
1012 switch (T->getTypeClass()) {
1013 // For all of the concrete, non-dependent types, call the
1014 // appropriate visitor function.
1015#define TYPE(Class, Base) \
1016 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1017#define ABSTRACT_TYPE(Class, Base)
1018#define DEPENDENT_TYPE(Class, Base)
1019#include "clang/AST/TypeNodes.def"
1020
1021 // For all of the dependent type nodes (which only occur in C++
1022 // templates), produce an error.
1023#define TYPE(Class, Base)
1024#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1025#include "clang/AST/TypeNodes.def"
1026 assert(false && "Cannot serialize dependent type nodes");
1027 break;
1028 }
1029
1030 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001031 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001032
1033 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001034 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001035}
1036
1037/// \brief Write a block containing all of the types.
1038void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001039 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001040 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001041
Douglas Gregore43f0972009-04-26 03:49:13 +00001042 // Emit all of the types that need to be emitted (so far).
1043 while (!TypesToEmit.empty()) {
1044 const Type *T = TypesToEmit.front();
1045 TypesToEmit.pop();
1046 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1047 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001048 }
1049
1050 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001051 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001052}
1053
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001054//===----------------------------------------------------------------------===//
1055// Declaration Serialization
1056//===----------------------------------------------------------------------===//
1057
Douglas Gregorc34897d2009-04-09 22:27:44 +00001058/// \brief Write the block containing all of the declaration IDs
1059/// lexically declared within the given DeclContext.
1060///
1061/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1062/// bistream, or 0 if no block was written.
1063uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1064 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001065 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001066 return 0;
1067
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001068 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001069 RecordData Record;
1070 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1071 DEnd = DC->decls_end(Context);
1072 D != DEnd; ++D)
1073 AddDeclRef(*D, Record);
1074
Douglas Gregoraf136d92009-04-22 22:34:57 +00001075 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001076 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001077 return Offset;
1078}
1079
1080/// \brief Write the block containing all of the declaration IDs
1081/// visible from the given DeclContext.
1082///
1083/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1084/// bistream, or 0 if no block was written.
1085uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1086 DeclContext *DC) {
1087 if (DC->getPrimaryContext() != DC)
1088 return 0;
1089
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001090 // Since there is no name lookup into functions or methods, and we
1091 // perform name lookup for the translation unit via the
1092 // IdentifierInfo chains, don't bother to build a
1093 // visible-declarations table for these entities.
1094 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001095 return 0;
1096
Douglas Gregorc34897d2009-04-09 22:27:44 +00001097 // Force the DeclContext to build a its name-lookup table.
1098 DC->lookup(Context, DeclarationName());
1099
1100 // Serialize the contents of the mapping used for lookup. Note that,
1101 // although we have two very different code paths, the serialized
1102 // representation is the same for both cases: a declaration name,
1103 // followed by a size, followed by references to the visible
1104 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001105 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001106 RecordData Record;
1107 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001108 if (!Map)
1109 return 0;
1110
Douglas Gregorc34897d2009-04-09 22:27:44 +00001111 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1112 D != DEnd; ++D) {
1113 AddDeclarationName(D->first, Record);
1114 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1115 Record.push_back(Result.second - Result.first);
1116 for(; Result.first != Result.second; ++Result.first)
1117 AddDeclRef(*Result.first, Record);
1118 }
1119
1120 if (Record.size() == 0)
1121 return 0;
1122
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001123 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001124 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001125 return Offset;
1126}
1127
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001128//===----------------------------------------------------------------------===//
1129// Global Method Pool and Selector Serialization
1130//===----------------------------------------------------------------------===//
1131
Douglas Gregorff9a6092009-04-20 20:36:09 +00001132namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001133// Trait used for the on-disk hash table used in the method pool.
1134class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1135 PCHWriter &Writer;
1136
1137public:
1138 typedef Selector key_type;
1139 typedef key_type key_type_ref;
1140
1141 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1142 typedef const data_type& data_type_ref;
1143
1144 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1145
1146 static unsigned ComputeHash(Selector Sel) {
1147 unsigned N = Sel.getNumArgs();
1148 if (N == 0)
1149 ++N;
1150 unsigned R = 5381;
1151 for (unsigned I = 0; I != N; ++I)
1152 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1153 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1154 return R;
1155 }
1156
1157 std::pair<unsigned,unsigned>
1158 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1159 data_type_ref Methods) {
1160 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1161 clang::io::Emit16(Out, KeyLen);
1162 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1163 for (const ObjCMethodList *Method = &Methods.first; Method;
1164 Method = Method->Next)
1165 if (Method->Method)
1166 DataLen += 4;
1167 for (const ObjCMethodList *Method = &Methods.second; Method;
1168 Method = Method->Next)
1169 if (Method->Method)
1170 DataLen += 4;
1171 clang::io::Emit16(Out, DataLen);
1172 return std::make_pair(KeyLen, DataLen);
1173 }
1174
Douglas Gregor2d711832009-04-25 17:48:32 +00001175 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1176 uint64_t Start = Out.tell();
1177 assert((Start >> 32) == 0 && "Selector key offset too large");
1178 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001179 unsigned N = Sel.getNumArgs();
1180 clang::io::Emit16(Out, N);
1181 if (N == 0)
1182 N = 1;
1183 for (unsigned I = 0; I != N; ++I)
1184 clang::io::Emit32(Out,
1185 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1186 }
1187
1188 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001189 data_type_ref Methods, unsigned DataLen) {
1190 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001191 unsigned NumInstanceMethods = 0;
1192 for (const ObjCMethodList *Method = &Methods.first; Method;
1193 Method = Method->Next)
1194 if (Method->Method)
1195 ++NumInstanceMethods;
1196
1197 unsigned NumFactoryMethods = 0;
1198 for (const ObjCMethodList *Method = &Methods.second; Method;
1199 Method = Method->Next)
1200 if (Method->Method)
1201 ++NumFactoryMethods;
1202
1203 clang::io::Emit16(Out, NumInstanceMethods);
1204 clang::io::Emit16(Out, NumFactoryMethods);
1205 for (const ObjCMethodList *Method = &Methods.first; Method;
1206 Method = Method->Next)
1207 if (Method->Method)
1208 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001209 for (const ObjCMethodList *Method = &Methods.second; Method;
1210 Method = Method->Next)
1211 if (Method->Method)
1212 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001213
1214 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001215 }
1216};
1217} // end anonymous namespace
1218
1219/// \brief Write the method pool into the PCH file.
1220///
1221/// The method pool contains both instance and factory methods, stored
1222/// in an on-disk hash table indexed by the selector.
1223void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1224 using namespace llvm;
1225
1226 // Create and write out the blob that contains the instance and
1227 // factor method pools.
1228 bool Empty = true;
1229 {
1230 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1231
1232 // Create the on-disk hash table representation. Start by
1233 // iterating through the instance method pool.
1234 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001235 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001236 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1237 Instance = SemaRef.InstanceMethodPool.begin(),
1238 InstanceEnd = SemaRef.InstanceMethodPool.end();
1239 Instance != InstanceEnd; ++Instance) {
1240 // Check whether there is a factory method with the same
1241 // selector.
1242 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1243 = SemaRef.FactoryMethodPool.find(Instance->first);
1244
1245 if (Factory == SemaRef.FactoryMethodPool.end())
1246 Generator.insert(Instance->first,
1247 std::make_pair(Instance->second,
1248 ObjCMethodList()));
1249 else
1250 Generator.insert(Instance->first,
1251 std::make_pair(Instance->second, Factory->second));
1252
Douglas Gregor2d711832009-04-25 17:48:32 +00001253 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001254 Empty = false;
1255 }
1256
1257 // Now iterate through the factory method pool, to pick up any
1258 // selectors that weren't already in the instance method pool.
1259 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1260 Factory = SemaRef.FactoryMethodPool.begin(),
1261 FactoryEnd = SemaRef.FactoryMethodPool.end();
1262 Factory != FactoryEnd; ++Factory) {
1263 // Check whether there is an instance method with the same
1264 // selector. If so, there is no work to do here.
1265 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1266 = SemaRef.InstanceMethodPool.find(Factory->first);
1267
Douglas Gregor2d711832009-04-25 17:48:32 +00001268 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001269 Generator.insert(Factory->first,
1270 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001271 ++NumSelectorsInMethodPool;
1272 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001273
1274 Empty = false;
1275 }
1276
Douglas Gregor2d711832009-04-25 17:48:32 +00001277 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001278 return;
1279
1280 // Create the on-disk hash table in a buffer.
1281 llvm::SmallVector<char, 4096> MethodPool;
1282 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001283 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001284 {
1285 PCHMethodPoolTrait Trait(*this);
1286 llvm::raw_svector_ostream Out(MethodPool);
1287 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001288 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001289 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001290
1291 // For every selector that we have seen but which was not
1292 // written into the hash table, write the selector itself and
1293 // record it's offset.
1294 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1295 if (SelectorOffsets[I] == 0)
1296 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001297 }
1298
1299 // Create a blob abbreviation
1300 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1301 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1305 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1306
Douglas Gregor2d711832009-04-25 17:48:32 +00001307 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001308 RecordData Record;
1309 Record.push_back(pch::METHOD_POOL);
1310 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001311 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001312 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1313 &MethodPool.front(),
1314 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001315
1316 // Create a blob abbreviation for the selector table offsets.
1317 Abbrev = new BitCodeAbbrev();
1318 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1319 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1320 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1321 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1322
1323 // Write the selector offsets table.
1324 Record.clear();
1325 Record.push_back(pch::SELECTOR_OFFSETS);
1326 Record.push_back(SelectorOffsets.size());
1327 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1328 (const char *)&SelectorOffsets.front(),
1329 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001330 }
1331}
1332
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001333//===----------------------------------------------------------------------===//
1334// Identifier Table Serialization
1335//===----------------------------------------------------------------------===//
1336
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001337namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001338class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1339 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001340 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001341
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001342 /// \brief Determines whether this is an "interesting" identifier
1343 /// that needs a full IdentifierInfo structure written into the hash
1344 /// table.
1345 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1346 return II->isPoisoned() ||
1347 II->isExtensionToken() ||
1348 II->hasMacroDefinition() ||
1349 II->getObjCOrBuiltinID() ||
1350 II->getFETokenInfo<void>();
1351 }
1352
Douglas Gregorff9a6092009-04-20 20:36:09 +00001353public:
1354 typedef const IdentifierInfo* key_type;
1355 typedef key_type key_type_ref;
1356
1357 typedef pch::IdentID data_type;
1358 typedef data_type data_type_ref;
1359
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001360 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1361 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001362
1363 static unsigned ComputeHash(const IdentifierInfo* II) {
1364 return clang::BernsteinHash(II->getName());
1365 }
1366
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001367 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001368 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1369 pch::IdentID ID) {
1370 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001371 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1372 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001373 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001374 if (II->hasMacroDefinition() &&
1375 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001376 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001377 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1378 DEnd = IdentifierResolver::end();
1379 D != DEnd; ++D)
1380 DataLen += sizeof(pch::DeclID);
1381 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001382 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001383 // We emit the key length after the data length so that every
1384 // string is preceded by a 16-bit length. This matches the PTH
1385 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001386 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001387 return std::make_pair(KeyLen, DataLen);
1388 }
1389
1390 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1391 unsigned KeyLen) {
1392 // Record the location of the key data. This is used when generating
1393 // the mapping from persistent IDs to strings.
1394 Writer.SetIdentifierOffset(II, Out.tell());
1395 Out.write(II->getName(), KeyLen);
1396 }
1397
1398 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1399 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001400 if (!isInterestingIdentifier(II)) {
1401 clang::io::Emit32(Out, ID << 1);
1402 return;
1403 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001404
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001405 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001406 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001407 bool hasMacroDefinition =
1408 II->hasMacroDefinition() &&
1409 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001410 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001411 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001412 Bits = (Bits << 1) | II->isExtensionToken();
1413 Bits = (Bits << 1) | II->isPoisoned();
1414 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001415 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001416
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001417 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001418 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001419
Douglas Gregorc713da92009-04-21 22:25:48 +00001420 // Emit the declaration IDs in reverse order, because the
1421 // IdentifierResolver provides the declarations as they would be
1422 // visible (e.g., the function "stat" would come before the struct
1423 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1424 // adds declarations to the end of the list (so we need to see the
1425 // struct "status" before the function "status").
1426 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1427 IdentifierResolver::end());
1428 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1429 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001430 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001431 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001432 }
1433};
1434} // end anonymous namespace
1435
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001436/// \brief Write the identifier table into the PCH file.
1437///
1438/// The identifier table consists of a blob containing string data
1439/// (the actual identifiers themselves) and a separate "offsets" index
1440/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001441void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001442 using namespace llvm;
1443
1444 // Create and write out the blob that contains the identifier
1445 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001446 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001447 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1448
Douglas Gregor91137812009-04-28 20:33:11 +00001449 // Look for any identifiers that were named while processing the
1450 // headers, but are otherwise not needed. We add these to the hash
1451 // table to enable checking of the predefines buffer in the case
1452 // where the user adds new macro definitions when building the PCH
1453 // file.
1454 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1455 IDEnd = PP.getIdentifierTable().end();
1456 ID != IDEnd; ++ID)
1457 getIdentifierRef(ID->second);
1458
Douglas Gregorff9a6092009-04-20 20:36:09 +00001459 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001460 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001461 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1462 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1463 ID != IDEnd; ++ID) {
1464 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001465 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001466 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001467
Douglas Gregorff9a6092009-04-20 20:36:09 +00001468 // Create the on-disk hash table in a buffer.
1469 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001470 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001471 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001472 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001473 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001474 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001475 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001476 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001477 }
1478
1479 // Create a blob abbreviation
1480 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1481 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001484 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001485
1486 // Write the identifier table
1487 RecordData Record;
1488 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001489 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001490 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1491 &IdentifierTable.front(),
1492 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001493 }
1494
1495 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001496 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1497 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1499 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1500 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1501
1502 RecordData Record;
1503 Record.push_back(pch::IDENTIFIER_OFFSET);
1504 Record.push_back(IdentifierOffsets.size());
1505 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1506 (const char *)&IdentifierOffsets.front(),
1507 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001508}
1509
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001510//===----------------------------------------------------------------------===//
1511// General Serialization Routines
1512//===----------------------------------------------------------------------===//
1513
Douglas Gregor1c507882009-04-15 21:30:51 +00001514/// \brief Write a record containing the given attributes.
1515void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1516 RecordData Record;
1517 for (; Attr; Attr = Attr->getNext()) {
1518 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1519 Record.push_back(Attr->isInherited());
1520 switch (Attr->getKind()) {
1521 case Attr::Alias:
1522 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1523 break;
1524
1525 case Attr::Aligned:
1526 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1527 break;
1528
1529 case Attr::AlwaysInline:
1530 break;
1531
1532 case Attr::AnalyzerNoReturn:
1533 break;
1534
1535 case Attr::Annotate:
1536 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1537 break;
1538
1539 case Attr::AsmLabel:
1540 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1541 break;
1542
1543 case Attr::Blocks:
1544 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1545 break;
1546
1547 case Attr::Cleanup:
1548 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1549 break;
1550
1551 case Attr::Const:
1552 break;
1553
1554 case Attr::Constructor:
1555 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1556 break;
1557
1558 case Attr::DLLExport:
1559 case Attr::DLLImport:
1560 case Attr::Deprecated:
1561 break;
1562
1563 case Attr::Destructor:
1564 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1565 break;
1566
1567 case Attr::FastCall:
1568 break;
1569
1570 case Attr::Format: {
1571 const FormatAttr *Format = cast<FormatAttr>(Attr);
1572 AddString(Format->getType(), Record);
1573 Record.push_back(Format->getFormatIdx());
1574 Record.push_back(Format->getFirstArg());
1575 break;
1576 }
1577
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001578 case Attr::FormatArg: {
1579 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1580 Record.push_back(Format->getFormatIdx());
1581 break;
1582 }
1583
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001584 case Attr::Sentinel : {
1585 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1586 Record.push_back(Sentinel->getSentinel());
1587 Record.push_back(Sentinel->getNullPos());
1588 break;
1589 }
1590
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001591 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001592 case Attr::IBOutletKind:
1593 case Attr::NoReturn:
1594 case Attr::NoThrow:
1595 case Attr::Nodebug:
1596 case Attr::Noinline:
1597 break;
1598
1599 case Attr::NonNull: {
1600 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1601 Record.push_back(NonNull->size());
1602 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1603 break;
1604 }
1605
1606 case Attr::ObjCException:
1607 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001608 case Attr::CFReturnsRetained:
1609 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001610 case Attr::Overloadable:
1611 break;
1612
1613 case Attr::Packed:
1614 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1615 break;
1616
1617 case Attr::Pure:
1618 break;
1619
1620 case Attr::Regparm:
1621 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1622 break;
1623
1624 case Attr::Section:
1625 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1626 break;
1627
1628 case Attr::StdCall:
1629 case Attr::TransparentUnion:
1630 case Attr::Unavailable:
1631 case Attr::Unused:
1632 case Attr::Used:
1633 break;
1634
1635 case Attr::Visibility:
1636 // FIXME: stable encoding
1637 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1638 break;
1639
1640 case Attr::WarnUnusedResult:
1641 case Attr::Weak:
1642 case Attr::WeakImport:
1643 break;
1644 }
1645 }
1646
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001647 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001648}
1649
1650void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1651 Record.push_back(Str.size());
1652 Record.insert(Record.end(), Str.begin(), Str.end());
1653}
1654
Douglas Gregorff9a6092009-04-20 20:36:09 +00001655/// \brief Note that the identifier II occurs at the given offset
1656/// within the identifier table.
1657void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001658 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001659}
1660
Douglas Gregor2d711832009-04-25 17:48:32 +00001661/// \brief Note that the selector Sel occurs at the given offset
1662/// within the method pool/selector table.
1663void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1664 unsigned ID = SelectorIDs[Sel];
1665 assert(ID && "Unknown selector");
1666 SelectorOffsets[ID - 1] = Offset;
1667}
1668
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001669PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001670 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001671 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1672 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001673
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001674void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001675 using namespace llvm;
1676
Douglas Gregor87887da2009-04-20 15:53:59 +00001677 ASTContext &Context = SemaRef.Context;
1678 Preprocessor &PP = SemaRef.PP;
1679
Douglas Gregorc34897d2009-04-09 22:27:44 +00001680 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001681 Stream.Emit((unsigned)'C', 8);
1682 Stream.Emit((unsigned)'P', 8);
1683 Stream.Emit((unsigned)'C', 8);
1684 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001685
1686 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001687
1688 // The translation unit is the first declaration we'll emit.
1689 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1690 DeclsToEmit.push(Context.getTranslationUnitDecl());
1691
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001692 // Make sure that we emit IdentifierInfos (and any attached
1693 // declarations) for builtins.
1694 {
1695 IdentifierTable &Table = PP.getIdentifierTable();
1696 llvm::SmallVector<const char *, 32> BuiltinNames;
1697 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1698 Context.getLangOptions().NoBuiltin);
1699 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1700 getIdentifierRef(&Table.get(BuiltinNames[I]));
1701 }
1702
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001703 // Build a record containing all of the tentative definitions in
1704 // this header file. Generally, this record will be empty.
1705 RecordData TentativeDefinitions;
1706 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1707 TD = SemaRef.TentativeDefinitions.begin(),
1708 TDEnd = SemaRef.TentativeDefinitions.end();
1709 TD != TDEnd; ++TD)
1710 AddDeclRef(TD->second, TentativeDefinitions);
1711
Douglas Gregor062d9482009-04-22 22:18:58 +00001712 // Build a record containing all of the locally-scoped external
1713 // declarations in this header file. Generally, this record will be
1714 // empty.
1715 RecordData LocallyScopedExternalDecls;
1716 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1717 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1718 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1719 TD != TDEnd; ++TD)
1720 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1721
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001722 // Build a record containing all of the ext_vector declarations.
1723 RecordData ExtVectorDecls;
1724 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1725 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1726
1727 // Build a record containing all of the Objective-C category
1728 // implementations.
1729 RecordData ObjCCategoryImpls;
1730 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1731 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1732
Douglas Gregorc34897d2009-04-09 22:27:44 +00001733 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001734 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001735 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001736 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001737 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001738 if (StatCalls)
1739 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001740 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001741 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001742
1743 // Keep writing types and declarations until all types and
1744 // declarations have been written.
1745 do {
1746 if (!DeclsToEmit.empty())
1747 WriteDeclsBlock(Context);
1748 if (!TypesToEmit.empty())
1749 WriteTypesBlock(Context);
1750 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1751
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001752 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001753 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001754
1755 // Write the type offsets array
1756 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1757 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1760 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1761 Record.clear();
1762 Record.push_back(pch::TYPE_OFFSET);
1763 Record.push_back(TypeOffsets.size());
1764 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1765 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001766 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001767
1768 // Write the declaration offsets array
1769 Abbrev = new BitCodeAbbrev();
1770 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1773 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1774 Record.clear();
1775 Record.push_back(pch::DECL_OFFSET);
1776 Record.push_back(DeclOffsets.size());
1777 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1778 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001779 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001780
1781 // Write the record of special types.
1782 Record.clear();
1783 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001784 AddTypeRef(Context.getObjCIdType(), Record);
1785 AddTypeRef(Context.getObjCSelType(), Record);
1786 AddTypeRef(Context.getObjCProtoType(), Record);
1787 AddTypeRef(Context.getObjCClassType(), Record);
1788 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1789 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001790 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1791
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001792 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001793 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001794 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001795
1796 // Write the record containing tentative definitions.
1797 if (!TentativeDefinitions.empty())
1798 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001799
1800 // Write the record containing locally-scoped external definitions.
1801 if (!LocallyScopedExternalDecls.empty())
1802 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1803 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001804
1805 // Write the record containing ext_vector type names.
1806 if (!ExtVectorDecls.empty())
1807 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1808
1809 // Write the record containing Objective-C category implementations.
1810 if (!ObjCCategoryImpls.empty())
1811 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001812
1813 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001814 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001815 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001816 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001817 Record.push_back(NumLexicalDeclContexts);
1818 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001819 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001820 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001821}
1822
1823void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1824 Record.push_back(Loc.getRawEncoding());
1825}
1826
1827void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1828 Record.push_back(Value.getBitWidth());
1829 unsigned N = Value.getNumWords();
1830 const uint64_t* Words = Value.getRawData();
1831 for (unsigned I = 0; I != N; ++I)
1832 Record.push_back(Words[I]);
1833}
1834
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001835void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1836 Record.push_back(Value.isUnsigned());
1837 AddAPInt(Value, Record);
1838}
1839
Douglas Gregore2f37202009-04-14 21:55:33 +00001840void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1841 AddAPInt(Value.bitcastToAPInt(), Record);
1842}
1843
Douglas Gregorc34897d2009-04-09 22:27:44 +00001844void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001845 Record.push_back(getIdentifierRef(II));
1846}
1847
1848pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1849 if (II == 0)
1850 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001851
1852 pch::IdentID &ID = IdentifierIDs[II];
1853 if (ID == 0)
1854 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001855 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001856}
1857
Steve Naroff9e84d782009-04-23 10:39:46 +00001858void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1859 if (SelRef.getAsOpaquePtr() == 0) {
1860 Record.push_back(0);
1861 return;
1862 }
1863
1864 pch::SelectorID &SID = SelectorIDs[SelRef];
1865 if (SID == 0) {
1866 SID = SelectorIDs.size();
1867 SelVector.push_back(SelRef);
1868 }
1869 Record.push_back(SID);
1870}
1871
Douglas Gregorc34897d2009-04-09 22:27:44 +00001872void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1873 if (T.isNull()) {
1874 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1875 return;
1876 }
1877
1878 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001879 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001880 switch (BT->getKind()) {
1881 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1882 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1883 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1884 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1885 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1886 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1887 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1888 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001889 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001890 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1891 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1892 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1893 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1894 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1895 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1896 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001897 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001898 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1899 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1900 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001901 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001902 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1903 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1904 }
1905
1906 Record.push_back((ID << 3) | T.getCVRQualifiers());
1907 return;
1908 }
1909
Douglas Gregorac8f2802009-04-10 17:25:41 +00001910 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001911 if (ID == 0) {
1912 // We haven't seen this type before. Assign it a new ID and put it
1913 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001914 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001915 TypesToEmit.push(T.getTypePtr());
1916 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001917
1918 // Encode the type qualifiers in the type reference.
1919 Record.push_back((ID << 3) | T.getCVRQualifiers());
1920}
1921
1922void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1923 if (D == 0) {
1924 Record.push_back(0);
1925 return;
1926 }
1927
Douglas Gregorac8f2802009-04-10 17:25:41 +00001928 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001929 if (ID == 0) {
1930 // We haven't seen this declaration before. Give it a new ID and
1931 // enqueue it in the list of declarations to emit.
1932 ID = DeclIDs.size();
1933 DeclsToEmit.push(const_cast<Decl *>(D));
1934 }
1935
1936 Record.push_back(ID);
1937}
1938
Douglas Gregorff9a6092009-04-20 20:36:09 +00001939pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1940 if (D == 0)
1941 return 0;
1942
1943 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1944 return DeclIDs[D];
1945}
1946
Douglas Gregorc34897d2009-04-09 22:27:44 +00001947void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001948 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001949 Record.push_back(Name.getNameKind());
1950 switch (Name.getNameKind()) {
1951 case DeclarationName::Identifier:
1952 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1953 break;
1954
1955 case DeclarationName::ObjCZeroArgSelector:
1956 case DeclarationName::ObjCOneArgSelector:
1957 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001958 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001959 break;
1960
1961 case DeclarationName::CXXConstructorName:
1962 case DeclarationName::CXXDestructorName:
1963 case DeclarationName::CXXConversionFunctionName:
1964 AddTypeRef(Name.getCXXNameType(), Record);
1965 break;
1966
1967 case DeclarationName::CXXOperatorName:
1968 Record.push_back(Name.getCXXOverloadedOperator());
1969 break;
1970
1971 case DeclarationName::CXXUsingDirective:
1972 // No extra data to emit
1973 break;
1974 }
1975}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001976