blob: 3b1eb080f229be1681d0a19a705317def9496d57 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
Sebastian Redl2767d882009-05-27 22:11:52 +0000165 Record.push_back(T->hasExceptionSpec());
166 Record.push_back(T->hasAnyExceptionSpec());
167 Record.push_back(T->getNumExceptions());
168 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
169 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_FUNCTION_PROTO;
171}
172
173void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
174 Writer.AddDeclRef(T->getDecl(), Record);
175 Code = pch::TYPE_TYPEDEF;
176}
177
178void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000180 Code = pch::TYPE_TYPEOF_EXPR;
181}
182
183void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
184 Writer.AddTypeRef(T->getUnderlyingType(), Record);
185 Code = pch::TYPE_TYPEOF;
186}
187
188void PCHTypeWriter::VisitTagType(const TagType *T) {
189 Writer.AddDeclRef(T->getDecl(), Record);
190 assert(!T->isBeingDefined() &&
191 "Cannot serialize in the middle of a type definition");
192}
193
194void PCHTypeWriter::VisitRecordType(const RecordType *T) {
195 VisitTagType(T);
196 Code = pch::TYPE_RECORD;
197}
198
199void PCHTypeWriter::VisitEnumType(const EnumType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_ENUM;
202}
203
204void
205PCHTypeWriter::VisitTemplateSpecializationType(
206 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000207 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 assert(false && "Cannot serialize template specialization types");
209}
210
211void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize qualified name types");
214}
215
216void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
217 Writer.AddDeclRef(T->getDecl(), Record);
218 Code = pch::TYPE_OBJC_INTERFACE;
219}
220
221void
222PCHTypeWriter::VisitObjCQualifiedInterfaceType(
223 const ObjCQualifiedInterfaceType *T) {
224 VisitObjCInterfaceType(T);
225 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000226 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
227 E = T->qual_end(); I != E; ++I)
228 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000229 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
230}
231
Steve Naroffc75c1a82009-06-17 22:40:22 +0000232void
233PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
234 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000235 Record.push_back(T->getNumProtocols());
Steve Naroffc75c1a82009-06-17 22:40:22 +0000236 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff83418522009-05-27 16:21:00 +0000237 E = T->qual_end(); I != E; ++I)
238 Writer.AddDeclRef(*I, Record);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000239 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000240}
241
Chris Lattner80f83c62009-04-22 05:57:30 +0000242//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000243// PCHWriter Implementation
244//===----------------------------------------------------------------------===//
245
Chris Lattner920673a2009-04-26 22:26:21 +0000246static void EmitBlockID(unsigned ID, const char *Name,
247 llvm::BitstreamWriter &Stream,
248 PCHWriter::RecordData &Record) {
249 Record.clear();
250 Record.push_back(ID);
251 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
252
253 // Emit the block name if present.
254 if (Name == 0 || Name[0] == 0) return;
255 Record.clear();
256 while (*Name)
257 Record.push_back(*Name++);
258 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
259}
260
261static void EmitRecordID(unsigned ID, const char *Name,
262 llvm::BitstreamWriter &Stream,
263 PCHWriter::RecordData &Record) {
264 Record.clear();
265 Record.push_back(ID);
266 while (*Name)
267 Record.push_back(*Name++);
268 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000269}
270
271static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
272 PCHWriter::RecordData &Record) {
273#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
274 RECORD(STMT_STOP);
275 RECORD(STMT_NULL_PTR);
276 RECORD(STMT_NULL);
277 RECORD(STMT_COMPOUND);
278 RECORD(STMT_CASE);
279 RECORD(STMT_DEFAULT);
280 RECORD(STMT_LABEL);
281 RECORD(STMT_IF);
282 RECORD(STMT_SWITCH);
283 RECORD(STMT_WHILE);
284 RECORD(STMT_DO);
285 RECORD(STMT_FOR);
286 RECORD(STMT_GOTO);
287 RECORD(STMT_INDIRECT_GOTO);
288 RECORD(STMT_CONTINUE);
289 RECORD(STMT_BREAK);
290 RECORD(STMT_RETURN);
291 RECORD(STMT_DECL);
292 RECORD(STMT_ASM);
293 RECORD(EXPR_PREDEFINED);
294 RECORD(EXPR_DECL_REF);
295 RECORD(EXPR_INTEGER_LITERAL);
296 RECORD(EXPR_FLOATING_LITERAL);
297 RECORD(EXPR_IMAGINARY_LITERAL);
298 RECORD(EXPR_STRING_LITERAL);
299 RECORD(EXPR_CHARACTER_LITERAL);
300 RECORD(EXPR_PAREN);
301 RECORD(EXPR_UNARY_OPERATOR);
302 RECORD(EXPR_SIZEOF_ALIGN_OF);
303 RECORD(EXPR_ARRAY_SUBSCRIPT);
304 RECORD(EXPR_CALL);
305 RECORD(EXPR_MEMBER);
306 RECORD(EXPR_BINARY_OPERATOR);
307 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
308 RECORD(EXPR_CONDITIONAL_OPERATOR);
309 RECORD(EXPR_IMPLICIT_CAST);
310 RECORD(EXPR_CSTYLE_CAST);
311 RECORD(EXPR_COMPOUND_LITERAL);
312 RECORD(EXPR_EXT_VECTOR_ELEMENT);
313 RECORD(EXPR_INIT_LIST);
314 RECORD(EXPR_DESIGNATED_INIT);
315 RECORD(EXPR_IMPLICIT_VALUE_INIT);
316 RECORD(EXPR_VA_ARG);
317 RECORD(EXPR_ADDR_LABEL);
318 RECORD(EXPR_STMT);
319 RECORD(EXPR_TYPES_COMPATIBLE);
320 RECORD(EXPR_CHOOSE);
321 RECORD(EXPR_GNU_NULL);
322 RECORD(EXPR_SHUFFLE_VECTOR);
323 RECORD(EXPR_BLOCK);
324 RECORD(EXPR_BLOCK_DECL_REF);
325 RECORD(EXPR_OBJC_STRING_LITERAL);
326 RECORD(EXPR_OBJC_ENCODE);
327 RECORD(EXPR_OBJC_SELECTOR_EXPR);
328 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
329 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
330 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
331 RECORD(EXPR_OBJC_KVC_REF_EXPR);
332 RECORD(EXPR_OBJC_MESSAGE_EXPR);
333 RECORD(EXPR_OBJC_SUPER_EXPR);
334 RECORD(STMT_OBJC_FOR_COLLECTION);
335 RECORD(STMT_OBJC_CATCH);
336 RECORD(STMT_OBJC_FINALLY);
337 RECORD(STMT_OBJC_AT_TRY);
338 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
339 RECORD(STMT_OBJC_AT_THROW);
340#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000341}
342
343void PCHWriter::WriteBlockInfoBlock() {
344 RecordData Record;
345 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
346
Chris Lattner880f3f72009-04-27 00:40:25 +0000347#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000348#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
349
350 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000351 BLOCK(PCH_BLOCK);
Zhongxing Xu29b61a52009-06-03 09:23:28 +0000352 RECORD(ORIGINAL_FILE_NAME);
Chris Lattner920673a2009-04-26 22:26:21 +0000353 RECORD(TYPE_OFFSET);
354 RECORD(DECL_OFFSET);
355 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000356 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000357 RECORD(IDENTIFIER_OFFSET);
358 RECORD(IDENTIFIER_TABLE);
359 RECORD(EXTERNAL_DEFINITIONS);
360 RECORD(SPECIAL_TYPES);
361 RECORD(STATISTICS);
362 RECORD(TENTATIVE_DEFINITIONS);
363 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
364 RECORD(SELECTOR_OFFSETS);
365 RECORD(METHOD_POOL);
366 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000367 RECORD(SOURCE_LOCATION_OFFSETS);
368 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000369 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000370 RECORD(EXT_VECTOR_DECLS);
371 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000372
Chris Lattner920673a2009-04-26 22:26:21 +0000373 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000374 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000375 RECORD(SM_SLOC_FILE_ENTRY);
376 RECORD(SM_SLOC_BUFFER_ENTRY);
377 RECORD(SM_SLOC_BUFFER_BLOB);
378 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
379 RECORD(SM_LINE_TABLE);
380 RECORD(SM_HEADER_FILE_INFO);
381
382 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000383 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000384 RECORD(PP_MACRO_OBJECT_LIKE);
385 RECORD(PP_MACRO_FUNCTION_LIKE);
386 RECORD(PP_TOKEN);
387
388 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000389 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000390 RECORD(TYPE_EXT_QUAL);
391 RECORD(TYPE_FIXED_WIDTH_INT);
392 RECORD(TYPE_COMPLEX);
393 RECORD(TYPE_POINTER);
394 RECORD(TYPE_BLOCK_POINTER);
395 RECORD(TYPE_LVALUE_REFERENCE);
396 RECORD(TYPE_RVALUE_REFERENCE);
397 RECORD(TYPE_MEMBER_POINTER);
398 RECORD(TYPE_CONSTANT_ARRAY);
399 RECORD(TYPE_INCOMPLETE_ARRAY);
400 RECORD(TYPE_VARIABLE_ARRAY);
401 RECORD(TYPE_VECTOR);
402 RECORD(TYPE_EXT_VECTOR);
403 RECORD(TYPE_FUNCTION_PROTO);
404 RECORD(TYPE_FUNCTION_NO_PROTO);
405 RECORD(TYPE_TYPEDEF);
406 RECORD(TYPE_TYPEOF_EXPR);
407 RECORD(TYPE_TYPEOF);
408 RECORD(TYPE_RECORD);
409 RECORD(TYPE_ENUM);
410 RECORD(TYPE_OBJC_INTERFACE);
411 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000412 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000413 // Statements and Exprs can occur in the Types block.
414 AddStmtsExprs(Stream, Record);
415
Chris Lattner920673a2009-04-26 22:26:21 +0000416 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000417 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000418 RECORD(DECL_ATTR);
419 RECORD(DECL_TRANSLATION_UNIT);
420 RECORD(DECL_TYPEDEF);
421 RECORD(DECL_ENUM);
422 RECORD(DECL_RECORD);
423 RECORD(DECL_ENUM_CONSTANT);
424 RECORD(DECL_FUNCTION);
425 RECORD(DECL_OBJC_METHOD);
426 RECORD(DECL_OBJC_INTERFACE);
427 RECORD(DECL_OBJC_PROTOCOL);
428 RECORD(DECL_OBJC_IVAR);
429 RECORD(DECL_OBJC_AT_DEFS_FIELD);
430 RECORD(DECL_OBJC_CLASS);
431 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
432 RECORD(DECL_OBJC_CATEGORY);
433 RECORD(DECL_OBJC_CATEGORY_IMPL);
434 RECORD(DECL_OBJC_IMPLEMENTATION);
435 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
436 RECORD(DECL_OBJC_PROPERTY);
437 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000438 RECORD(DECL_FIELD);
439 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000440 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000441 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000442 RECORD(DECL_ORIGINAL_PARM_VAR);
443 RECORD(DECL_FILE_SCOPE_ASM);
444 RECORD(DECL_BLOCK);
445 RECORD(DECL_CONTEXT_LEXICAL);
446 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000447 // Statements and Exprs can occur in the Decls block.
448 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000449#undef RECORD
450#undef BLOCK
451 Stream.ExitBlock();
452}
453
454
Douglas Gregorb7064742009-04-27 22:23:34 +0000455/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000456void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000457 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000458
459 // Original file name
460 SourceManager &SM = Context.getSourceManager();
461 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
462 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
463 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
464 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
465 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
466
467 llvm::sys::Path MainFilePath(MainFile->getName());
468 std::string MainFileName;
469
470 if (!MainFilePath.isAbsolute()) {
471 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
472 P.appendComponent(MainFilePath.toString());
473 MainFileName = P.toString();
474 } else {
475 MainFileName = MainFilePath.toString();
476 }
477
478 RecordData Record;
479 Record.push_back(pch::ORIGINAL_FILE_NAME);
480 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
481 MainFileName.size());
482 }
483
484 // Metadata
485 const TargetInfo &Target = Context.Target;
486 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
487 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
488 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
489 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
490 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
491 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
492 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
493 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000494
495 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000496 Record.push_back(pch::METADATA);
497 Record.push_back(pch::VERSION_MAJOR);
498 Record.push_back(pch::VERSION_MINOR);
499 Record.push_back(CLANG_VERSION_MAJOR);
500 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000501 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000502 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000503}
504
505/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000506void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
507 RecordData Record;
508 Record.push_back(LangOpts.Trigraphs);
509 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
510 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
511 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
512 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
513 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
514 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
515 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
516 Record.push_back(LangOpts.C99); // C99 Support
517 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
518 Record.push_back(LangOpts.CPlusPlus); // C++ Support
519 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000520 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
521
522 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
523 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
524 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
525
526 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000527 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
528 Record.push_back(LangOpts.LaxVectorConversions);
529 Record.push_back(LangOpts.Exceptions); // Support exception handling.
530
531 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
532 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
533 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
534
Chris Lattnercd4da472009-04-27 07:35:58 +0000535 // Whether static initializers are protected by locks.
536 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000537 Record.push_back(LangOpts.Blocks); // block extension to C
538 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
539 // they are unused.
540 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
541 // (modulo the platform support).
542
543 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
544 // signed integer arithmetic overflows.
545
546 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
547 // may be ripped out at any time.
548
549 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
550 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
551 // defined.
552 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
553 // opposed to __DYNAMIC__).
554 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
555
556 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
557 // used (instead of C99 semantics).
558 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000559 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
560 // be enabled.
Eli Friedmand9389be2009-06-05 07:05:05 +0000561 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
562 // unsigned type
Douglas Gregor179cfb12009-04-10 20:39:37 +0000563 Record.push_back(LangOpts.getGCMode());
564 Record.push_back(LangOpts.getVisibilityMode());
565 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000566 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000567}
568
Douglas Gregorab1cef72009-04-10 03:52:48 +0000569//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000570// stat cache Serialization
571//===----------------------------------------------------------------------===//
572
573namespace {
574// Trait used for the on-disk hash table of stat cache results.
575class VISIBILITY_HIDDEN PCHStatCacheTrait {
576public:
577 typedef const char * key_type;
578 typedef key_type key_type_ref;
579
580 typedef std::pair<int, struct stat> data_type;
581 typedef const data_type& data_type_ref;
582
583 static unsigned ComputeHash(const char *path) {
584 return BernsteinHash(path);
585 }
586
587 std::pair<unsigned,unsigned>
588 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
589 data_type_ref Data) {
590 unsigned StrLen = strlen(path);
591 clang::io::Emit16(Out, StrLen);
592 unsigned DataLen = 1; // result value
593 if (Data.first == 0)
594 DataLen += 4 + 4 + 2 + 8 + 8;
595 clang::io::Emit8(Out, DataLen);
596 return std::make_pair(StrLen + 1, DataLen);
597 }
598
599 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
600 Out.write(path, KeyLen);
601 }
602
603 void EmitData(llvm::raw_ostream& Out, key_type_ref,
604 data_type_ref Data, unsigned DataLen) {
605 using namespace clang::io;
606 uint64_t Start = Out.tell(); (void)Start;
607
608 // Result of stat()
609 Emit8(Out, Data.first? 1 : 0);
610
611 if (Data.first == 0) {
612 Emit32(Out, (uint32_t) Data.second.st_ino);
613 Emit32(Out, (uint32_t) Data.second.st_dev);
614 Emit16(Out, (uint16_t) Data.second.st_mode);
615 Emit64(Out, (uint64_t) Data.second.st_mtime);
616 Emit64(Out, (uint64_t) Data.second.st_size);
617 }
618
619 assert(Out.tell() - Start == DataLen && "Wrong data length");
620 }
621};
622} // end anonymous namespace
623
624/// \brief Write the stat() system call cache to the PCH file.
625void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
626 // Build the on-disk hash table containing information about every
627 // stat() call.
628 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
629 unsigned NumStatEntries = 0;
630 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
631 StatEnd = StatCalls.end();
632 Stat != StatEnd; ++Stat, ++NumStatEntries)
633 Generator.insert(Stat->first(), Stat->second);
634
635 // Create the on-disk hash table in a buffer.
636 llvm::SmallVector<char, 4096> StatCacheData;
637 uint32_t BucketOffset;
638 {
639 llvm::raw_svector_ostream Out(StatCacheData);
640 // Make sure that no bucket is at offset 0
641 clang::io::Emit32(Out, 0);
642 BucketOffset = Generator.Emit(Out);
643 }
644
645 // Create a blob abbreviation
646 using namespace llvm;
647 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
648 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
652 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
653
654 // Write the stat cache
655 RecordData Record;
656 Record.push_back(pch::STAT_CACHE);
657 Record.push_back(BucketOffset);
658 Record.push_back(NumStatEntries);
659 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
660 &StatCacheData.front(),
661 StatCacheData.size());
662}
663
664//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000665// Source Manager Serialization
666//===----------------------------------------------------------------------===//
667
668/// \brief Create an abbreviation for the SLocEntry that refers to a
669/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000670static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000671 using namespace llvm;
672 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
673 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000679 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000680}
681
682/// \brief Create an abbreviation for the SLocEntry that refers to a
683/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000684static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000685 using namespace llvm;
686 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
687 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
689 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
690 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
691 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
692 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000693 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000694}
695
696/// \brief Create an abbreviation for the SLocEntry that refers to a
697/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000698static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000699 using namespace llvm;
700 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
701 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000703 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000704}
705
706/// \brief Create an abbreviation for the SLocEntry that refers to an
707/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000708static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000709 using namespace llvm;
710 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
711 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000717 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000718}
719
720/// \brief Writes the block containing the serialized form of the
721/// source manager.
722///
723/// TODO: We should probably use an on-disk hash table (stored in a
724/// blob), indexed based on the file name, so that we only create
725/// entries for files that we actually need. In the common case (no
726/// errors), we probably won't have to create file entries for any of
727/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000728void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
729 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000730 RecordData Record;
731
Chris Lattner84b04f12009-04-10 17:16:57 +0000732 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000733 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000734
735 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000736 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
737 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
738 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
739 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000740
Douglas Gregor635f97f2009-04-13 16:31:14 +0000741 // Write the line table.
742 if (SourceMgr.hasLineTable()) {
743 LineTableInfo &LineTable = SourceMgr.getLineTable();
744
745 // Emit the file names
746 Record.push_back(LineTable.getNumFilenames());
747 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
748 // Emit the file name
749 const char *Filename = LineTable.getFilename(I);
750 unsigned FilenameLen = Filename? strlen(Filename) : 0;
751 Record.push_back(FilenameLen);
752 if (FilenameLen)
753 Record.insert(Record.end(), Filename, Filename + FilenameLen);
754 }
755
756 // Emit the line entries
757 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
758 L != LEnd; ++L) {
759 // Emit the file ID
760 Record.push_back(L->first);
761
762 // Emit the line entries
763 Record.push_back(L->second.size());
764 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
765 LEEnd = L->second.end();
766 LE != LEEnd; ++LE) {
767 Record.push_back(LE->FileOffset);
768 Record.push_back(LE->LineNo);
769 Record.push_back(LE->FilenameID);
770 Record.push_back((unsigned)LE->FileKind);
771 Record.push_back(LE->IncludeOffset);
772 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000773 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000774 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000775 }
776
Douglas Gregor32e231c2009-04-27 06:38:32 +0000777 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000778 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000779 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000780 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
781 E = HS.header_file_end();
782 I != E; ++I) {
783 Record.push_back(I->isImport);
784 Record.push_back(I->DirInfo);
785 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000786 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000787 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
788 Record.clear();
789 }
790
Douglas Gregor32e231c2009-04-27 06:38:32 +0000791 // Write out the source location entry table. We skip the first
792 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000793 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000794 RecordData PreloadSLocs;
795 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
796 for (SourceManager::sloc_entry_iterator
797 SLoc = SourceMgr.sloc_entry_begin() + 1,
798 SLocEnd = SourceMgr.sloc_entry_end();
799 SLoc != SLocEnd; ++SLoc) {
800 // Record the offset of this source-location entry.
801 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
802
803 // Figure out which record code to use.
804 unsigned Code;
805 if (SLoc->isFile()) {
806 if (SLoc->getFile().getContentCache()->Entry)
807 Code = pch::SM_SLOC_FILE_ENTRY;
808 else
809 Code = pch::SM_SLOC_BUFFER_ENTRY;
810 } else
811 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
812 Record.clear();
813 Record.push_back(Code);
814
815 Record.push_back(SLoc->getOffset());
816 if (SLoc->isFile()) {
817 const SrcMgr::FileInfo &File = SLoc->getFile();
818 Record.push_back(File.getIncludeLoc().getRawEncoding());
819 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
820 Record.push_back(File.hasLineDirectives());
821
822 const SrcMgr::ContentCache *Content = File.getContentCache();
823 if (Content->Entry) {
824 // The source location entry is a file. The blob associated
825 // with this entry is the file name.
826 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
827 Content->Entry->getName(),
828 strlen(Content->Entry->getName()));
829
830 // FIXME: For now, preload all file source locations, so that
831 // we get the appropriate File entries in the reader. This is
832 // a temporary measure.
833 PreloadSLocs.push_back(SLocEntryOffsets.size());
834 } else {
835 // The source location entry is a buffer. The blob associated
836 // with this entry contains the contents of the buffer.
837
838 // We add one to the size so that we capture the trailing NULL
839 // that is required by llvm::MemoryBuffer::getMemBuffer (on
840 // the reader side).
841 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
842 const char *Name = Buffer->getBufferIdentifier();
843 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
844 Record.clear();
845 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
846 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
847 Buffer->getBufferStart(),
848 Buffer->getBufferSize() + 1);
849
850 if (strcmp(Name, "<built-in>") == 0)
851 PreloadSLocs.push_back(SLocEntryOffsets.size());
852 }
853 } else {
854 // The source location entry is an instantiation.
855 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
856 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
857 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
858 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
859
860 // Compute the token length for this macro expansion.
861 unsigned NextOffset = SourceMgr.getNextOffset();
862 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
863 if (++NextSLoc != SLocEnd)
864 NextOffset = NextSLoc->getOffset();
865 Record.push_back(NextOffset - SLoc->getOffset() - 1);
866 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
867 }
868 }
869
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000870 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000871
872 if (SLocEntryOffsets.empty())
873 return;
874
875 // Write the source-location offsets table into the PCH block. This
876 // table is used for lazily loading source-location information.
877 using namespace llvm;
878 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
879 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
881 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
882 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
883 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
884
885 Record.clear();
886 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
887 Record.push_back(SLocEntryOffsets.size());
888 Record.push_back(SourceMgr.getNextOffset());
889 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
890 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000891 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000892
893 // Write the source location entry preloads array, telling the PCH
894 // reader which source locations entries it should load eagerly.
895 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000896}
897
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000898//===----------------------------------------------------------------------===//
899// Preprocessor Serialization
900//===----------------------------------------------------------------------===//
901
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000902/// \brief Writes the block containing the serialized form of the
903/// preprocessor.
904///
Chris Lattner850eabd2009-04-10 18:08:30 +0000905void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000906 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000907
Chris Lattner4b21c202009-04-13 01:29:17 +0000908 // If the preprocessor __COUNTER__ value has been bumped, remember it.
909 if (PP.getCounterValue() != 0) {
910 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000911 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000912 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000913 }
914
915 // Enter the preprocessor block.
916 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000917
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000918 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
919 // FIXME: use diagnostics subsystem for localization etc.
920 if (PP.SawDateOrTime())
921 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
922
Chris Lattner1b094952009-04-10 18:00:12 +0000923 // Loop over all the macro definitions that are live at the end of the file,
924 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000925 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
926 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000927 // FIXME: This emits macros in hash table order, we should do it in a stable
928 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000929 MacroInfo *MI = I->second;
930
931 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
932 // been redefined by the header (in which case they are not isBuiltinMacro).
933 if (MI->isBuiltinMacro())
934 continue;
935
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000936 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000937 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000938 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000939 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
940 Record.push_back(MI->isUsed());
941
942 unsigned Code;
943 if (MI->isObjectLike()) {
944 Code = pch::PP_MACRO_OBJECT_LIKE;
945 } else {
946 Code = pch::PP_MACRO_FUNCTION_LIKE;
947
948 Record.push_back(MI->isC99Varargs());
949 Record.push_back(MI->isGNUVarargs());
950 Record.push_back(MI->getNumArgs());
951 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
952 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000953 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000954 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000955 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000956 Record.clear();
957
Chris Lattner850eabd2009-04-10 18:08:30 +0000958 // Emit the tokens array.
959 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
960 // Note that we know that the preprocessor does not have any annotation
961 // tokens in it because they are created by the parser, and thus can't be
962 // in a macro definition.
963 const Token &Tok = MI->getReplacementToken(TokNo);
964
965 Record.push_back(Tok.getLocation().getRawEncoding());
966 Record.push_back(Tok.getLength());
967
Chris Lattner850eabd2009-04-10 18:08:30 +0000968 // FIXME: When reading literal tokens, reconstruct the literal pointer if
969 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000970 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000971
972 // FIXME: Should translate token kind to a stable encoding.
973 Record.push_back(Tok.getKind());
974 // FIXME: Should translate token flags to a stable encoding.
975 Record.push_back(Tok.getFlags());
976
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000977 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000978 Record.clear();
979 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000980 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000981 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000982 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000983}
984
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000985//===----------------------------------------------------------------------===//
986// Type Serialization
987//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000988
Douglas Gregorc34897d2009-04-09 22:27:44 +0000989/// \brief Write the representation of a type to the PCH stream.
990void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000991 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000992 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000993 ID = NextTypeID++;
994
995 // Record the offset for this type.
996 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000997 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000998 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
999 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001000 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001001 }
1002
1003 RecordData Record;
1004
1005 // Emit the type's representation.
1006 PCHTypeWriter W(*this, Record);
1007 switch (T->getTypeClass()) {
1008 // For all of the concrete, non-dependent types, call the
1009 // appropriate visitor function.
1010#define TYPE(Class, Base) \
1011 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1012#define ABSTRACT_TYPE(Class, Base)
1013#define DEPENDENT_TYPE(Class, Base)
1014#include "clang/AST/TypeNodes.def"
1015
1016 // For all of the dependent type nodes (which only occur in C++
1017 // templates), produce an error.
1018#define TYPE(Class, Base)
1019#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1020#include "clang/AST/TypeNodes.def"
1021 assert(false && "Cannot serialize dependent type nodes");
1022 break;
1023 }
1024
1025 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001026 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001027
1028 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001029 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001030}
1031
1032/// \brief Write a block containing all of the types.
1033void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001034 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001035 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001036
Douglas Gregore43f0972009-04-26 03:49:13 +00001037 // Emit all of the types that need to be emitted (so far).
1038 while (!TypesToEmit.empty()) {
1039 const Type *T = TypesToEmit.front();
1040 TypesToEmit.pop();
1041 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1042 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001043 }
1044
1045 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001046 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001047}
1048
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001049//===----------------------------------------------------------------------===//
1050// Declaration Serialization
1051//===----------------------------------------------------------------------===//
1052
Douglas Gregorc34897d2009-04-09 22:27:44 +00001053/// \brief Write the block containing all of the declaration IDs
1054/// lexically declared within the given DeclContext.
1055///
1056/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1057/// bistream, or 0 if no block was written.
1058uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1059 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001060 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001061 return 0;
1062
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001063 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001064 RecordData Record;
1065 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1066 DEnd = DC->decls_end(Context);
1067 D != DEnd; ++D)
1068 AddDeclRef(*D, Record);
1069
Douglas Gregoraf136d92009-04-22 22:34:57 +00001070 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001071 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001072 return Offset;
1073}
1074
1075/// \brief Write the block containing all of the declaration IDs
1076/// visible from the given DeclContext.
1077///
1078/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1079/// bistream, or 0 if no block was written.
1080uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1081 DeclContext *DC) {
1082 if (DC->getPrimaryContext() != DC)
1083 return 0;
1084
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001085 // Since there is no name lookup into functions or methods, and we
1086 // perform name lookup for the translation unit via the
1087 // IdentifierInfo chains, don't bother to build a
1088 // visible-declarations table for these entities.
1089 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001090 return 0;
1091
Douglas Gregorc34897d2009-04-09 22:27:44 +00001092 // Force the DeclContext to build a its name-lookup table.
1093 DC->lookup(Context, DeclarationName());
1094
1095 // Serialize the contents of the mapping used for lookup. Note that,
1096 // although we have two very different code paths, the serialized
1097 // representation is the same for both cases: a declaration name,
1098 // followed by a size, followed by references to the visible
1099 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001100 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001101 RecordData Record;
1102 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001103 if (!Map)
1104 return 0;
1105
Douglas Gregorc34897d2009-04-09 22:27:44 +00001106 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1107 D != DEnd; ++D) {
1108 AddDeclarationName(D->first, Record);
1109 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1110 Record.push_back(Result.second - Result.first);
1111 for(; Result.first != Result.second; ++Result.first)
1112 AddDeclRef(*Result.first, Record);
1113 }
1114
1115 if (Record.size() == 0)
1116 return 0;
1117
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001118 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001119 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001120 return Offset;
1121}
1122
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001123//===----------------------------------------------------------------------===//
1124// Global Method Pool and Selector Serialization
1125//===----------------------------------------------------------------------===//
1126
Douglas Gregorff9a6092009-04-20 20:36:09 +00001127namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001128// Trait used for the on-disk hash table used in the method pool.
1129class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1130 PCHWriter &Writer;
1131
1132public:
1133 typedef Selector key_type;
1134 typedef key_type key_type_ref;
1135
1136 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1137 typedef const data_type& data_type_ref;
1138
1139 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1140
1141 static unsigned ComputeHash(Selector Sel) {
1142 unsigned N = Sel.getNumArgs();
1143 if (N == 0)
1144 ++N;
1145 unsigned R = 5381;
1146 for (unsigned I = 0; I != N; ++I)
1147 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1148 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1149 return R;
1150 }
1151
1152 std::pair<unsigned,unsigned>
1153 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1154 data_type_ref Methods) {
1155 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1156 clang::io::Emit16(Out, KeyLen);
1157 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1158 for (const ObjCMethodList *Method = &Methods.first; Method;
1159 Method = Method->Next)
1160 if (Method->Method)
1161 DataLen += 4;
1162 for (const ObjCMethodList *Method = &Methods.second; Method;
1163 Method = Method->Next)
1164 if (Method->Method)
1165 DataLen += 4;
1166 clang::io::Emit16(Out, DataLen);
1167 return std::make_pair(KeyLen, DataLen);
1168 }
1169
Douglas Gregor2d711832009-04-25 17:48:32 +00001170 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1171 uint64_t Start = Out.tell();
1172 assert((Start >> 32) == 0 && "Selector key offset too large");
1173 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001174 unsigned N = Sel.getNumArgs();
1175 clang::io::Emit16(Out, N);
1176 if (N == 0)
1177 N = 1;
1178 for (unsigned I = 0; I != N; ++I)
1179 clang::io::Emit32(Out,
1180 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1181 }
1182
1183 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001184 data_type_ref Methods, unsigned DataLen) {
1185 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001186 unsigned NumInstanceMethods = 0;
1187 for (const ObjCMethodList *Method = &Methods.first; Method;
1188 Method = Method->Next)
1189 if (Method->Method)
1190 ++NumInstanceMethods;
1191
1192 unsigned NumFactoryMethods = 0;
1193 for (const ObjCMethodList *Method = &Methods.second; Method;
1194 Method = Method->Next)
1195 if (Method->Method)
1196 ++NumFactoryMethods;
1197
1198 clang::io::Emit16(Out, NumInstanceMethods);
1199 clang::io::Emit16(Out, NumFactoryMethods);
1200 for (const ObjCMethodList *Method = &Methods.first; Method;
1201 Method = Method->Next)
1202 if (Method->Method)
1203 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001204 for (const ObjCMethodList *Method = &Methods.second; Method;
1205 Method = Method->Next)
1206 if (Method->Method)
1207 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001208
1209 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001210 }
1211};
1212} // end anonymous namespace
1213
1214/// \brief Write the method pool into the PCH file.
1215///
1216/// The method pool contains both instance and factory methods, stored
1217/// in an on-disk hash table indexed by the selector.
1218void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1219 using namespace llvm;
1220
1221 // Create and write out the blob that contains the instance and
1222 // factor method pools.
1223 bool Empty = true;
1224 {
1225 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1226
1227 // Create the on-disk hash table representation. Start by
1228 // iterating through the instance method pool.
1229 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001230 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001231 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1232 Instance = SemaRef.InstanceMethodPool.begin(),
1233 InstanceEnd = SemaRef.InstanceMethodPool.end();
1234 Instance != InstanceEnd; ++Instance) {
1235 // Check whether there is a factory method with the same
1236 // selector.
1237 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1238 = SemaRef.FactoryMethodPool.find(Instance->first);
1239
1240 if (Factory == SemaRef.FactoryMethodPool.end())
1241 Generator.insert(Instance->first,
1242 std::make_pair(Instance->second,
1243 ObjCMethodList()));
1244 else
1245 Generator.insert(Instance->first,
1246 std::make_pair(Instance->second, Factory->second));
1247
Douglas Gregor2d711832009-04-25 17:48:32 +00001248 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001249 Empty = false;
1250 }
1251
1252 // Now iterate through the factory method pool, to pick up any
1253 // selectors that weren't already in the instance method pool.
1254 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1255 Factory = SemaRef.FactoryMethodPool.begin(),
1256 FactoryEnd = SemaRef.FactoryMethodPool.end();
1257 Factory != FactoryEnd; ++Factory) {
1258 // Check whether there is an instance method with the same
1259 // selector. If so, there is no work to do here.
1260 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1261 = SemaRef.InstanceMethodPool.find(Factory->first);
1262
Douglas Gregor2d711832009-04-25 17:48:32 +00001263 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001264 Generator.insert(Factory->first,
1265 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001266 ++NumSelectorsInMethodPool;
1267 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001268
1269 Empty = false;
1270 }
1271
Douglas Gregor2d711832009-04-25 17:48:32 +00001272 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001273 return;
1274
1275 // Create the on-disk hash table in a buffer.
1276 llvm::SmallVector<char, 4096> MethodPool;
1277 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001278 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001279 {
1280 PCHMethodPoolTrait Trait(*this);
1281 llvm::raw_svector_ostream Out(MethodPool);
1282 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001283 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001284 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001285
1286 // For every selector that we have seen but which was not
1287 // written into the hash table, write the selector itself and
1288 // record it's offset.
1289 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1290 if (SelectorOffsets[I] == 0)
1291 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001292 }
1293
1294 // Create a blob abbreviation
1295 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1296 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1297 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001298 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001299 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1300 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1301
Douglas Gregor2d711832009-04-25 17:48:32 +00001302 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001303 RecordData Record;
1304 Record.push_back(pch::METHOD_POOL);
1305 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001306 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001307 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1308 &MethodPool.front(),
1309 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001310
1311 // Create a blob abbreviation for the selector table offsets.
1312 Abbrev = new BitCodeAbbrev();
1313 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1314 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1315 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1316 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1317
1318 // Write the selector offsets table.
1319 Record.clear();
1320 Record.push_back(pch::SELECTOR_OFFSETS);
1321 Record.push_back(SelectorOffsets.size());
1322 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1323 (const char *)&SelectorOffsets.front(),
1324 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001325 }
1326}
1327
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001328//===----------------------------------------------------------------------===//
1329// Identifier Table Serialization
1330//===----------------------------------------------------------------------===//
1331
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001332namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001333class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1334 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001335 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001336
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001337 /// \brief Determines whether this is an "interesting" identifier
1338 /// that needs a full IdentifierInfo structure written into the hash
1339 /// table.
1340 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1341 return II->isPoisoned() ||
1342 II->isExtensionToken() ||
1343 II->hasMacroDefinition() ||
1344 II->getObjCOrBuiltinID() ||
1345 II->getFETokenInfo<void>();
1346 }
1347
Douglas Gregorff9a6092009-04-20 20:36:09 +00001348public:
1349 typedef const IdentifierInfo* key_type;
1350 typedef key_type key_type_ref;
1351
1352 typedef pch::IdentID data_type;
1353 typedef data_type data_type_ref;
1354
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001355 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1356 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001357
1358 static unsigned ComputeHash(const IdentifierInfo* II) {
1359 return clang::BernsteinHash(II->getName());
1360 }
1361
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001362 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001363 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1364 pch::IdentID ID) {
1365 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001366 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1367 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001368 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001369 if (II->hasMacroDefinition() &&
1370 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001371 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001372 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1373 DEnd = IdentifierResolver::end();
1374 D != DEnd; ++D)
1375 DataLen += sizeof(pch::DeclID);
1376 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001377 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001378 // We emit the key length after the data length so that every
1379 // string is preceded by a 16-bit length. This matches the PTH
1380 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001381 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001382 return std::make_pair(KeyLen, DataLen);
1383 }
1384
1385 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1386 unsigned KeyLen) {
1387 // Record the location of the key data. This is used when generating
1388 // the mapping from persistent IDs to strings.
1389 Writer.SetIdentifierOffset(II, Out.tell());
1390 Out.write(II->getName(), KeyLen);
1391 }
1392
1393 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1394 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001395 if (!isInterestingIdentifier(II)) {
1396 clang::io::Emit32(Out, ID << 1);
1397 return;
1398 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001399
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001400 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001401 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001402 bool hasMacroDefinition =
1403 II->hasMacroDefinition() &&
1404 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001405 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001406 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001407 Bits = (Bits << 1) | II->isExtensionToken();
1408 Bits = (Bits << 1) | II->isPoisoned();
1409 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001410 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001411
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001412 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001413 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001414
Douglas Gregorc713da92009-04-21 22:25:48 +00001415 // Emit the declaration IDs in reverse order, because the
1416 // IdentifierResolver provides the declarations as they would be
1417 // visible (e.g., the function "stat" would come before the struct
1418 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1419 // adds declarations to the end of the list (so we need to see the
1420 // struct "status" before the function "status").
1421 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1422 IdentifierResolver::end());
1423 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1424 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001425 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001426 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001427 }
1428};
1429} // end anonymous namespace
1430
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001431/// \brief Write the identifier table into the PCH file.
1432///
1433/// The identifier table consists of a blob containing string data
1434/// (the actual identifiers themselves) and a separate "offsets" index
1435/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001436void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001437 using namespace llvm;
1438
1439 // Create and write out the blob that contains the identifier
1440 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001441 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001442 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1443
Douglas Gregor91137812009-04-28 20:33:11 +00001444 // Look for any identifiers that were named while processing the
1445 // headers, but are otherwise not needed. We add these to the hash
1446 // table to enable checking of the predefines buffer in the case
1447 // where the user adds new macro definitions when building the PCH
1448 // file.
1449 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1450 IDEnd = PP.getIdentifierTable().end();
1451 ID != IDEnd; ++ID)
1452 getIdentifierRef(ID->second);
1453
Douglas Gregorff9a6092009-04-20 20:36:09 +00001454 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001455 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001456 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1457 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1458 ID != IDEnd; ++ID) {
1459 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001460 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001461 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001462
Douglas Gregorff9a6092009-04-20 20:36:09 +00001463 // Create the on-disk hash table in a buffer.
1464 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001465 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001466 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001467 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001468 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001469 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001470 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001471 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001472 }
1473
1474 // Create a blob abbreviation
1475 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1476 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001477 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001478 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001479 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001480
1481 // Write the identifier table
1482 RecordData Record;
1483 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001484 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001485 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1486 &IdentifierTable.front(),
1487 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001488 }
1489
1490 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001491 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1492 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1493 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1494 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1495 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1496
1497 RecordData Record;
1498 Record.push_back(pch::IDENTIFIER_OFFSET);
1499 Record.push_back(IdentifierOffsets.size());
1500 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1501 (const char *)&IdentifierOffsets.front(),
1502 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001503}
1504
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001505//===----------------------------------------------------------------------===//
1506// General Serialization Routines
1507//===----------------------------------------------------------------------===//
1508
Douglas Gregor1c507882009-04-15 21:30:51 +00001509/// \brief Write a record containing the given attributes.
1510void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1511 RecordData Record;
1512 for (; Attr; Attr = Attr->getNext()) {
1513 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1514 Record.push_back(Attr->isInherited());
1515 switch (Attr->getKind()) {
1516 case Attr::Alias:
1517 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1518 break;
1519
1520 case Attr::Aligned:
1521 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1522 break;
1523
1524 case Attr::AlwaysInline:
1525 break;
1526
1527 case Attr::AnalyzerNoReturn:
1528 break;
1529
1530 case Attr::Annotate:
1531 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1532 break;
1533
1534 case Attr::AsmLabel:
1535 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1536 break;
1537
1538 case Attr::Blocks:
1539 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1540 break;
1541
1542 case Attr::Cleanup:
1543 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1544 break;
1545
1546 case Attr::Const:
1547 break;
1548
1549 case Attr::Constructor:
1550 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1551 break;
1552
1553 case Attr::DLLExport:
1554 case Attr::DLLImport:
1555 case Attr::Deprecated:
1556 break;
1557
1558 case Attr::Destructor:
1559 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1560 break;
1561
1562 case Attr::FastCall:
1563 break;
1564
1565 case Attr::Format: {
1566 const FormatAttr *Format = cast<FormatAttr>(Attr);
1567 AddString(Format->getType(), Record);
1568 Record.push_back(Format->getFormatIdx());
1569 Record.push_back(Format->getFirstArg());
1570 break;
1571 }
1572
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001573 case Attr::FormatArg: {
1574 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1575 Record.push_back(Format->getFormatIdx());
1576 break;
1577 }
1578
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001579 case Attr::Sentinel : {
1580 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1581 Record.push_back(Sentinel->getSentinel());
1582 Record.push_back(Sentinel->getNullPos());
1583 break;
1584 }
1585
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001586 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001587 case Attr::IBOutletKind:
1588 case Attr::NoReturn:
1589 case Attr::NoThrow:
1590 case Attr::Nodebug:
1591 case Attr::Noinline:
1592 break;
1593
1594 case Attr::NonNull: {
1595 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1596 Record.push_back(NonNull->size());
1597 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1598 break;
1599 }
1600
1601 case Attr::ObjCException:
1602 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001603 case Attr::CFReturnsRetained:
1604 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001605 case Attr::Overloadable:
1606 break;
1607
1608 case Attr::Packed:
1609 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1610 break;
1611
1612 case Attr::Pure:
1613 break;
1614
1615 case Attr::Regparm:
1616 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1617 break;
1618
1619 case Attr::Section:
1620 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1621 break;
1622
1623 case Attr::StdCall:
1624 case Attr::TransparentUnion:
1625 case Attr::Unavailable:
1626 case Attr::Unused:
1627 case Attr::Used:
1628 break;
1629
1630 case Attr::Visibility:
1631 // FIXME: stable encoding
1632 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1633 break;
1634
1635 case Attr::WarnUnusedResult:
1636 case Attr::Weak:
1637 case Attr::WeakImport:
1638 break;
1639 }
1640 }
1641
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001642 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001643}
1644
1645void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1646 Record.push_back(Str.size());
1647 Record.insert(Record.end(), Str.begin(), Str.end());
1648}
1649
Douglas Gregorff9a6092009-04-20 20:36:09 +00001650/// \brief Note that the identifier II occurs at the given offset
1651/// within the identifier table.
1652void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001653 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001654}
1655
Douglas Gregor2d711832009-04-25 17:48:32 +00001656/// \brief Note that the selector Sel occurs at the given offset
1657/// within the method pool/selector table.
1658void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1659 unsigned ID = SelectorIDs[Sel];
1660 assert(ID && "Unknown selector");
1661 SelectorOffsets[ID - 1] = Offset;
1662}
1663
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001664PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001665 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001666 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1667 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001668
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001669void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001670 using namespace llvm;
1671
Douglas Gregor87887da2009-04-20 15:53:59 +00001672 ASTContext &Context = SemaRef.Context;
1673 Preprocessor &PP = SemaRef.PP;
1674
Douglas Gregorc34897d2009-04-09 22:27:44 +00001675 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001676 Stream.Emit((unsigned)'C', 8);
1677 Stream.Emit((unsigned)'P', 8);
1678 Stream.Emit((unsigned)'C', 8);
1679 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001680
1681 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001682
1683 // The translation unit is the first declaration we'll emit.
1684 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1685 DeclsToEmit.push(Context.getTranslationUnitDecl());
1686
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001687 // Make sure that we emit IdentifierInfos (and any attached
1688 // declarations) for builtins.
1689 {
1690 IdentifierTable &Table = PP.getIdentifierTable();
1691 llvm::SmallVector<const char *, 32> BuiltinNames;
1692 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1693 Context.getLangOptions().NoBuiltin);
1694 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1695 getIdentifierRef(&Table.get(BuiltinNames[I]));
1696 }
1697
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001698 // Build a record containing all of the tentative definitions in
1699 // this header file. Generally, this record will be empty.
1700 RecordData TentativeDefinitions;
1701 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1702 TD = SemaRef.TentativeDefinitions.begin(),
1703 TDEnd = SemaRef.TentativeDefinitions.end();
1704 TD != TDEnd; ++TD)
1705 AddDeclRef(TD->second, TentativeDefinitions);
1706
Douglas Gregor062d9482009-04-22 22:18:58 +00001707 // Build a record containing all of the locally-scoped external
1708 // declarations in this header file. Generally, this record will be
1709 // empty.
1710 RecordData LocallyScopedExternalDecls;
1711 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1712 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1713 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1714 TD != TDEnd; ++TD)
1715 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1716
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001717 // Build a record containing all of the ext_vector declarations.
1718 RecordData ExtVectorDecls;
1719 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1720 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1721
1722 // Build a record containing all of the Objective-C category
1723 // implementations.
1724 RecordData ObjCCategoryImpls;
1725 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1726 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1727
Douglas Gregorc34897d2009-04-09 22:27:44 +00001728 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001729 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001730 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001731 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001732 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001733 if (StatCalls)
1734 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001735 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001736 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001737
1738 // Keep writing types and declarations until all types and
1739 // declarations have been written.
1740 do {
1741 if (!DeclsToEmit.empty())
1742 WriteDeclsBlock(Context);
1743 if (!TypesToEmit.empty())
1744 WriteTypesBlock(Context);
1745 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1746
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001747 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001748 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001749
1750 // Write the type offsets array
1751 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1752 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1755 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1756 Record.clear();
1757 Record.push_back(pch::TYPE_OFFSET);
1758 Record.push_back(TypeOffsets.size());
1759 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1760 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001761 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001762
1763 // Write the declaration offsets array
1764 Abbrev = new BitCodeAbbrev();
1765 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1767 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1768 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1769 Record.clear();
1770 Record.push_back(pch::DECL_OFFSET);
1771 Record.push_back(DeclOffsets.size());
1772 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1773 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001774 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001775
1776 // Write the record of special types.
1777 Record.clear();
1778 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001779 AddTypeRef(Context.getObjCIdType(), Record);
1780 AddTypeRef(Context.getObjCSelType(), Record);
1781 AddTypeRef(Context.getObjCProtoType(), Record);
1782 AddTypeRef(Context.getObjCClassType(), Record);
1783 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1784 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001785 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1786
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001787 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001788 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001789 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001790
1791 // Write the record containing tentative definitions.
1792 if (!TentativeDefinitions.empty())
1793 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001794
1795 // Write the record containing locally-scoped external definitions.
1796 if (!LocallyScopedExternalDecls.empty())
1797 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1798 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001799
1800 // Write the record containing ext_vector type names.
1801 if (!ExtVectorDecls.empty())
1802 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1803
1804 // Write the record containing Objective-C category implementations.
1805 if (!ObjCCategoryImpls.empty())
1806 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001807
1808 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001809 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001810 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001811 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001812 Record.push_back(NumLexicalDeclContexts);
1813 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001814 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001815 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001816}
1817
1818void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1819 Record.push_back(Loc.getRawEncoding());
1820}
1821
1822void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1823 Record.push_back(Value.getBitWidth());
1824 unsigned N = Value.getNumWords();
1825 const uint64_t* Words = Value.getRawData();
1826 for (unsigned I = 0; I != N; ++I)
1827 Record.push_back(Words[I]);
1828}
1829
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001830void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1831 Record.push_back(Value.isUnsigned());
1832 AddAPInt(Value, Record);
1833}
1834
Douglas Gregore2f37202009-04-14 21:55:33 +00001835void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1836 AddAPInt(Value.bitcastToAPInt(), Record);
1837}
1838
Douglas Gregorc34897d2009-04-09 22:27:44 +00001839void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001840 Record.push_back(getIdentifierRef(II));
1841}
1842
1843pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1844 if (II == 0)
1845 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001846
1847 pch::IdentID &ID = IdentifierIDs[II];
1848 if (ID == 0)
1849 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001850 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001851}
1852
Steve Naroff9e84d782009-04-23 10:39:46 +00001853void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1854 if (SelRef.getAsOpaquePtr() == 0) {
1855 Record.push_back(0);
1856 return;
1857 }
1858
1859 pch::SelectorID &SID = SelectorIDs[SelRef];
1860 if (SID == 0) {
1861 SID = SelectorIDs.size();
1862 SelVector.push_back(SelRef);
1863 }
1864 Record.push_back(SID);
1865}
1866
Douglas Gregorc34897d2009-04-09 22:27:44 +00001867void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1868 if (T.isNull()) {
1869 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1870 return;
1871 }
1872
1873 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001874 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001875 switch (BT->getKind()) {
1876 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1877 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1878 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1879 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1880 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1881 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1882 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1883 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001884 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001885 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1886 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1887 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1888 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1889 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1890 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1891 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001892 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001893 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1894 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1895 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001896 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001897 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1898 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1899 }
1900
1901 Record.push_back((ID << 3) | T.getCVRQualifiers());
1902 return;
1903 }
1904
Douglas Gregorac8f2802009-04-10 17:25:41 +00001905 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001906 if (ID == 0) {
1907 // We haven't seen this type before. Assign it a new ID and put it
1908 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001909 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001910 TypesToEmit.push(T.getTypePtr());
1911 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001912
1913 // Encode the type qualifiers in the type reference.
1914 Record.push_back((ID << 3) | T.getCVRQualifiers());
1915}
1916
1917void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1918 if (D == 0) {
1919 Record.push_back(0);
1920 return;
1921 }
1922
Douglas Gregorac8f2802009-04-10 17:25:41 +00001923 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001924 if (ID == 0) {
1925 // We haven't seen this declaration before. Give it a new ID and
1926 // enqueue it in the list of declarations to emit.
1927 ID = DeclIDs.size();
1928 DeclsToEmit.push(const_cast<Decl *>(D));
1929 }
1930
1931 Record.push_back(ID);
1932}
1933
Douglas Gregorff9a6092009-04-20 20:36:09 +00001934pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1935 if (D == 0)
1936 return 0;
1937
1938 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1939 return DeclIDs[D];
1940}
1941
Douglas Gregorc34897d2009-04-09 22:27:44 +00001942void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001943 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001944 Record.push_back(Name.getNameKind());
1945 switch (Name.getNameKind()) {
1946 case DeclarationName::Identifier:
1947 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1948 break;
1949
1950 case DeclarationName::ObjCZeroArgSelector:
1951 case DeclarationName::ObjCOneArgSelector:
1952 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001953 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001954 break;
1955
1956 case DeclarationName::CXXConstructorName:
1957 case DeclarationName::CXXDestructorName:
1958 case DeclarationName::CXXConversionFunctionName:
1959 AddTypeRef(Name.getCXXNameType(), Record);
1960 break;
1961
1962 case DeclarationName::CXXOperatorName:
1963 Record.push_back(Name.getCXXOverloadedOperator());
1964 break;
1965
1966 case DeclarationName::CXXUsingDirective:
1967 // No extra data to emit
1968 break;
1969 }
1970}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001971