blob: fee2137314bd8035df57cb7e4378ccc24e42a3da [file] [log] [blame]
Douglas Gregor2cf26342009-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 Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregor3251ceb2009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregorb64c1932009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000043
Douglas Gregor2cf26342009-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 Gregor4fed3f42009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-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
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000127void PCHTypeWriter
128::VisitConstantArrayWithExprType(const ConstantArrayWithExprType *T) {
129 VisitArrayType(T);
130 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
131 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
132 Writer.AddAPInt(T->getSize(), Record);
133 Writer.AddStmt(T->getSizeExpr());
134 Code = pch::TYPE_CONSTANT_ARRAY_WITH_EXPR;
135}
136
137void PCHTypeWriter
138::VisitConstantArrayWithoutExprType(const ConstantArrayWithoutExprType *T) {
139 VisitArrayType(T);
140 Writer.AddAPInt(T->getSize(), Record);
141 Code = pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR;
142}
143
Douglas Gregor2cf26342009-04-09 22:27:44 +0000144void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
145 VisitArrayType(T);
146 Code = pch::TYPE_INCOMPLETE_ARRAY;
147}
148
149void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
150 VisitArrayType(T);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000151 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
152 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000153 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000154 Code = pch::TYPE_VARIABLE_ARRAY;
155}
156
157void PCHTypeWriter::VisitVectorType(const VectorType *T) {
158 Writer.AddTypeRef(T->getElementType(), Record);
159 Record.push_back(T->getNumElements());
160 Code = pch::TYPE_VECTOR;
161}
162
163void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
164 VisitVectorType(T);
165 Code = pch::TYPE_EXT_VECTOR;
166}
167
168void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
169 Writer.AddTypeRef(T->getResultType(), Record);
170}
171
172void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
173 VisitFunctionType(T);
174 Code = pch::TYPE_FUNCTION_NO_PROTO;
175}
176
177void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
178 VisitFunctionType(T);
179 Record.push_back(T->getNumArgs());
180 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
181 Writer.AddTypeRef(T->getArgType(I), Record);
182 Record.push_back(T->isVariadic());
183 Record.push_back(T->getTypeQuals());
Sebastian Redl465226e2009-05-27 22:11:52 +0000184 Record.push_back(T->hasExceptionSpec());
185 Record.push_back(T->hasAnyExceptionSpec());
186 Record.push_back(T->getNumExceptions());
187 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
188 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000189 Code = pch::TYPE_FUNCTION_PROTO;
190}
191
192void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
193 Writer.AddDeclRef(T->getDecl(), Record);
194 Code = pch::TYPE_TYPEDEF;
195}
196
197void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000198 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000199 Code = pch::TYPE_TYPEOF_EXPR;
200}
201
202void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
203 Writer.AddTypeRef(T->getUnderlyingType(), Record);
204 Code = pch::TYPE_TYPEOF;
205}
206
Anders Carlsson395b4752009-06-24 19:06:50 +0000207void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
208 Writer.AddStmt(T->getUnderlyingExpr());
209 Code = pch::TYPE_DECLTYPE;
210}
211
Douglas Gregor2cf26342009-04-09 22:27:44 +0000212void PCHTypeWriter::VisitTagType(const TagType *T) {
213 Writer.AddDeclRef(T->getDecl(), Record);
214 assert(!T->isBeingDefined() &&
215 "Cannot serialize in the middle of a type definition");
216}
217
218void PCHTypeWriter::VisitRecordType(const RecordType *T) {
219 VisitTagType(T);
220 Code = pch::TYPE_RECORD;
221}
222
223void PCHTypeWriter::VisitEnumType(const EnumType *T) {
224 VisitTagType(T);
225 Code = pch::TYPE_ENUM;
226}
227
228void
229PCHTypeWriter::VisitTemplateSpecializationType(
230 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000231 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000232 assert(false && "Cannot serialize template specialization types");
233}
234
235void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000236 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000237 assert(false && "Cannot serialize qualified name types");
238}
239
240void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
241 Writer.AddDeclRef(T->getDecl(), Record);
242 Code = pch::TYPE_OBJC_INTERFACE;
243}
244
245void
246PCHTypeWriter::VisitObjCQualifiedInterfaceType(
247 const ObjCQualifiedInterfaceType *T) {
248 VisitObjCInterfaceType(T);
249 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000250 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
251 E = T->qual_end(); I != E; ++I)
252 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000253 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
254}
255
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000256void
257PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
258 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000259 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000260 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000261 E = T->qual_end(); I != E; ++I)
262 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000263 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000264}
265
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000266//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000267// PCHWriter Implementation
268//===----------------------------------------------------------------------===//
269
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000270static void EmitBlockID(unsigned ID, const char *Name,
271 llvm::BitstreamWriter &Stream,
272 PCHWriter::RecordData &Record) {
273 Record.clear();
274 Record.push_back(ID);
275 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
276
277 // Emit the block name if present.
278 if (Name == 0 || Name[0] == 0) return;
279 Record.clear();
280 while (*Name)
281 Record.push_back(*Name++);
282 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
283}
284
285static void EmitRecordID(unsigned ID, const char *Name,
286 llvm::BitstreamWriter &Stream,
287 PCHWriter::RecordData &Record) {
288 Record.clear();
289 Record.push_back(ID);
290 while (*Name)
291 Record.push_back(*Name++);
292 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000293}
294
295static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
296 PCHWriter::RecordData &Record) {
297#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
298 RECORD(STMT_STOP);
299 RECORD(STMT_NULL_PTR);
300 RECORD(STMT_NULL);
301 RECORD(STMT_COMPOUND);
302 RECORD(STMT_CASE);
303 RECORD(STMT_DEFAULT);
304 RECORD(STMT_LABEL);
305 RECORD(STMT_IF);
306 RECORD(STMT_SWITCH);
307 RECORD(STMT_WHILE);
308 RECORD(STMT_DO);
309 RECORD(STMT_FOR);
310 RECORD(STMT_GOTO);
311 RECORD(STMT_INDIRECT_GOTO);
312 RECORD(STMT_CONTINUE);
313 RECORD(STMT_BREAK);
314 RECORD(STMT_RETURN);
315 RECORD(STMT_DECL);
316 RECORD(STMT_ASM);
317 RECORD(EXPR_PREDEFINED);
318 RECORD(EXPR_DECL_REF);
319 RECORD(EXPR_INTEGER_LITERAL);
320 RECORD(EXPR_FLOATING_LITERAL);
321 RECORD(EXPR_IMAGINARY_LITERAL);
322 RECORD(EXPR_STRING_LITERAL);
323 RECORD(EXPR_CHARACTER_LITERAL);
324 RECORD(EXPR_PAREN);
325 RECORD(EXPR_UNARY_OPERATOR);
326 RECORD(EXPR_SIZEOF_ALIGN_OF);
327 RECORD(EXPR_ARRAY_SUBSCRIPT);
328 RECORD(EXPR_CALL);
329 RECORD(EXPR_MEMBER);
330 RECORD(EXPR_BINARY_OPERATOR);
331 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
332 RECORD(EXPR_CONDITIONAL_OPERATOR);
333 RECORD(EXPR_IMPLICIT_CAST);
334 RECORD(EXPR_CSTYLE_CAST);
335 RECORD(EXPR_COMPOUND_LITERAL);
336 RECORD(EXPR_EXT_VECTOR_ELEMENT);
337 RECORD(EXPR_INIT_LIST);
338 RECORD(EXPR_DESIGNATED_INIT);
339 RECORD(EXPR_IMPLICIT_VALUE_INIT);
340 RECORD(EXPR_VA_ARG);
341 RECORD(EXPR_ADDR_LABEL);
342 RECORD(EXPR_STMT);
343 RECORD(EXPR_TYPES_COMPATIBLE);
344 RECORD(EXPR_CHOOSE);
345 RECORD(EXPR_GNU_NULL);
346 RECORD(EXPR_SHUFFLE_VECTOR);
347 RECORD(EXPR_BLOCK);
348 RECORD(EXPR_BLOCK_DECL_REF);
349 RECORD(EXPR_OBJC_STRING_LITERAL);
350 RECORD(EXPR_OBJC_ENCODE);
351 RECORD(EXPR_OBJC_SELECTOR_EXPR);
352 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
353 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
354 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
355 RECORD(EXPR_OBJC_KVC_REF_EXPR);
356 RECORD(EXPR_OBJC_MESSAGE_EXPR);
357 RECORD(EXPR_OBJC_SUPER_EXPR);
358 RECORD(STMT_OBJC_FOR_COLLECTION);
359 RECORD(STMT_OBJC_CATCH);
360 RECORD(STMT_OBJC_FINALLY);
361 RECORD(STMT_OBJC_AT_TRY);
362 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
363 RECORD(STMT_OBJC_AT_THROW);
364#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000365}
366
367void PCHWriter::WriteBlockInfoBlock() {
368 RecordData Record;
369 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
370
Chris Lattner2f4efd12009-04-27 00:40:25 +0000371#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000372#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
373
374 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000375 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000376 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000377 RECORD(TYPE_OFFSET);
378 RECORD(DECL_OFFSET);
379 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000380 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000381 RECORD(IDENTIFIER_OFFSET);
382 RECORD(IDENTIFIER_TABLE);
383 RECORD(EXTERNAL_DEFINITIONS);
384 RECORD(SPECIAL_TYPES);
385 RECORD(STATISTICS);
386 RECORD(TENTATIVE_DEFINITIONS);
387 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
388 RECORD(SELECTOR_OFFSETS);
389 RECORD(METHOD_POOL);
390 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000391 RECORD(SOURCE_LOCATION_OFFSETS);
392 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000393 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000394 RECORD(EXT_VECTOR_DECLS);
395 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000396 RECORD(COMMENT_RANGES);
397
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000398 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000399 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000400 RECORD(SM_SLOC_FILE_ENTRY);
401 RECORD(SM_SLOC_BUFFER_ENTRY);
402 RECORD(SM_SLOC_BUFFER_BLOB);
403 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
404 RECORD(SM_LINE_TABLE);
405 RECORD(SM_HEADER_FILE_INFO);
406
407 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000408 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000409 RECORD(PP_MACRO_OBJECT_LIKE);
410 RECORD(PP_MACRO_FUNCTION_LIKE);
411 RECORD(PP_TOKEN);
412
413 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000414 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000415 RECORD(TYPE_EXT_QUAL);
416 RECORD(TYPE_FIXED_WIDTH_INT);
417 RECORD(TYPE_COMPLEX);
418 RECORD(TYPE_POINTER);
419 RECORD(TYPE_BLOCK_POINTER);
420 RECORD(TYPE_LVALUE_REFERENCE);
421 RECORD(TYPE_RVALUE_REFERENCE);
422 RECORD(TYPE_MEMBER_POINTER);
423 RECORD(TYPE_CONSTANT_ARRAY);
424 RECORD(TYPE_INCOMPLETE_ARRAY);
425 RECORD(TYPE_VARIABLE_ARRAY);
426 RECORD(TYPE_VECTOR);
427 RECORD(TYPE_EXT_VECTOR);
428 RECORD(TYPE_FUNCTION_PROTO);
429 RECORD(TYPE_FUNCTION_NO_PROTO);
430 RECORD(TYPE_TYPEDEF);
431 RECORD(TYPE_TYPEOF_EXPR);
432 RECORD(TYPE_TYPEOF);
433 RECORD(TYPE_RECORD);
434 RECORD(TYPE_ENUM);
435 RECORD(TYPE_OBJC_INTERFACE);
436 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000437 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000438 // Statements and Exprs can occur in the Types block.
439 AddStmtsExprs(Stream, Record);
440
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000441 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000442 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000443 RECORD(DECL_ATTR);
444 RECORD(DECL_TRANSLATION_UNIT);
445 RECORD(DECL_TYPEDEF);
446 RECORD(DECL_ENUM);
447 RECORD(DECL_RECORD);
448 RECORD(DECL_ENUM_CONSTANT);
449 RECORD(DECL_FUNCTION);
450 RECORD(DECL_OBJC_METHOD);
451 RECORD(DECL_OBJC_INTERFACE);
452 RECORD(DECL_OBJC_PROTOCOL);
453 RECORD(DECL_OBJC_IVAR);
454 RECORD(DECL_OBJC_AT_DEFS_FIELD);
455 RECORD(DECL_OBJC_CLASS);
456 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
457 RECORD(DECL_OBJC_CATEGORY);
458 RECORD(DECL_OBJC_CATEGORY_IMPL);
459 RECORD(DECL_OBJC_IMPLEMENTATION);
460 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
461 RECORD(DECL_OBJC_PROPERTY);
462 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000463 RECORD(DECL_FIELD);
464 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000465 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000466 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000467 RECORD(DECL_ORIGINAL_PARM_VAR);
468 RECORD(DECL_FILE_SCOPE_ASM);
469 RECORD(DECL_BLOCK);
470 RECORD(DECL_CONTEXT_LEXICAL);
471 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000472 // Statements and Exprs can occur in the Decls block.
473 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000474#undef RECORD
475#undef BLOCK
476 Stream.ExitBlock();
477}
478
479
Douglas Gregorab41e632009-04-27 22:23:34 +0000480/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregorb64c1932009-05-12 01:31:05 +0000481void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000482 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000483
484 // Original file name
485 SourceManager &SM = Context.getSourceManager();
486 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
487 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
488 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
489 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
490 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
491
492 llvm::sys::Path MainFilePath(MainFile->getName());
493 std::string MainFileName;
494
495 if (!MainFilePath.isAbsolute()) {
496 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
497 P.appendComponent(MainFilePath.toString());
498 MainFileName = P.toString();
499 } else {
500 MainFileName = MainFilePath.toString();
501 }
502
503 RecordData Record;
504 Record.push_back(pch::ORIGINAL_FILE_NAME);
505 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
506 MainFileName.size());
507 }
508
509 // Metadata
510 const TargetInfo &Target = Context.Target;
511 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
512 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
513 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
514 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
515 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
516 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
517 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
518 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000519
520 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000521 Record.push_back(pch::METADATA);
522 Record.push_back(pch::VERSION_MAJOR);
523 Record.push_back(pch::VERSION_MINOR);
524 Record.push_back(CLANG_VERSION_MAJOR);
525 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000526 const char *Triple = Target.getTargetTriple();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000527 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000528}
529
530/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000531void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
532 RecordData Record;
533 Record.push_back(LangOpts.Trigraphs);
534 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
535 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
536 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
537 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
538 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
539 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
540 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
541 Record.push_back(LangOpts.C99); // C99 Support
542 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
543 Record.push_back(LangOpts.CPlusPlus); // C++ Support
544 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000545 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
546
547 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
548 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
549 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
550
551 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000552 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
553 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000554 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000555 Record.push_back(LangOpts.Exceptions); // Support exception handling.
556
557 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
558 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
559 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
560
Chris Lattnerea5ce472009-04-27 07:35:58 +0000561 // Whether static initializers are protected by locks.
562 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000563 Record.push_back(LangOpts.Blocks); // block extension to C
564 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
565 // they are unused.
566 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
567 // (modulo the platform support).
568
569 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
570 // signed integer arithmetic overflows.
571
572 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
573 // may be ripped out at any time.
574
575 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
576 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
577 // defined.
578 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
579 // opposed to __DYNAMIC__).
580 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
581
582 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
583 // used (instead of C99 semantics).
584 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000585 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
586 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000587 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
588 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000589 Record.push_back(LangOpts.getGCMode());
590 Record.push_back(LangOpts.getVisibilityMode());
591 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000592 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000593 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000594}
595
Douglas Gregor14f79002009-04-10 03:52:48 +0000596//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000597// stat cache Serialization
598//===----------------------------------------------------------------------===//
599
600namespace {
601// Trait used for the on-disk hash table of stat cache results.
602class VISIBILITY_HIDDEN PCHStatCacheTrait {
603public:
604 typedef const char * key_type;
605 typedef key_type key_type_ref;
606
607 typedef std::pair<int, struct stat> data_type;
608 typedef const data_type& data_type_ref;
609
610 static unsigned ComputeHash(const char *path) {
611 return BernsteinHash(path);
612 }
613
614 std::pair<unsigned,unsigned>
615 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
616 data_type_ref Data) {
617 unsigned StrLen = strlen(path);
618 clang::io::Emit16(Out, StrLen);
619 unsigned DataLen = 1; // result value
620 if (Data.first == 0)
621 DataLen += 4 + 4 + 2 + 8 + 8;
622 clang::io::Emit8(Out, DataLen);
623 return std::make_pair(StrLen + 1, DataLen);
624 }
625
626 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
627 Out.write(path, KeyLen);
628 }
629
630 void EmitData(llvm::raw_ostream& Out, key_type_ref,
631 data_type_ref Data, unsigned DataLen) {
632 using namespace clang::io;
633 uint64_t Start = Out.tell(); (void)Start;
634
635 // Result of stat()
636 Emit8(Out, Data.first? 1 : 0);
637
638 if (Data.first == 0) {
639 Emit32(Out, (uint32_t) Data.second.st_ino);
640 Emit32(Out, (uint32_t) Data.second.st_dev);
641 Emit16(Out, (uint16_t) Data.second.st_mode);
642 Emit64(Out, (uint64_t) Data.second.st_mtime);
643 Emit64(Out, (uint64_t) Data.second.st_size);
644 }
645
646 assert(Out.tell() - Start == DataLen && "Wrong data length");
647 }
648};
649} // end anonymous namespace
650
651/// \brief Write the stat() system call cache to the PCH file.
652void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
653 // Build the on-disk hash table containing information about every
654 // stat() call.
655 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
656 unsigned NumStatEntries = 0;
657 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
658 StatEnd = StatCalls.end();
659 Stat != StatEnd; ++Stat, ++NumStatEntries)
660 Generator.insert(Stat->first(), Stat->second);
661
662 // Create the on-disk hash table in a buffer.
663 llvm::SmallVector<char, 4096> StatCacheData;
664 uint32_t BucketOffset;
665 {
666 llvm::raw_svector_ostream Out(StatCacheData);
667 // Make sure that no bucket is at offset 0
668 clang::io::Emit32(Out, 0);
669 BucketOffset = Generator.Emit(Out);
670 }
671
672 // Create a blob abbreviation
673 using namespace llvm;
674 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
675 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
679 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
680
681 // Write the stat cache
682 RecordData Record;
683 Record.push_back(pch::STAT_CACHE);
684 Record.push_back(BucketOffset);
685 Record.push_back(NumStatEntries);
686 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
687 &StatCacheData.front(),
688 StatCacheData.size());
689}
690
691//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000692// Source Manager Serialization
693//===----------------------------------------------------------------------===//
694
695/// \brief Create an abbreviation for the SLocEntry that refers to a
696/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000697static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000698 using namespace llvm;
699 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
700 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
701 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000706 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000707}
708
709/// \brief Create an abbreviation for the SLocEntry that refers to a
710/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000711static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000712 using namespace llvm;
713 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
714 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
717 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
718 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000720 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000721}
722
723/// \brief Create an abbreviation for the SLocEntry that refers to a
724/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000725static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000726 using namespace llvm;
727 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
728 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
729 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000730 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000731}
732
733/// \brief Create an abbreviation for the SLocEntry that refers to an
734/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000735static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000736 using namespace llvm;
737 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
738 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
739 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
740 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000744 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000745}
746
747/// \brief Writes the block containing the serialized form of the
748/// source manager.
749///
750/// TODO: We should probably use an on-disk hash table (stored in a
751/// blob), indexed based on the file name, so that we only create
752/// entries for files that we actually need. In the common case (no
753/// errors), we probably won't have to create file entries for any of
754/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000755void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
756 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000757 RecordData Record;
758
Chris Lattnerf04ad692009-04-10 17:16:57 +0000759 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000760 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000761
762 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000763 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
764 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
765 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
766 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000767
Douglas Gregorbd945002009-04-13 16:31:14 +0000768 // Write the line table.
769 if (SourceMgr.hasLineTable()) {
770 LineTableInfo &LineTable = SourceMgr.getLineTable();
771
772 // Emit the file names
773 Record.push_back(LineTable.getNumFilenames());
774 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
775 // Emit the file name
776 const char *Filename = LineTable.getFilename(I);
777 unsigned FilenameLen = Filename? strlen(Filename) : 0;
778 Record.push_back(FilenameLen);
779 if (FilenameLen)
780 Record.insert(Record.end(), Filename, Filename + FilenameLen);
781 }
782
783 // Emit the line entries
784 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
785 L != LEnd; ++L) {
786 // Emit the file ID
787 Record.push_back(L->first);
788
789 // Emit the line entries
790 Record.push_back(L->second.size());
791 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
792 LEEnd = L->second.end();
793 LE != LEEnd; ++LE) {
794 Record.push_back(LE->FileOffset);
795 Record.push_back(LE->LineNo);
796 Record.push_back(LE->FilenameID);
797 Record.push_back((unsigned)LE->FileKind);
798 Record.push_back(LE->IncludeOffset);
799 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000800 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000801 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000802 }
803
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000804 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000805 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000806 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000807 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
808 E = HS.header_file_end();
809 I != E; ++I) {
810 Record.push_back(I->isImport);
811 Record.push_back(I->DirInfo);
812 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000813 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000814 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
815 Record.clear();
816 }
817
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000818 // Write out the source location entry table. We skip the first
819 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000820 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000821 RecordData PreloadSLocs;
822 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
823 for (SourceManager::sloc_entry_iterator
824 SLoc = SourceMgr.sloc_entry_begin() + 1,
825 SLocEnd = SourceMgr.sloc_entry_end();
826 SLoc != SLocEnd; ++SLoc) {
827 // Record the offset of this source-location entry.
828 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
829
830 // Figure out which record code to use.
831 unsigned Code;
832 if (SLoc->isFile()) {
833 if (SLoc->getFile().getContentCache()->Entry)
834 Code = pch::SM_SLOC_FILE_ENTRY;
835 else
836 Code = pch::SM_SLOC_BUFFER_ENTRY;
837 } else
838 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
839 Record.clear();
840 Record.push_back(Code);
841
842 Record.push_back(SLoc->getOffset());
843 if (SLoc->isFile()) {
844 const SrcMgr::FileInfo &File = SLoc->getFile();
845 Record.push_back(File.getIncludeLoc().getRawEncoding());
846 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
847 Record.push_back(File.hasLineDirectives());
848
849 const SrcMgr::ContentCache *Content = File.getContentCache();
850 if (Content->Entry) {
851 // The source location entry is a file. The blob associated
852 // with this entry is the file name.
853 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
854 Content->Entry->getName(),
855 strlen(Content->Entry->getName()));
856
857 // FIXME: For now, preload all file source locations, so that
858 // we get the appropriate File entries in the reader. This is
859 // a temporary measure.
860 PreloadSLocs.push_back(SLocEntryOffsets.size());
861 } else {
862 // The source location entry is a buffer. The blob associated
863 // with this entry contains the contents of the buffer.
864
865 // We add one to the size so that we capture the trailing NULL
866 // that is required by llvm::MemoryBuffer::getMemBuffer (on
867 // the reader side).
868 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
869 const char *Name = Buffer->getBufferIdentifier();
870 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
871 Record.clear();
872 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
873 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
874 Buffer->getBufferStart(),
875 Buffer->getBufferSize() + 1);
876
877 if (strcmp(Name, "<built-in>") == 0)
878 PreloadSLocs.push_back(SLocEntryOffsets.size());
879 }
880 } else {
881 // The source location entry is an instantiation.
882 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
883 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
884 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
885 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
886
887 // Compute the token length for this macro expansion.
888 unsigned NextOffset = SourceMgr.getNextOffset();
889 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
890 if (++NextSLoc != SLocEnd)
891 NextOffset = NextSLoc->getOffset();
892 Record.push_back(NextOffset - SLoc->getOffset() - 1);
893 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
894 }
895 }
896
Douglas Gregorc9490c02009-04-16 22:23:12 +0000897 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000898
899 if (SLocEntryOffsets.empty())
900 return;
901
902 // Write the source-location offsets table into the PCH block. This
903 // table is used for lazily loading source-location information.
904 using namespace llvm;
905 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
906 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
907 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
908 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
910 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
911
912 Record.clear();
913 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
914 Record.push_back(SLocEntryOffsets.size());
915 Record.push_back(SourceMgr.getNextOffset());
916 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
917 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000918 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000919
920 // Write the source location entry preloads array, telling the PCH
921 // reader which source locations entries it should load eagerly.
922 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000923}
924
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000925//===----------------------------------------------------------------------===//
926// Preprocessor Serialization
927//===----------------------------------------------------------------------===//
928
Chris Lattner0b1fb982009-04-10 17:15:23 +0000929/// \brief Writes the block containing the serialized form of the
930/// preprocessor.
931///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000932void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000933 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000934
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000935 // If the preprocessor __COUNTER__ value has been bumped, remember it.
936 if (PP.getCounterValue() != 0) {
937 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000938 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000939 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000940 }
941
942 // Enter the preprocessor block.
943 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000944
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000945 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
946 // FIXME: use diagnostics subsystem for localization etc.
947 if (PP.SawDateOrTime())
948 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
949
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000950 // Loop over all the macro definitions that are live at the end of the file,
951 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000952 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
953 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000954 // FIXME: This emits macros in hash table order, we should do it in a stable
955 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000956 MacroInfo *MI = I->second;
957
958 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
959 // been redefined by the header (in which case they are not isBuiltinMacro).
960 if (MI->isBuiltinMacro())
961 continue;
962
Douglas Gregor37e26842009-04-21 23:56:24 +0000963 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000964 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000965 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000966 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
967 Record.push_back(MI->isUsed());
968
969 unsigned Code;
970 if (MI->isObjectLike()) {
971 Code = pch::PP_MACRO_OBJECT_LIKE;
972 } else {
973 Code = pch::PP_MACRO_FUNCTION_LIKE;
974
975 Record.push_back(MI->isC99Varargs());
976 Record.push_back(MI->isGNUVarargs());
977 Record.push_back(MI->getNumArgs());
978 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
979 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000980 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000981 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000982 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000983 Record.clear();
984
Chris Lattnerdf961c22009-04-10 18:08:30 +0000985 // Emit the tokens array.
986 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
987 // Note that we know that the preprocessor does not have any annotation
988 // tokens in it because they are created by the parser, and thus can't be
989 // in a macro definition.
990 const Token &Tok = MI->getReplacementToken(TokNo);
991
992 Record.push_back(Tok.getLocation().getRawEncoding());
993 Record.push_back(Tok.getLength());
994
Chris Lattnerdf961c22009-04-10 18:08:30 +0000995 // FIXME: When reading literal tokens, reconstruct the literal pointer if
996 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000997 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000998
999 // FIXME: Should translate token kind to a stable encoding.
1000 Record.push_back(Tok.getKind());
1001 // FIXME: Should translate token flags to a stable encoding.
1002 Record.push_back(Tok.getFlags());
1003
Douglas Gregorc9490c02009-04-16 22:23:12 +00001004 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001005 Record.clear();
1006 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001007 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001008 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001009 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001010}
1011
Douglas Gregor2e222532009-07-02 17:08:52 +00001012void PCHWriter::WriteComments(ASTContext &Context) {
1013 using namespace llvm;
1014
1015 if (Context.Comments.empty())
1016 return;
1017
1018 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1019 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1020 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1021 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1022
1023 RecordData Record;
1024 Record.push_back(pch::COMMENT_RANGES);
1025 Stream.EmitRecordWithBlob(CommentCode, Record,
1026 (const char*)&Context.Comments[0],
1027 Context.Comments.size() * sizeof(SourceRange));
1028}
1029
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001030//===----------------------------------------------------------------------===//
1031// Type Serialization
1032//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001033
Douglas Gregor2cf26342009-04-09 22:27:44 +00001034/// \brief Write the representation of a type to the PCH stream.
1035void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001036 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001037 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001038 ID = NextTypeID++;
1039
1040 // Record the offset for this type.
1041 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001042 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001043 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1044 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001045 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001046 }
1047
1048 RecordData Record;
1049
1050 // Emit the type's representation.
1051 PCHTypeWriter W(*this, Record);
1052 switch (T->getTypeClass()) {
1053 // For all of the concrete, non-dependent types, call the
1054 // appropriate visitor function.
1055#define TYPE(Class, Base) \
1056 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1057#define ABSTRACT_TYPE(Class, Base)
1058#define DEPENDENT_TYPE(Class, Base)
1059#include "clang/AST/TypeNodes.def"
1060
1061 // For all of the dependent type nodes (which only occur in C++
1062 // templates), produce an error.
1063#define TYPE(Class, Base)
1064#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1065#include "clang/AST/TypeNodes.def"
1066 assert(false && "Cannot serialize dependent type nodes");
1067 break;
1068 }
1069
1070 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001071 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001072
1073 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001074 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001075}
1076
1077/// \brief Write a block containing all of the types.
1078void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001079 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001080 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001081
Douglas Gregor366809a2009-04-26 03:49:13 +00001082 // Emit all of the types that need to be emitted (so far).
1083 while (!TypesToEmit.empty()) {
1084 const Type *T = TypesToEmit.front();
1085 TypesToEmit.pop();
1086 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1087 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001088 }
1089
1090 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001091 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001092}
1093
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001094//===----------------------------------------------------------------------===//
1095// Declaration Serialization
1096//===----------------------------------------------------------------------===//
1097
Douglas Gregor2cf26342009-04-09 22:27:44 +00001098/// \brief Write the block containing all of the declaration IDs
1099/// lexically declared within the given DeclContext.
1100///
1101/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1102/// bistream, or 0 if no block was written.
1103uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1104 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001105 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001106 return 0;
1107
Douglas Gregorc9490c02009-04-16 22:23:12 +00001108 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001109 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001110 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1111 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001112 AddDeclRef(*D, Record);
1113
Douglas Gregor25123082009-04-22 22:34:57 +00001114 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001115 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001116 return Offset;
1117}
1118
1119/// \brief Write the block containing all of the declaration IDs
1120/// visible from the given DeclContext.
1121///
1122/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1123/// bistream, or 0 if no block was written.
1124uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1125 DeclContext *DC) {
1126 if (DC->getPrimaryContext() != DC)
1127 return 0;
1128
Douglas Gregoraff22df2009-04-21 22:32:33 +00001129 // Since there is no name lookup into functions or methods, and we
1130 // perform name lookup for the translation unit via the
1131 // IdentifierInfo chains, don't bother to build a
1132 // visible-declarations table for these entities.
1133 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001134 return 0;
1135
Douglas Gregor2cf26342009-04-09 22:27:44 +00001136 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001137 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001138
1139 // Serialize the contents of the mapping used for lookup. Note that,
1140 // although we have two very different code paths, the serialized
1141 // representation is the same for both cases: a declaration name,
1142 // followed by a size, followed by references to the visible
1143 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001144 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001145 RecordData Record;
1146 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001147 if (!Map)
1148 return 0;
1149
Douglas Gregor2cf26342009-04-09 22:27:44 +00001150 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1151 D != DEnd; ++D) {
1152 AddDeclarationName(D->first, Record);
1153 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1154 Record.push_back(Result.second - Result.first);
1155 for(; Result.first != Result.second; ++Result.first)
1156 AddDeclRef(*Result.first, Record);
1157 }
1158
1159 if (Record.size() == 0)
1160 return 0;
1161
Douglas Gregorc9490c02009-04-16 22:23:12 +00001162 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001163 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001164 return Offset;
1165}
1166
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001167//===----------------------------------------------------------------------===//
1168// Global Method Pool and Selector Serialization
1169//===----------------------------------------------------------------------===//
1170
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001171namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001172// Trait used for the on-disk hash table used in the method pool.
1173class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1174 PCHWriter &Writer;
1175
1176public:
1177 typedef Selector key_type;
1178 typedef key_type key_type_ref;
1179
1180 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1181 typedef const data_type& data_type_ref;
1182
1183 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1184
1185 static unsigned ComputeHash(Selector Sel) {
1186 unsigned N = Sel.getNumArgs();
1187 if (N == 0)
1188 ++N;
1189 unsigned R = 5381;
1190 for (unsigned I = 0; I != N; ++I)
1191 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1192 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1193 return R;
1194 }
1195
1196 std::pair<unsigned,unsigned>
1197 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1198 data_type_ref Methods) {
1199 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1200 clang::io::Emit16(Out, KeyLen);
1201 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1202 for (const ObjCMethodList *Method = &Methods.first; Method;
1203 Method = Method->Next)
1204 if (Method->Method)
1205 DataLen += 4;
1206 for (const ObjCMethodList *Method = &Methods.second; Method;
1207 Method = Method->Next)
1208 if (Method->Method)
1209 DataLen += 4;
1210 clang::io::Emit16(Out, DataLen);
1211 return std::make_pair(KeyLen, DataLen);
1212 }
1213
Douglas Gregor83941df2009-04-25 17:48:32 +00001214 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1215 uint64_t Start = Out.tell();
1216 assert((Start >> 32) == 0 && "Selector key offset too large");
1217 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001218 unsigned N = Sel.getNumArgs();
1219 clang::io::Emit16(Out, N);
1220 if (N == 0)
1221 N = 1;
1222 for (unsigned I = 0; I != N; ++I)
1223 clang::io::Emit32(Out,
1224 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1225 }
1226
1227 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001228 data_type_ref Methods, unsigned DataLen) {
1229 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001230 unsigned NumInstanceMethods = 0;
1231 for (const ObjCMethodList *Method = &Methods.first; Method;
1232 Method = Method->Next)
1233 if (Method->Method)
1234 ++NumInstanceMethods;
1235
1236 unsigned NumFactoryMethods = 0;
1237 for (const ObjCMethodList *Method = &Methods.second; Method;
1238 Method = Method->Next)
1239 if (Method->Method)
1240 ++NumFactoryMethods;
1241
1242 clang::io::Emit16(Out, NumInstanceMethods);
1243 clang::io::Emit16(Out, NumFactoryMethods);
1244 for (const ObjCMethodList *Method = &Methods.first; Method;
1245 Method = Method->Next)
1246 if (Method->Method)
1247 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001248 for (const ObjCMethodList *Method = &Methods.second; Method;
1249 Method = Method->Next)
1250 if (Method->Method)
1251 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001252
1253 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001254 }
1255};
1256} // end anonymous namespace
1257
1258/// \brief Write the method pool into the PCH file.
1259///
1260/// The method pool contains both instance and factory methods, stored
1261/// in an on-disk hash table indexed by the selector.
1262void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1263 using namespace llvm;
1264
1265 // Create and write out the blob that contains the instance and
1266 // factor method pools.
1267 bool Empty = true;
1268 {
1269 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1270
1271 // Create the on-disk hash table representation. Start by
1272 // iterating through the instance method pool.
1273 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001274 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001275 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1276 Instance = SemaRef.InstanceMethodPool.begin(),
1277 InstanceEnd = SemaRef.InstanceMethodPool.end();
1278 Instance != InstanceEnd; ++Instance) {
1279 // Check whether there is a factory method with the same
1280 // selector.
1281 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1282 = SemaRef.FactoryMethodPool.find(Instance->first);
1283
1284 if (Factory == SemaRef.FactoryMethodPool.end())
1285 Generator.insert(Instance->first,
1286 std::make_pair(Instance->second,
1287 ObjCMethodList()));
1288 else
1289 Generator.insert(Instance->first,
1290 std::make_pair(Instance->second, Factory->second));
1291
Douglas Gregor83941df2009-04-25 17:48:32 +00001292 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001293 Empty = false;
1294 }
1295
1296 // Now iterate through the factory method pool, to pick up any
1297 // selectors that weren't already in the instance method pool.
1298 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1299 Factory = SemaRef.FactoryMethodPool.begin(),
1300 FactoryEnd = SemaRef.FactoryMethodPool.end();
1301 Factory != FactoryEnd; ++Factory) {
1302 // Check whether there is an instance method with the same
1303 // selector. If so, there is no work to do here.
1304 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1305 = SemaRef.InstanceMethodPool.find(Factory->first);
1306
Douglas Gregor83941df2009-04-25 17:48:32 +00001307 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001308 Generator.insert(Factory->first,
1309 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001310 ++NumSelectorsInMethodPool;
1311 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001312
1313 Empty = false;
1314 }
1315
Douglas Gregor83941df2009-04-25 17:48:32 +00001316 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001317 return;
1318
1319 // Create the on-disk hash table in a buffer.
1320 llvm::SmallVector<char, 4096> MethodPool;
1321 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001322 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001323 {
1324 PCHMethodPoolTrait Trait(*this);
1325 llvm::raw_svector_ostream Out(MethodPool);
1326 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001327 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001328 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001329
1330 // For every selector that we have seen but which was not
1331 // written into the hash table, write the selector itself and
1332 // record it's offset.
1333 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1334 if (SelectorOffsets[I] == 0)
1335 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001336 }
1337
1338 // Create a blob abbreviation
1339 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1340 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1341 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1344 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1345
Douglas Gregor83941df2009-04-25 17:48:32 +00001346 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001347 RecordData Record;
1348 Record.push_back(pch::METHOD_POOL);
1349 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001350 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001351 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1352 &MethodPool.front(),
1353 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001354
1355 // Create a blob abbreviation for the selector table offsets.
1356 Abbrev = new BitCodeAbbrev();
1357 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1359 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1360 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1361
1362 // Write the selector offsets table.
1363 Record.clear();
1364 Record.push_back(pch::SELECTOR_OFFSETS);
1365 Record.push_back(SelectorOffsets.size());
1366 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1367 (const char *)&SelectorOffsets.front(),
1368 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001369 }
1370}
1371
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001372//===----------------------------------------------------------------------===//
1373// Identifier Table Serialization
1374//===----------------------------------------------------------------------===//
1375
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001376namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001377class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1378 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001379 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001380
Douglas Gregora92193e2009-04-28 21:18:29 +00001381 /// \brief Determines whether this is an "interesting" identifier
1382 /// that needs a full IdentifierInfo structure written into the hash
1383 /// table.
1384 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1385 return II->isPoisoned() ||
1386 II->isExtensionToken() ||
1387 II->hasMacroDefinition() ||
1388 II->getObjCOrBuiltinID() ||
1389 II->getFETokenInfo<void>();
1390 }
1391
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001392public:
1393 typedef const IdentifierInfo* key_type;
1394 typedef key_type key_type_ref;
1395
1396 typedef pch::IdentID data_type;
1397 typedef data_type data_type_ref;
1398
Douglas Gregor37e26842009-04-21 23:56:24 +00001399 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1400 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001401
1402 static unsigned ComputeHash(const IdentifierInfo* II) {
1403 return clang::BernsteinHash(II->getName());
1404 }
1405
Douglas Gregor37e26842009-04-21 23:56:24 +00001406 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001407 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1408 pch::IdentID ID) {
1409 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001410 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1411 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001412 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001413 if (II->hasMacroDefinition() &&
1414 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001415 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001416 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1417 DEnd = IdentifierResolver::end();
1418 D != DEnd; ++D)
1419 DataLen += sizeof(pch::DeclID);
1420 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001421 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001422 // We emit the key length after the data length so that every
1423 // string is preceded by a 16-bit length. This matches the PTH
1424 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001425 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001426 return std::make_pair(KeyLen, DataLen);
1427 }
1428
1429 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1430 unsigned KeyLen) {
1431 // Record the location of the key data. This is used when generating
1432 // the mapping from persistent IDs to strings.
1433 Writer.SetIdentifierOffset(II, Out.tell());
1434 Out.write(II->getName(), KeyLen);
1435 }
1436
1437 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1438 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001439 if (!isInterestingIdentifier(II)) {
1440 clang::io::Emit32(Out, ID << 1);
1441 return;
1442 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001443
Douglas Gregora92193e2009-04-28 21:18:29 +00001444 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001445 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001446 bool hasMacroDefinition =
1447 II->hasMacroDefinition() &&
1448 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001449 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001450 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001451 Bits = (Bits << 1) | II->isExtensionToken();
1452 Bits = (Bits << 1) | II->isPoisoned();
1453 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001454 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001455
Douglas Gregor37e26842009-04-21 23:56:24 +00001456 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001457 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001458
Douglas Gregor668c1a42009-04-21 22:25:48 +00001459 // Emit the declaration IDs in reverse order, because the
1460 // IdentifierResolver provides the declarations as they would be
1461 // visible (e.g., the function "stat" would come before the struct
1462 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1463 // adds declarations to the end of the list (so we need to see the
1464 // struct "status" before the function "status").
1465 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1466 IdentifierResolver::end());
1467 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1468 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001469 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001470 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001471 }
1472};
1473} // end anonymous namespace
1474
Douglas Gregorafaf3082009-04-11 00:14:32 +00001475/// \brief Write the identifier table into the PCH file.
1476///
1477/// The identifier table consists of a blob containing string data
1478/// (the actual identifiers themselves) and a separate "offsets" index
1479/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001480void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001481 using namespace llvm;
1482
1483 // Create and write out the blob that contains the identifier
1484 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001485 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001486 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1487
Douglas Gregor92b059e2009-04-28 20:33:11 +00001488 // Look for any identifiers that were named while processing the
1489 // headers, but are otherwise not needed. We add these to the hash
1490 // table to enable checking of the predefines buffer in the case
1491 // where the user adds new macro definitions when building the PCH
1492 // file.
1493 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1494 IDEnd = PP.getIdentifierTable().end();
1495 ID != IDEnd; ++ID)
1496 getIdentifierRef(ID->second);
1497
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001498 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001499 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001500 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1501 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1502 ID != IDEnd; ++ID) {
1503 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001504 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001505 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001506
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001507 // Create the on-disk hash table in a buffer.
1508 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001509 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001510 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001511 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001512 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001513 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001514 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001515 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001516 }
1517
1518 // Create a blob abbreviation
1519 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1520 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001521 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001522 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001523 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001524
1525 // Write the identifier table
1526 RecordData Record;
1527 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001528 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001529 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1530 &IdentifierTable.front(),
1531 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001532 }
1533
1534 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001535 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1536 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1537 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1538 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1539 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1540
1541 RecordData Record;
1542 Record.push_back(pch::IDENTIFIER_OFFSET);
1543 Record.push_back(IdentifierOffsets.size());
1544 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1545 (const char *)&IdentifierOffsets.front(),
1546 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001547}
1548
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001549//===----------------------------------------------------------------------===//
1550// General Serialization Routines
1551//===----------------------------------------------------------------------===//
1552
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001553/// \brief Write a record containing the given attributes.
1554void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1555 RecordData Record;
1556 for (; Attr; Attr = Attr->getNext()) {
1557 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1558 Record.push_back(Attr->isInherited());
1559 switch (Attr->getKind()) {
1560 case Attr::Alias:
1561 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1562 break;
1563
1564 case Attr::Aligned:
1565 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1566 break;
1567
1568 case Attr::AlwaysInline:
1569 break;
1570
1571 case Attr::AnalyzerNoReturn:
1572 break;
1573
1574 case Attr::Annotate:
1575 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1576 break;
1577
1578 case Attr::AsmLabel:
1579 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1580 break;
1581
1582 case Attr::Blocks:
1583 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1584 break;
1585
1586 case Attr::Cleanup:
1587 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1588 break;
1589
1590 case Attr::Const:
1591 break;
1592
1593 case Attr::Constructor:
1594 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1595 break;
1596
1597 case Attr::DLLExport:
1598 case Attr::DLLImport:
1599 case Attr::Deprecated:
1600 break;
1601
1602 case Attr::Destructor:
1603 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1604 break;
1605
1606 case Attr::FastCall:
1607 break;
1608
1609 case Attr::Format: {
1610 const FormatAttr *Format = cast<FormatAttr>(Attr);
1611 AddString(Format->getType(), Record);
1612 Record.push_back(Format->getFormatIdx());
1613 Record.push_back(Format->getFirstArg());
1614 break;
1615 }
1616
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001617 case Attr::FormatArg: {
1618 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1619 Record.push_back(Format->getFormatIdx());
1620 break;
1621 }
1622
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001623 case Attr::Sentinel : {
1624 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1625 Record.push_back(Sentinel->getSentinel());
1626 Record.push_back(Sentinel->getNullPos());
1627 break;
1628 }
1629
Chris Lattnercf2a7212009-04-20 19:12:28 +00001630 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001631 case Attr::IBOutletKind:
1632 case Attr::NoReturn:
1633 case Attr::NoThrow:
1634 case Attr::Nodebug:
1635 case Attr::Noinline:
1636 break;
1637
1638 case Attr::NonNull: {
1639 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1640 Record.push_back(NonNull->size());
1641 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1642 break;
1643 }
1644
1645 case Attr::ObjCException:
1646 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001647 case Attr::CFReturnsRetained:
1648 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001649 case Attr::Overloadable:
1650 break;
1651
1652 case Attr::Packed:
1653 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1654 break;
1655
1656 case Attr::Pure:
1657 break;
1658
1659 case Attr::Regparm:
1660 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1661 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001662
1663 case Attr::ReqdWorkGroupSize:
1664 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1665 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1666 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1667 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001668
1669 case Attr::Section:
1670 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1671 break;
1672
1673 case Attr::StdCall:
1674 case Attr::TransparentUnion:
1675 case Attr::Unavailable:
1676 case Attr::Unused:
1677 case Attr::Used:
1678 break;
1679
1680 case Attr::Visibility:
1681 // FIXME: stable encoding
1682 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1683 break;
1684
1685 case Attr::WarnUnusedResult:
1686 case Attr::Weak:
1687 case Attr::WeakImport:
1688 break;
1689 }
1690 }
1691
Douglas Gregorc9490c02009-04-16 22:23:12 +00001692 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001693}
1694
1695void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1696 Record.push_back(Str.size());
1697 Record.insert(Record.end(), Str.begin(), Str.end());
1698}
1699
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001700/// \brief Note that the identifier II occurs at the given offset
1701/// within the identifier table.
1702void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001703 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001704}
1705
Douglas Gregor83941df2009-04-25 17:48:32 +00001706/// \brief Note that the selector Sel occurs at the given offset
1707/// within the method pool/selector table.
1708void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1709 unsigned ID = SelectorIDs[Sel];
1710 assert(ID && "Unknown selector");
1711 SelectorOffsets[ID - 1] = Offset;
1712}
1713
Douglas Gregorc9490c02009-04-16 22:23:12 +00001714PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001715 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001716 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1717 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001718
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001719void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001720 using namespace llvm;
1721
Douglas Gregore7785042009-04-20 15:53:59 +00001722 ASTContext &Context = SemaRef.Context;
1723 Preprocessor &PP = SemaRef.PP;
1724
Douglas Gregor2cf26342009-04-09 22:27:44 +00001725 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001726 Stream.Emit((unsigned)'C', 8);
1727 Stream.Emit((unsigned)'P', 8);
1728 Stream.Emit((unsigned)'C', 8);
1729 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001730
1731 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001732
1733 // The translation unit is the first declaration we'll emit.
1734 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1735 DeclsToEmit.push(Context.getTranslationUnitDecl());
1736
Douglas Gregor2deaea32009-04-22 18:49:13 +00001737 // Make sure that we emit IdentifierInfos (and any attached
1738 // declarations) for builtins.
1739 {
1740 IdentifierTable &Table = PP.getIdentifierTable();
1741 llvm::SmallVector<const char *, 32> BuiltinNames;
1742 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1743 Context.getLangOptions().NoBuiltin);
1744 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1745 getIdentifierRef(&Table.get(BuiltinNames[I]));
1746 }
1747
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001748 // Build a record containing all of the tentative definitions in
1749 // this header file. Generally, this record will be empty.
1750 RecordData TentativeDefinitions;
1751 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1752 TD = SemaRef.TentativeDefinitions.begin(),
1753 TDEnd = SemaRef.TentativeDefinitions.end();
1754 TD != TDEnd; ++TD)
1755 AddDeclRef(TD->second, TentativeDefinitions);
1756
Douglas Gregor14c22f22009-04-22 22:18:58 +00001757 // Build a record containing all of the locally-scoped external
1758 // declarations in this header file. Generally, this record will be
1759 // empty.
1760 RecordData LocallyScopedExternalDecls;
1761 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1762 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1763 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1764 TD != TDEnd; ++TD)
1765 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1766
Douglas Gregorb81c1702009-04-27 20:06:05 +00001767 // Build a record containing all of the ext_vector declarations.
1768 RecordData ExtVectorDecls;
1769 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1770 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1771
1772 // Build a record containing all of the Objective-C category
1773 // implementations.
1774 RecordData ObjCCategoryImpls;
1775 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1776 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1777
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001779 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001780 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001781 WriteMetadata(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001782 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001783 if (StatCalls)
1784 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001785 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001786 WritePreprocessor(PP);
Douglas Gregor2e222532009-07-02 17:08:52 +00001787 WriteComments(Context);
1788
Douglas Gregor366809a2009-04-26 03:49:13 +00001789 // Keep writing types and declarations until all types and
1790 // declarations have been written.
1791 do {
1792 if (!DeclsToEmit.empty())
1793 WriteDeclsBlock(Context);
1794 if (!TypesToEmit.empty())
1795 WriteTypesBlock(Context);
1796 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1797
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001798 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001799 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001800
1801 // Write the type offsets array
1802 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1803 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1805 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1806 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1807 Record.clear();
1808 Record.push_back(pch::TYPE_OFFSET);
1809 Record.push_back(TypeOffsets.size());
1810 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1811 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001812 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001813
1814 // Write the declaration offsets array
1815 Abbrev = new BitCodeAbbrev();
1816 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1818 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1819 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1820 Record.clear();
1821 Record.push_back(pch::DECL_OFFSET);
1822 Record.push_back(DeclOffsets.size());
1823 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1824 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001825 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001826
1827 // Write the record of special types.
1828 Record.clear();
1829 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001830 AddTypeRef(Context.getObjCIdType(), Record);
1831 AddTypeRef(Context.getObjCSelType(), Record);
1832 AddTypeRef(Context.getObjCProtoType(), Record);
1833 AddTypeRef(Context.getObjCClassType(), Record);
1834 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1835 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001836 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1837
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001838 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001839 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001840 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001841
1842 // Write the record containing tentative definitions.
1843 if (!TentativeDefinitions.empty())
1844 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001845
1846 // Write the record containing locally-scoped external definitions.
1847 if (!LocallyScopedExternalDecls.empty())
1848 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1849 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001850
1851 // Write the record containing ext_vector type names.
1852 if (!ExtVectorDecls.empty())
1853 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1854
1855 // Write the record containing Objective-C category implementations.
1856 if (!ObjCCategoryImpls.empty())
1857 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001858
1859 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001860 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001861 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001862 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001863 Record.push_back(NumLexicalDeclContexts);
1864 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001865 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001866 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001867}
1868
1869void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1870 Record.push_back(Loc.getRawEncoding());
1871}
1872
1873void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1874 Record.push_back(Value.getBitWidth());
1875 unsigned N = Value.getNumWords();
1876 const uint64_t* Words = Value.getRawData();
1877 for (unsigned I = 0; I != N; ++I)
1878 Record.push_back(Words[I]);
1879}
1880
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001881void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1882 Record.push_back(Value.isUnsigned());
1883 AddAPInt(Value, Record);
1884}
1885
Douglas Gregor17fc2232009-04-14 21:55:33 +00001886void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1887 AddAPInt(Value.bitcastToAPInt(), Record);
1888}
1889
Douglas Gregor2cf26342009-04-09 22:27:44 +00001890void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001891 Record.push_back(getIdentifierRef(II));
1892}
1893
1894pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1895 if (II == 0)
1896 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001897
1898 pch::IdentID &ID = IdentifierIDs[II];
1899 if (ID == 0)
1900 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001901 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001902}
1903
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001904void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1905 if (SelRef.getAsOpaquePtr() == 0) {
1906 Record.push_back(0);
1907 return;
1908 }
1909
1910 pch::SelectorID &SID = SelectorIDs[SelRef];
1911 if (SID == 0) {
1912 SID = SelectorIDs.size();
1913 SelVector.push_back(SelRef);
1914 }
1915 Record.push_back(SID);
1916}
1917
Douglas Gregor2cf26342009-04-09 22:27:44 +00001918void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1919 if (T.isNull()) {
1920 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1921 return;
1922 }
1923
1924 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001925 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001926 switch (BT->getKind()) {
1927 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1928 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1929 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1930 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1931 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1932 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1933 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1934 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001935 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001936 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1937 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1938 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1939 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1940 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1941 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1942 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001943 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001944 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1945 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1946 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001947 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001948 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1949 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00001950 case BuiltinType::UndeducedAuto:
1951 assert(0 && "Should not see undeduced auto here");
1952 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001953 }
1954
1955 Record.push_back((ID << 3) | T.getCVRQualifiers());
1956 return;
1957 }
1958
Douglas Gregor8038d512009-04-10 17:25:41 +00001959 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001960 if (ID == 0) {
1961 // We haven't seen this type before. Assign it a new ID and put it
1962 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001963 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001964 TypesToEmit.push(T.getTypePtr());
1965 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001966
1967 // Encode the type qualifiers in the type reference.
1968 Record.push_back((ID << 3) | T.getCVRQualifiers());
1969}
1970
1971void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1972 if (D == 0) {
1973 Record.push_back(0);
1974 return;
1975 }
1976
Douglas Gregor8038d512009-04-10 17:25:41 +00001977 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978 if (ID == 0) {
1979 // We haven't seen this declaration before. Give it a new ID and
1980 // enqueue it in the list of declarations to emit.
1981 ID = DeclIDs.size();
1982 DeclsToEmit.push(const_cast<Decl *>(D));
1983 }
1984
1985 Record.push_back(ID);
1986}
1987
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001988pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1989 if (D == 0)
1990 return 0;
1991
1992 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1993 return DeclIDs[D];
1994}
1995
Douglas Gregor2cf26342009-04-09 22:27:44 +00001996void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001997 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001998 Record.push_back(Name.getNameKind());
1999 switch (Name.getNameKind()) {
2000 case DeclarationName::Identifier:
2001 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2002 break;
2003
2004 case DeclarationName::ObjCZeroArgSelector:
2005 case DeclarationName::ObjCOneArgSelector:
2006 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002007 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002008 break;
2009
2010 case DeclarationName::CXXConstructorName:
2011 case DeclarationName::CXXDestructorName:
2012 case DeclarationName::CXXConversionFunctionName:
2013 AddTypeRef(Name.getCXXNameType(), Record);
2014 break;
2015
2016 case DeclarationName::CXXOperatorName:
2017 Record.push_back(Name.getCXXOverloadedOperator());
2018 break;
2019
2020 case DeclarationName::CXXUsingDirective:
2021 // No extra data to emit
2022 break;
2023 }
2024}
Douglas Gregor0b748912009-04-14 21:18:50 +00002025