blob: 6b58e250920d0bd32bb492f839820bb7cbc34a81 [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"
Chris Lattner64b65f82009-04-11 18:40:46 +000036#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000037using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// Type serialization
41//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000042
Douglas Gregorc34897d2009-04-09 22:27:44 +000043namespace {
44 class VISIBILITY_HIDDEN PCHTypeWriter {
45 PCHWriter &Writer;
46 PCHWriter::RecordData &Record;
47
48 public:
49 /// \brief Type code that corresponds to the record generated.
50 pch::TypeCode Code;
51
52 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000053 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000054
55 void VisitArrayType(const ArrayType *T);
56 void VisitFunctionType(const FunctionType *T);
57 void VisitTagType(const TagType *T);
58
59#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
60#define ABSTRACT_TYPE(Class, Base)
61#define DEPENDENT_TYPE(Class, Base)
62#include "clang/AST/TypeNodes.def"
63 };
64}
65
66void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
67 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
68 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
69 Record.push_back(T->getAddressSpace());
70 Code = pch::TYPE_EXT_QUAL;
71}
72
73void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
74 assert(false && "Built-in types are never serialized");
75}
76
77void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
78 Record.push_back(T->getWidth());
79 Record.push_back(T->isSigned());
80 Code = pch::TYPE_FIXED_WIDTH_INT;
81}
82
83void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
84 Writer.AddTypeRef(T->getElementType(), Record);
85 Code = pch::TYPE_COMPLEX;
86}
87
88void PCHTypeWriter::VisitPointerType(const PointerType *T) {
89 Writer.AddTypeRef(T->getPointeeType(), Record);
90 Code = pch::TYPE_POINTER;
91}
92
93void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
94 Writer.AddTypeRef(T->getPointeeType(), Record);
95 Code = pch::TYPE_BLOCK_POINTER;
96}
97
98void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
99 Writer.AddTypeRef(T->getPointeeType(), Record);
100 Code = pch::TYPE_LVALUE_REFERENCE;
101}
102
103void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
104 Writer.AddTypeRef(T->getPointeeType(), Record);
105 Code = pch::TYPE_RVALUE_REFERENCE;
106}
107
108void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
109 Writer.AddTypeRef(T->getPointeeType(), Record);
110 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
111 Code = pch::TYPE_MEMBER_POINTER;
112}
113
114void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
115 Writer.AddTypeRef(T->getElementType(), Record);
116 Record.push_back(T->getSizeModifier()); // FIXME: stable values
117 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
118}
119
120void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
121 VisitArrayType(T);
122 Writer.AddAPInt(T->getSize(), Record);
123 Code = pch::TYPE_CONSTANT_ARRAY;
124}
125
126void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
127 VisitArrayType(T);
128 Code = pch::TYPE_INCOMPLETE_ARRAY;
129}
130
131void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
132 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000133 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000134 Code = pch::TYPE_VARIABLE_ARRAY;
135}
136
137void PCHTypeWriter::VisitVectorType(const VectorType *T) {
138 Writer.AddTypeRef(T->getElementType(), Record);
139 Record.push_back(T->getNumElements());
140 Code = pch::TYPE_VECTOR;
141}
142
143void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
144 VisitVectorType(T);
145 Code = pch::TYPE_EXT_VECTOR;
146}
147
148void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
149 Writer.AddTypeRef(T->getResultType(), Record);
150}
151
152void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
153 VisitFunctionType(T);
154 Code = pch::TYPE_FUNCTION_NO_PROTO;
155}
156
157void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
158 VisitFunctionType(T);
159 Record.push_back(T->getNumArgs());
160 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
161 Writer.AddTypeRef(T->getArgType(I), Record);
162 Record.push_back(T->isVariadic());
163 Record.push_back(T->getTypeQuals());
164 Code = pch::TYPE_FUNCTION_PROTO;
165}
166
167void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
168 Writer.AddDeclRef(T->getDecl(), Record);
169 Code = pch::TYPE_TYPEDEF;
170}
171
172void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000173 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000174 Code = pch::TYPE_TYPEOF_EXPR;
175}
176
177void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
178 Writer.AddTypeRef(T->getUnderlyingType(), Record);
179 Code = pch::TYPE_TYPEOF;
180}
181
182void PCHTypeWriter::VisitTagType(const TagType *T) {
183 Writer.AddDeclRef(T->getDecl(), Record);
184 assert(!T->isBeingDefined() &&
185 "Cannot serialize in the middle of a type definition");
186}
187
188void PCHTypeWriter::VisitRecordType(const RecordType *T) {
189 VisitTagType(T);
190 Code = pch::TYPE_RECORD;
191}
192
193void PCHTypeWriter::VisitEnumType(const EnumType *T) {
194 VisitTagType(T);
195 Code = pch::TYPE_ENUM;
196}
197
198void
199PCHTypeWriter::VisitTemplateSpecializationType(
200 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000201 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000202 assert(false && "Cannot serialize template specialization types");
203}
204
205void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000206 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000207 assert(false && "Cannot serialize qualified name types");
208}
209
210void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
211 Writer.AddDeclRef(T->getDecl(), Record);
212 Code = pch::TYPE_OBJC_INTERFACE;
213}
214
215void
216PCHTypeWriter::VisitObjCQualifiedInterfaceType(
217 const ObjCQualifiedInterfaceType *T) {
218 VisitObjCInterfaceType(T);
219 Record.push_back(T->getNumProtocols());
220 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
221 Writer.AddDeclRef(T->getProtocol(I), Record);
222 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
223}
224
225void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
226 Record.push_back(T->getNumProtocols());
227 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
228 Writer.AddDeclRef(T->getProtocols(I), Record);
229 Code = pch::TYPE_OBJC_QUALIFIED_ID;
230}
231
Chris Lattner80f83c62009-04-22 05:57:30 +0000232//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000233// PCHWriter Implementation
234//===----------------------------------------------------------------------===//
235
Chris Lattner920673a2009-04-26 22:26:21 +0000236static void EmitBlockID(unsigned ID, const char *Name,
237 llvm::BitstreamWriter &Stream,
238 PCHWriter::RecordData &Record) {
239 Record.clear();
240 Record.push_back(ID);
241 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
242
243 // Emit the block name if present.
244 if (Name == 0 || Name[0] == 0) return;
245 Record.clear();
246 while (*Name)
247 Record.push_back(*Name++);
248 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
249}
250
251static void EmitRecordID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 while (*Name)
257 Record.push_back(*Name++);
258 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000259}
260
261static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
262 PCHWriter::RecordData &Record) {
263#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
264 RECORD(STMT_STOP);
265 RECORD(STMT_NULL_PTR);
266 RECORD(STMT_NULL);
267 RECORD(STMT_COMPOUND);
268 RECORD(STMT_CASE);
269 RECORD(STMT_DEFAULT);
270 RECORD(STMT_LABEL);
271 RECORD(STMT_IF);
272 RECORD(STMT_SWITCH);
273 RECORD(STMT_WHILE);
274 RECORD(STMT_DO);
275 RECORD(STMT_FOR);
276 RECORD(STMT_GOTO);
277 RECORD(STMT_INDIRECT_GOTO);
278 RECORD(STMT_CONTINUE);
279 RECORD(STMT_BREAK);
280 RECORD(STMT_RETURN);
281 RECORD(STMT_DECL);
282 RECORD(STMT_ASM);
283 RECORD(EXPR_PREDEFINED);
284 RECORD(EXPR_DECL_REF);
285 RECORD(EXPR_INTEGER_LITERAL);
286 RECORD(EXPR_FLOATING_LITERAL);
287 RECORD(EXPR_IMAGINARY_LITERAL);
288 RECORD(EXPR_STRING_LITERAL);
289 RECORD(EXPR_CHARACTER_LITERAL);
290 RECORD(EXPR_PAREN);
291 RECORD(EXPR_UNARY_OPERATOR);
292 RECORD(EXPR_SIZEOF_ALIGN_OF);
293 RECORD(EXPR_ARRAY_SUBSCRIPT);
294 RECORD(EXPR_CALL);
295 RECORD(EXPR_MEMBER);
296 RECORD(EXPR_BINARY_OPERATOR);
297 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
298 RECORD(EXPR_CONDITIONAL_OPERATOR);
299 RECORD(EXPR_IMPLICIT_CAST);
300 RECORD(EXPR_CSTYLE_CAST);
301 RECORD(EXPR_COMPOUND_LITERAL);
302 RECORD(EXPR_EXT_VECTOR_ELEMENT);
303 RECORD(EXPR_INIT_LIST);
304 RECORD(EXPR_DESIGNATED_INIT);
305 RECORD(EXPR_IMPLICIT_VALUE_INIT);
306 RECORD(EXPR_VA_ARG);
307 RECORD(EXPR_ADDR_LABEL);
308 RECORD(EXPR_STMT);
309 RECORD(EXPR_TYPES_COMPATIBLE);
310 RECORD(EXPR_CHOOSE);
311 RECORD(EXPR_GNU_NULL);
312 RECORD(EXPR_SHUFFLE_VECTOR);
313 RECORD(EXPR_BLOCK);
314 RECORD(EXPR_BLOCK_DECL_REF);
315 RECORD(EXPR_OBJC_STRING_LITERAL);
316 RECORD(EXPR_OBJC_ENCODE);
317 RECORD(EXPR_OBJC_SELECTOR_EXPR);
318 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
319 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
320 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
321 RECORD(EXPR_OBJC_KVC_REF_EXPR);
322 RECORD(EXPR_OBJC_MESSAGE_EXPR);
323 RECORD(EXPR_OBJC_SUPER_EXPR);
324 RECORD(STMT_OBJC_FOR_COLLECTION);
325 RECORD(STMT_OBJC_CATCH);
326 RECORD(STMT_OBJC_FINALLY);
327 RECORD(STMT_OBJC_AT_TRY);
328 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
329 RECORD(STMT_OBJC_AT_THROW);
330#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000331}
332
333void PCHWriter::WriteBlockInfoBlock() {
334 RecordData Record;
335 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
336
Chris Lattner880f3f72009-04-27 00:40:25 +0000337#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000338#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
339
340 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000341 BLOCK(PCH_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000342 RECORD(TYPE_OFFSET);
343 RECORD(DECL_OFFSET);
344 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000345 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000346 RECORD(IDENTIFIER_OFFSET);
347 RECORD(IDENTIFIER_TABLE);
348 RECORD(EXTERNAL_DEFINITIONS);
349 RECORD(SPECIAL_TYPES);
350 RECORD(STATISTICS);
351 RECORD(TENTATIVE_DEFINITIONS);
352 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
353 RECORD(SELECTOR_OFFSETS);
354 RECORD(METHOD_POOL);
355 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000356 RECORD(SOURCE_LOCATION_OFFSETS);
357 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000358 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000359 RECORD(EXT_VECTOR_DECLS);
360 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000361
Chris Lattner920673a2009-04-26 22:26:21 +0000362 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000363 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000364 RECORD(SM_SLOC_FILE_ENTRY);
365 RECORD(SM_SLOC_BUFFER_ENTRY);
366 RECORD(SM_SLOC_BUFFER_BLOB);
367 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
368 RECORD(SM_LINE_TABLE);
369 RECORD(SM_HEADER_FILE_INFO);
370
371 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000372 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000373 RECORD(PP_MACRO_OBJECT_LIKE);
374 RECORD(PP_MACRO_FUNCTION_LIKE);
375 RECORD(PP_TOKEN);
376
377 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000378 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000379 RECORD(TYPE_EXT_QUAL);
380 RECORD(TYPE_FIXED_WIDTH_INT);
381 RECORD(TYPE_COMPLEX);
382 RECORD(TYPE_POINTER);
383 RECORD(TYPE_BLOCK_POINTER);
384 RECORD(TYPE_LVALUE_REFERENCE);
385 RECORD(TYPE_RVALUE_REFERENCE);
386 RECORD(TYPE_MEMBER_POINTER);
387 RECORD(TYPE_CONSTANT_ARRAY);
388 RECORD(TYPE_INCOMPLETE_ARRAY);
389 RECORD(TYPE_VARIABLE_ARRAY);
390 RECORD(TYPE_VECTOR);
391 RECORD(TYPE_EXT_VECTOR);
392 RECORD(TYPE_FUNCTION_PROTO);
393 RECORD(TYPE_FUNCTION_NO_PROTO);
394 RECORD(TYPE_TYPEDEF);
395 RECORD(TYPE_TYPEOF_EXPR);
396 RECORD(TYPE_TYPEOF);
397 RECORD(TYPE_RECORD);
398 RECORD(TYPE_ENUM);
399 RECORD(TYPE_OBJC_INTERFACE);
400 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
401 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000402 // Statements and Exprs can occur in the Types block.
403 AddStmtsExprs(Stream, Record);
404
Chris Lattner920673a2009-04-26 22:26:21 +0000405 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000406 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000407 RECORD(DECL_ATTR);
408 RECORD(DECL_TRANSLATION_UNIT);
409 RECORD(DECL_TYPEDEF);
410 RECORD(DECL_ENUM);
411 RECORD(DECL_RECORD);
412 RECORD(DECL_ENUM_CONSTANT);
413 RECORD(DECL_FUNCTION);
414 RECORD(DECL_OBJC_METHOD);
415 RECORD(DECL_OBJC_INTERFACE);
416 RECORD(DECL_OBJC_PROTOCOL);
417 RECORD(DECL_OBJC_IVAR);
418 RECORD(DECL_OBJC_AT_DEFS_FIELD);
419 RECORD(DECL_OBJC_CLASS);
420 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
421 RECORD(DECL_OBJC_CATEGORY);
422 RECORD(DECL_OBJC_CATEGORY_IMPL);
423 RECORD(DECL_OBJC_IMPLEMENTATION);
424 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
425 RECORD(DECL_OBJC_PROPERTY);
426 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000427 RECORD(DECL_FIELD);
428 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000429 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000430 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000431 RECORD(DECL_ORIGINAL_PARM_VAR);
432 RECORD(DECL_FILE_SCOPE_ASM);
433 RECORD(DECL_BLOCK);
434 RECORD(DECL_CONTEXT_LEXICAL);
435 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000436 // Statements and Exprs can occur in the Decls block.
437 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000438#undef RECORD
439#undef BLOCK
440 Stream.ExitBlock();
441}
442
443
Douglas Gregorb7064742009-04-27 22:23:34 +0000444/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
445void PCHWriter::WriteMetadata(const TargetInfo &Target) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000446 using namespace llvm;
447 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Douglas Gregorb7064742009-04-27 22:23:34 +0000448 Abbrev->Add(BitCodeAbbrevOp(pch::METADATA));
449 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
454 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000455
456 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000457 Record.push_back(pch::METADATA);
458 Record.push_back(pch::VERSION_MAJOR);
459 Record.push_back(pch::VERSION_MINOR);
460 Record.push_back(CLANG_VERSION_MAJOR);
461 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000462 const char *Triple = Target.getTargetTriple();
Douglas Gregorb7064742009-04-27 22:23:34 +0000463 Stream.EmitRecordWithBlob(AbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000464}
465
466/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000467void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
468 RecordData Record;
469 Record.push_back(LangOpts.Trigraphs);
470 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
471 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
472 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
473 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
474 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
475 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
476 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
477 Record.push_back(LangOpts.C99); // C99 Support
478 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
479 Record.push_back(LangOpts.CPlusPlus); // C++ Support
480 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
481 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
482 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
483
484 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
485 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
486 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
487
488 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
489 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
490 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
491 Record.push_back(LangOpts.LaxVectorConversions);
492 Record.push_back(LangOpts.Exceptions); // Support exception handling.
493
494 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
495 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
496 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
497
Chris Lattnercd4da472009-04-27 07:35:58 +0000498 // Whether static initializers are protected by locks.
499 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000500 Record.push_back(LangOpts.Blocks); // block extension to C
501 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
502 // they are unused.
503 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
504 // (modulo the platform support).
505
506 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
507 // signed integer arithmetic overflows.
508
509 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
510 // may be ripped out at any time.
511
512 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
513 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
514 // defined.
515 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
516 // opposed to __DYNAMIC__).
517 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
518
519 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
520 // used (instead of C99 semantics).
521 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
522 Record.push_back(LangOpts.getGCMode());
523 Record.push_back(LangOpts.getVisibilityMode());
524 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000525 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000526}
527
Douglas Gregorab1cef72009-04-10 03:52:48 +0000528//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000529// stat cache Serialization
530//===----------------------------------------------------------------------===//
531
532namespace {
533// Trait used for the on-disk hash table of stat cache results.
534class VISIBILITY_HIDDEN PCHStatCacheTrait {
535public:
536 typedef const char * key_type;
537 typedef key_type key_type_ref;
538
539 typedef std::pair<int, struct stat> data_type;
540 typedef const data_type& data_type_ref;
541
542 static unsigned ComputeHash(const char *path) {
543 return BernsteinHash(path);
544 }
545
546 std::pair<unsigned,unsigned>
547 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
548 data_type_ref Data) {
549 unsigned StrLen = strlen(path);
550 clang::io::Emit16(Out, StrLen);
551 unsigned DataLen = 1; // result value
552 if (Data.first == 0)
553 DataLen += 4 + 4 + 2 + 8 + 8;
554 clang::io::Emit8(Out, DataLen);
555 return std::make_pair(StrLen + 1, DataLen);
556 }
557
558 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
559 Out.write(path, KeyLen);
560 }
561
562 void EmitData(llvm::raw_ostream& Out, key_type_ref,
563 data_type_ref Data, unsigned DataLen) {
564 using namespace clang::io;
565 uint64_t Start = Out.tell(); (void)Start;
566
567 // Result of stat()
568 Emit8(Out, Data.first? 1 : 0);
569
570 if (Data.first == 0) {
571 Emit32(Out, (uint32_t) Data.second.st_ino);
572 Emit32(Out, (uint32_t) Data.second.st_dev);
573 Emit16(Out, (uint16_t) Data.second.st_mode);
574 Emit64(Out, (uint64_t) Data.second.st_mtime);
575 Emit64(Out, (uint64_t) Data.second.st_size);
576 }
577
578 assert(Out.tell() - Start == DataLen && "Wrong data length");
579 }
580};
581} // end anonymous namespace
582
583/// \brief Write the stat() system call cache to the PCH file.
584void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
585 // Build the on-disk hash table containing information about every
586 // stat() call.
587 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
588 unsigned NumStatEntries = 0;
589 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
590 StatEnd = StatCalls.end();
591 Stat != StatEnd; ++Stat, ++NumStatEntries)
592 Generator.insert(Stat->first(), Stat->second);
593
594 // Create the on-disk hash table in a buffer.
595 llvm::SmallVector<char, 4096> StatCacheData;
596 uint32_t BucketOffset;
597 {
598 llvm::raw_svector_ostream Out(StatCacheData);
599 // Make sure that no bucket is at offset 0
600 clang::io::Emit32(Out, 0);
601 BucketOffset = Generator.Emit(Out);
602 }
603
604 // Create a blob abbreviation
605 using namespace llvm;
606 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
607 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
611 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
612
613 // Write the stat cache
614 RecordData Record;
615 Record.push_back(pch::STAT_CACHE);
616 Record.push_back(BucketOffset);
617 Record.push_back(NumStatEntries);
618 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
619 &StatCacheData.front(),
620 StatCacheData.size());
621}
622
623//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000624// Source Manager Serialization
625//===----------------------------------------------------------------------===//
626
627/// \brief Create an abbreviation for the SLocEntry that refers to a
628/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000629static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000630 using namespace llvm;
631 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
632 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
634 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000638 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000639}
640
641/// \brief Create an abbreviation for the SLocEntry that refers to a
642/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000643static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000644 using namespace llvm;
645 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
646 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000652 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000653}
654
655/// \brief Create an abbreviation for the SLocEntry that refers to a
656/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000657static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000658 using namespace llvm;
659 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
660 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000662 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000663}
664
665/// \brief Create an abbreviation for the SLocEntry that refers to an
666/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000667static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000668 using namespace llvm;
669 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
670 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
671 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000676 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000677}
678
679/// \brief Writes the block containing the serialized form of the
680/// source manager.
681///
682/// TODO: We should probably use an on-disk hash table (stored in a
683/// blob), indexed based on the file name, so that we only create
684/// entries for files that we actually need. In the common case (no
685/// errors), we probably won't have to create file entries for any of
686/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000687void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
688 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000689 RecordData Record;
690
Chris Lattner84b04f12009-04-10 17:16:57 +0000691 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000692 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000693
694 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000695 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
696 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
697 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
698 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000699
Douglas Gregor635f97f2009-04-13 16:31:14 +0000700 // Write the line table.
701 if (SourceMgr.hasLineTable()) {
702 LineTableInfo &LineTable = SourceMgr.getLineTable();
703
704 // Emit the file names
705 Record.push_back(LineTable.getNumFilenames());
706 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
707 // Emit the file name
708 const char *Filename = LineTable.getFilename(I);
709 unsigned FilenameLen = Filename? strlen(Filename) : 0;
710 Record.push_back(FilenameLen);
711 if (FilenameLen)
712 Record.insert(Record.end(), Filename, Filename + FilenameLen);
713 }
714
715 // Emit the line entries
716 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
717 L != LEnd; ++L) {
718 // Emit the file ID
719 Record.push_back(L->first);
720
721 // Emit the line entries
722 Record.push_back(L->second.size());
723 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
724 LEEnd = L->second.end();
725 LE != LEEnd; ++LE) {
726 Record.push_back(LE->FileOffset);
727 Record.push_back(LE->LineNo);
728 Record.push_back(LE->FilenameID);
729 Record.push_back((unsigned)LE->FileKind);
730 Record.push_back(LE->IncludeOffset);
731 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000732 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000733 }
734 }
735
Douglas Gregor32e231c2009-04-27 06:38:32 +0000736 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000737 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000738 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000739 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
740 E = HS.header_file_end();
741 I != E; ++I) {
742 Record.push_back(I->isImport);
743 Record.push_back(I->DirInfo);
744 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000745 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000746 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
747 Record.clear();
748 }
749
Douglas Gregor32e231c2009-04-27 06:38:32 +0000750 // Write out the source location entry table. We skip the first
751 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000752 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000753 RecordData PreloadSLocs;
754 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
755 for (SourceManager::sloc_entry_iterator
756 SLoc = SourceMgr.sloc_entry_begin() + 1,
757 SLocEnd = SourceMgr.sloc_entry_end();
758 SLoc != SLocEnd; ++SLoc) {
759 // Record the offset of this source-location entry.
760 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
761
762 // Figure out which record code to use.
763 unsigned Code;
764 if (SLoc->isFile()) {
765 if (SLoc->getFile().getContentCache()->Entry)
766 Code = pch::SM_SLOC_FILE_ENTRY;
767 else
768 Code = pch::SM_SLOC_BUFFER_ENTRY;
769 } else
770 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
771 Record.clear();
772 Record.push_back(Code);
773
774 Record.push_back(SLoc->getOffset());
775 if (SLoc->isFile()) {
776 const SrcMgr::FileInfo &File = SLoc->getFile();
777 Record.push_back(File.getIncludeLoc().getRawEncoding());
778 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
779 Record.push_back(File.hasLineDirectives());
780
781 const SrcMgr::ContentCache *Content = File.getContentCache();
782 if (Content->Entry) {
783 // The source location entry is a file. The blob associated
784 // with this entry is the file name.
785 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
786 Content->Entry->getName(),
787 strlen(Content->Entry->getName()));
788
789 // FIXME: For now, preload all file source locations, so that
790 // we get the appropriate File entries in the reader. This is
791 // a temporary measure.
792 PreloadSLocs.push_back(SLocEntryOffsets.size());
793 } else {
794 // The source location entry is a buffer. The blob associated
795 // with this entry contains the contents of the buffer.
796
797 // We add one to the size so that we capture the trailing NULL
798 // that is required by llvm::MemoryBuffer::getMemBuffer (on
799 // the reader side).
800 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
801 const char *Name = Buffer->getBufferIdentifier();
802 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
803 Record.clear();
804 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
805 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
806 Buffer->getBufferStart(),
807 Buffer->getBufferSize() + 1);
808
809 if (strcmp(Name, "<built-in>") == 0)
810 PreloadSLocs.push_back(SLocEntryOffsets.size());
811 }
812 } else {
813 // The source location entry is an instantiation.
814 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
815 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
816 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
817 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
818
819 // Compute the token length for this macro expansion.
820 unsigned NextOffset = SourceMgr.getNextOffset();
821 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
822 if (++NextSLoc != SLocEnd)
823 NextOffset = NextSLoc->getOffset();
824 Record.push_back(NextOffset - SLoc->getOffset() - 1);
825 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
826 }
827 }
828
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000829 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000830
831 if (SLocEntryOffsets.empty())
832 return;
833
834 // Write the source-location offsets table into the PCH block. This
835 // table is used for lazily loading source-location information.
836 using namespace llvm;
837 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
838 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
842 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
843
844 Record.clear();
845 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
846 Record.push_back(SLocEntryOffsets.size());
847 Record.push_back(SourceMgr.getNextOffset());
848 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
849 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000850 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000851
852 // Write the source location entry preloads array, telling the PCH
853 // reader which source locations entries it should load eagerly.
854 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000855}
856
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000857//===----------------------------------------------------------------------===//
858// Preprocessor Serialization
859//===----------------------------------------------------------------------===//
860
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000861/// \brief Writes the block containing the serialized form of the
862/// preprocessor.
863///
Chris Lattner850eabd2009-04-10 18:08:30 +0000864void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000865 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000866
Chris Lattner4b21c202009-04-13 01:29:17 +0000867 // If the preprocessor __COUNTER__ value has been bumped, remember it.
868 if (PP.getCounterValue() != 0) {
869 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000870 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000871 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000872 }
873
874 // Enter the preprocessor block.
875 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000876
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000877 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
878 // FIXME: use diagnostics subsystem for localization etc.
879 if (PP.SawDateOrTime())
880 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
881
Chris Lattner1b094952009-04-10 18:00:12 +0000882 // Loop over all the macro definitions that are live at the end of the file,
883 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000884 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
885 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000886 // FIXME: This emits macros in hash table order, we should do it in a stable
887 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000888 MacroInfo *MI = I->second;
889
890 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
891 // been redefined by the header (in which case they are not isBuiltinMacro).
892 if (MI->isBuiltinMacro())
893 continue;
894
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000895 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000896 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000897 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000898 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
899 Record.push_back(MI->isUsed());
900
901 unsigned Code;
902 if (MI->isObjectLike()) {
903 Code = pch::PP_MACRO_OBJECT_LIKE;
904 } else {
905 Code = pch::PP_MACRO_FUNCTION_LIKE;
906
907 Record.push_back(MI->isC99Varargs());
908 Record.push_back(MI->isGNUVarargs());
909 Record.push_back(MI->getNumArgs());
910 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
911 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000912 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000913 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000914 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000915 Record.clear();
916
Chris Lattner850eabd2009-04-10 18:08:30 +0000917 // Emit the tokens array.
918 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
919 // Note that we know that the preprocessor does not have any annotation
920 // tokens in it because they are created by the parser, and thus can't be
921 // in a macro definition.
922 const Token &Tok = MI->getReplacementToken(TokNo);
923
924 Record.push_back(Tok.getLocation().getRawEncoding());
925 Record.push_back(Tok.getLength());
926
Chris Lattner850eabd2009-04-10 18:08:30 +0000927 // FIXME: When reading literal tokens, reconstruct the literal pointer if
928 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000929 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000930
931 // FIXME: Should translate token kind to a stable encoding.
932 Record.push_back(Tok.getKind());
933 // FIXME: Should translate token flags to a stable encoding.
934 Record.push_back(Tok.getFlags());
935
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000936 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000937 Record.clear();
938 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000939 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000940 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000941 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000942}
943
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000944//===----------------------------------------------------------------------===//
945// Type Serialization
946//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000947
Douglas Gregorc34897d2009-04-09 22:27:44 +0000948/// \brief Write the representation of a type to the PCH stream.
949void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000950 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000951 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000952 ID = NextTypeID++;
953
954 // Record the offset for this type.
955 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000956 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000957 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
958 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000959 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000960 }
961
962 RecordData Record;
963
964 // Emit the type's representation.
965 PCHTypeWriter W(*this, Record);
966 switch (T->getTypeClass()) {
967 // For all of the concrete, non-dependent types, call the
968 // appropriate visitor function.
969#define TYPE(Class, Base) \
970 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
971#define ABSTRACT_TYPE(Class, Base)
972#define DEPENDENT_TYPE(Class, Base)
973#include "clang/AST/TypeNodes.def"
974
975 // For all of the dependent type nodes (which only occur in C++
976 // templates), produce an error.
977#define TYPE(Class, Base)
978#define DEPENDENT_TYPE(Class, Base) case Type::Class:
979#include "clang/AST/TypeNodes.def"
980 assert(false && "Cannot serialize dependent type nodes");
981 break;
982 }
983
984 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000985 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000986
987 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000988 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000989}
990
991/// \brief Write a block containing all of the types.
992void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000993 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000994 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000995
Douglas Gregore43f0972009-04-26 03:49:13 +0000996 // Emit all of the types that need to be emitted (so far).
997 while (!TypesToEmit.empty()) {
998 const Type *T = TypesToEmit.front();
999 TypesToEmit.pop();
1000 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1001 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001002 }
1003
1004 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001005 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001006}
1007
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001008//===----------------------------------------------------------------------===//
1009// Declaration Serialization
1010//===----------------------------------------------------------------------===//
1011
Douglas Gregorc34897d2009-04-09 22:27:44 +00001012/// \brief Write the block containing all of the declaration IDs
1013/// lexically declared within the given DeclContext.
1014///
1015/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1016/// bistream, or 0 if no block was written.
1017uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1018 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001019 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001020 return 0;
1021
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001022 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001023 RecordData Record;
1024 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1025 DEnd = DC->decls_end(Context);
1026 D != DEnd; ++D)
1027 AddDeclRef(*D, Record);
1028
Douglas Gregoraf136d92009-04-22 22:34:57 +00001029 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001030 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001031 return Offset;
1032}
1033
1034/// \brief Write the block containing all of the declaration IDs
1035/// visible from the given DeclContext.
1036///
1037/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1038/// bistream, or 0 if no block was written.
1039uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1040 DeclContext *DC) {
1041 if (DC->getPrimaryContext() != DC)
1042 return 0;
1043
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001044 // Since there is no name lookup into functions or methods, and we
1045 // perform name lookup for the translation unit via the
1046 // IdentifierInfo chains, don't bother to build a
1047 // visible-declarations table for these entities.
1048 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001049 return 0;
1050
Douglas Gregorc34897d2009-04-09 22:27:44 +00001051 // Force the DeclContext to build a its name-lookup table.
1052 DC->lookup(Context, DeclarationName());
1053
1054 // Serialize the contents of the mapping used for lookup. Note that,
1055 // although we have two very different code paths, the serialized
1056 // representation is the same for both cases: a declaration name,
1057 // followed by a size, followed by references to the visible
1058 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001059 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001060 RecordData Record;
1061 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001062 if (!Map)
1063 return 0;
1064
Douglas Gregorc34897d2009-04-09 22:27:44 +00001065 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1066 D != DEnd; ++D) {
1067 AddDeclarationName(D->first, Record);
1068 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1069 Record.push_back(Result.second - Result.first);
1070 for(; Result.first != Result.second; ++Result.first)
1071 AddDeclRef(*Result.first, Record);
1072 }
1073
1074 if (Record.size() == 0)
1075 return 0;
1076
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001077 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001078 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001079 return Offset;
1080}
1081
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001082//===----------------------------------------------------------------------===//
1083// Global Method Pool and Selector Serialization
1084//===----------------------------------------------------------------------===//
1085
Douglas Gregorff9a6092009-04-20 20:36:09 +00001086namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001087// Trait used for the on-disk hash table used in the method pool.
1088class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1089 PCHWriter &Writer;
1090
1091public:
1092 typedef Selector key_type;
1093 typedef key_type key_type_ref;
1094
1095 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1096 typedef const data_type& data_type_ref;
1097
1098 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1099
1100 static unsigned ComputeHash(Selector Sel) {
1101 unsigned N = Sel.getNumArgs();
1102 if (N == 0)
1103 ++N;
1104 unsigned R = 5381;
1105 for (unsigned I = 0; I != N; ++I)
1106 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1107 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1108 return R;
1109 }
1110
1111 std::pair<unsigned,unsigned>
1112 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1113 data_type_ref Methods) {
1114 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1115 clang::io::Emit16(Out, KeyLen);
1116 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1117 for (const ObjCMethodList *Method = &Methods.first; Method;
1118 Method = Method->Next)
1119 if (Method->Method)
1120 DataLen += 4;
1121 for (const ObjCMethodList *Method = &Methods.second; Method;
1122 Method = Method->Next)
1123 if (Method->Method)
1124 DataLen += 4;
1125 clang::io::Emit16(Out, DataLen);
1126 return std::make_pair(KeyLen, DataLen);
1127 }
1128
Douglas Gregor2d711832009-04-25 17:48:32 +00001129 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1130 uint64_t Start = Out.tell();
1131 assert((Start >> 32) == 0 && "Selector key offset too large");
1132 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001133 unsigned N = Sel.getNumArgs();
1134 clang::io::Emit16(Out, N);
1135 if (N == 0)
1136 N = 1;
1137 for (unsigned I = 0; I != N; ++I)
1138 clang::io::Emit32(Out,
1139 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1140 }
1141
1142 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001143 data_type_ref Methods, unsigned DataLen) {
1144 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001145 unsigned NumInstanceMethods = 0;
1146 for (const ObjCMethodList *Method = &Methods.first; Method;
1147 Method = Method->Next)
1148 if (Method->Method)
1149 ++NumInstanceMethods;
1150
1151 unsigned NumFactoryMethods = 0;
1152 for (const ObjCMethodList *Method = &Methods.second; Method;
1153 Method = Method->Next)
1154 if (Method->Method)
1155 ++NumFactoryMethods;
1156
1157 clang::io::Emit16(Out, NumInstanceMethods);
1158 clang::io::Emit16(Out, NumFactoryMethods);
1159 for (const ObjCMethodList *Method = &Methods.first; Method;
1160 Method = Method->Next)
1161 if (Method->Method)
1162 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001163 for (const ObjCMethodList *Method = &Methods.second; Method;
1164 Method = Method->Next)
1165 if (Method->Method)
1166 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001167
1168 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001169 }
1170};
1171} // end anonymous namespace
1172
1173/// \brief Write the method pool into the PCH file.
1174///
1175/// The method pool contains both instance and factory methods, stored
1176/// in an on-disk hash table indexed by the selector.
1177void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1178 using namespace llvm;
1179
1180 // Create and write out the blob that contains the instance and
1181 // factor method pools.
1182 bool Empty = true;
1183 {
1184 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1185
1186 // Create the on-disk hash table representation. Start by
1187 // iterating through the instance method pool.
1188 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001189 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001190 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1191 Instance = SemaRef.InstanceMethodPool.begin(),
1192 InstanceEnd = SemaRef.InstanceMethodPool.end();
1193 Instance != InstanceEnd; ++Instance) {
1194 // Check whether there is a factory method with the same
1195 // selector.
1196 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1197 = SemaRef.FactoryMethodPool.find(Instance->first);
1198
1199 if (Factory == SemaRef.FactoryMethodPool.end())
1200 Generator.insert(Instance->first,
1201 std::make_pair(Instance->second,
1202 ObjCMethodList()));
1203 else
1204 Generator.insert(Instance->first,
1205 std::make_pair(Instance->second, Factory->second));
1206
Douglas Gregor2d711832009-04-25 17:48:32 +00001207 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001208 Empty = false;
1209 }
1210
1211 // Now iterate through the factory method pool, to pick up any
1212 // selectors that weren't already in the instance method pool.
1213 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1214 Factory = SemaRef.FactoryMethodPool.begin(),
1215 FactoryEnd = SemaRef.FactoryMethodPool.end();
1216 Factory != FactoryEnd; ++Factory) {
1217 // Check whether there is an instance method with the same
1218 // selector. If so, there is no work to do here.
1219 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1220 = SemaRef.InstanceMethodPool.find(Factory->first);
1221
Douglas Gregor2d711832009-04-25 17:48:32 +00001222 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001223 Generator.insert(Factory->first,
1224 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001225 ++NumSelectorsInMethodPool;
1226 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001227
1228 Empty = false;
1229 }
1230
Douglas Gregor2d711832009-04-25 17:48:32 +00001231 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001232 return;
1233
1234 // Create the on-disk hash table in a buffer.
1235 llvm::SmallVector<char, 4096> MethodPool;
1236 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001237 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001238 {
1239 PCHMethodPoolTrait Trait(*this);
1240 llvm::raw_svector_ostream Out(MethodPool);
1241 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001242 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001243 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001244
1245 // For every selector that we have seen but which was not
1246 // written into the hash table, write the selector itself and
1247 // record it's offset.
1248 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1249 if (SelectorOffsets[I] == 0)
1250 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001251 }
1252
1253 // Create a blob abbreviation
1254 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1255 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001258 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1259 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1260
Douglas Gregor2d711832009-04-25 17:48:32 +00001261 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001262 RecordData Record;
1263 Record.push_back(pch::METHOD_POOL);
1264 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001265 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001266 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1267 &MethodPool.front(),
1268 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001269
1270 // Create a blob abbreviation for the selector table offsets.
1271 Abbrev = new BitCodeAbbrev();
1272 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1273 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1274 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1275 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1276
1277 // Write the selector offsets table.
1278 Record.clear();
1279 Record.push_back(pch::SELECTOR_OFFSETS);
1280 Record.push_back(SelectorOffsets.size());
1281 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1282 (const char *)&SelectorOffsets.front(),
1283 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001284 }
1285}
1286
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001287//===----------------------------------------------------------------------===//
1288// Identifier Table Serialization
1289//===----------------------------------------------------------------------===//
1290
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001291namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001292class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1293 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001294 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001295
1296public:
1297 typedef const IdentifierInfo* key_type;
1298 typedef key_type key_type_ref;
1299
1300 typedef pch::IdentID data_type;
1301 typedef data_type data_type_ref;
1302
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001303 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1304 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001305
1306 static unsigned ComputeHash(const IdentifierInfo* II) {
1307 return clang::BernsteinHash(II->getName());
1308 }
1309
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001310 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001311 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1312 pch::IdentID ID) {
1313 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregorc713da92009-04-21 22:25:48 +00001314 unsigned DataLen = 4 + 4; // 4 bytes for token ID, builtin, flags
1315 // 4 bytes for the persistent ID
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001316 if (II->hasMacroDefinition() &&
1317 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1318 DataLen += 8;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001319 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1320 DEnd = IdentifierResolver::end();
1321 D != DEnd; ++D)
1322 DataLen += sizeof(pch::DeclID);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001323 // We emit the key length after the data length so that the
1324 // "uninteresting" identifiers following the identifier hash table
1325 // structure will have the same (key length, key characters)
1326 // layout as the keys in the hash table. This also matches the
1327 // format for identifiers in pretokenized headers.
Douglas Gregorc713da92009-04-21 22:25:48 +00001328 clang::io::Emit16(Out, DataLen);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001329 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001330 return std::make_pair(KeyLen, DataLen);
1331 }
1332
1333 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1334 unsigned KeyLen) {
1335 // Record the location of the key data. This is used when generating
1336 // the mapping from persistent IDs to strings.
1337 Writer.SetIdentifierOffset(II, Out.tell());
1338 Out.write(II->getName(), KeyLen);
1339 }
1340
1341 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1342 pch::IdentID ID, unsigned) {
1343 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001344 bool hasMacroDefinition =
1345 II->hasMacroDefinition() &&
1346 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001347 Bits = Bits | (uint32_t)II->getTokenID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001348 Bits = (Bits << 10) | (uint32_t)II->getObjCOrBuiltinID();
1349 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001350 Bits = (Bits << 1) | II->isExtensionToken();
1351 Bits = (Bits << 1) | II->isPoisoned();
1352 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
1353 clang::io::Emit32(Out, Bits);
1354 clang::io::Emit32(Out, ID);
1355
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001356 if (hasMacroDefinition)
1357 clang::io::Emit64(Out, Writer.getMacroOffset(II));
1358
Douglas Gregorc713da92009-04-21 22:25:48 +00001359 // Emit the declaration IDs in reverse order, because the
1360 // IdentifierResolver provides the declarations as they would be
1361 // visible (e.g., the function "stat" would come before the struct
1362 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1363 // adds declarations to the end of the list (so we need to see the
1364 // struct "status" before the function "status").
1365 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1366 IdentifierResolver::end());
1367 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1368 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001369 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001370 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001371 }
1372};
1373} // end anonymous namespace
1374
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001375/// \brief Write the identifier table into the PCH file.
1376///
1377/// The identifier table consists of a blob containing string data
1378/// (the actual identifiers themselves) and a separate "offsets" index
1379/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001380void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001381 using namespace llvm;
1382
1383 // Create and write out the blob that contains the identifier
1384 // strings.
Douglas Gregorff9a6092009-04-20 20:36:09 +00001385 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001386 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001387 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1388
Douglas Gregor85c4a872009-04-25 21:04:17 +00001389 llvm::SmallVector<const IdentifierInfo *, 32> UninterestingIdentifiers;
1390
Douglas Gregorff9a6092009-04-20 20:36:09 +00001391 // Create the on-disk hash table representation.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001392 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1393 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1394 ID != IDEnd; ++ID) {
1395 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor85c4a872009-04-25 21:04:17 +00001396
1397 // Classify each identifier as either "interesting" or "not
1398 // interesting". Interesting identifiers are those that have
1399 // additional information that needs to be read from the PCH
1400 // file, e.g., a built-in ID, declaration chain, or macro
1401 // definition. These identifiers are placed into the hash table
1402 // so that they can be found when looked up in the user program.
1403 // All other identifiers are "uninteresting", which means that
1404 // the IdentifierInfo built by default has all of the
1405 // information we care about. Such identifiers are placed after
1406 // the hash table.
1407 const IdentifierInfo *II = ID->first;
1408 if (II->isPoisoned() ||
1409 II->isExtensionToken() ||
1410 II->hasMacroDefinition() ||
1411 II->getObjCOrBuiltinID() ||
1412 II->getFETokenInfo<void>())
1413 Generator.insert(ID->first, ID->second);
1414 else
1415 UninterestingIdentifiers.push_back(II);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001416 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001417
Douglas Gregorff9a6092009-04-20 20:36:09 +00001418 // Create the on-disk hash table in a buffer.
1419 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001420 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001421 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001422 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001423 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001424 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001425 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001426 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001427
1428 for (unsigned I = 0, N = UninterestingIdentifiers.size(); I != N; ++I) {
1429 const IdentifierInfo *II = UninterestingIdentifiers[I];
1430 unsigned N = II->getLength() + 1;
1431 clang::io::Emit16(Out, N);
1432 SetIdentifierOffset(II, Out.tell());
1433 Out.write(II->getName(), N);
1434 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001435 }
1436
1437 // Create a blob abbreviation
1438 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1439 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001440 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001441 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001442 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001443
1444 // Write the identifier table
1445 RecordData Record;
1446 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001447 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001448 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1449 &IdentifierTable.front(),
1450 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001451 }
1452
1453 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001454 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1455 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1458 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1459
1460 RecordData Record;
1461 Record.push_back(pch::IDENTIFIER_OFFSET);
1462 Record.push_back(IdentifierOffsets.size());
1463 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1464 (const char *)&IdentifierOffsets.front(),
1465 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001466}
1467
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001468//===----------------------------------------------------------------------===//
1469// General Serialization Routines
1470//===----------------------------------------------------------------------===//
1471
Douglas Gregor1c507882009-04-15 21:30:51 +00001472/// \brief Write a record containing the given attributes.
1473void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1474 RecordData Record;
1475 for (; Attr; Attr = Attr->getNext()) {
1476 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1477 Record.push_back(Attr->isInherited());
1478 switch (Attr->getKind()) {
1479 case Attr::Alias:
1480 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1481 break;
1482
1483 case Attr::Aligned:
1484 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1485 break;
1486
1487 case Attr::AlwaysInline:
1488 break;
1489
1490 case Attr::AnalyzerNoReturn:
1491 break;
1492
1493 case Attr::Annotate:
1494 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1495 break;
1496
1497 case Attr::AsmLabel:
1498 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1499 break;
1500
1501 case Attr::Blocks:
1502 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1503 break;
1504
1505 case Attr::Cleanup:
1506 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1507 break;
1508
1509 case Attr::Const:
1510 break;
1511
1512 case Attr::Constructor:
1513 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1514 break;
1515
1516 case Attr::DLLExport:
1517 case Attr::DLLImport:
1518 case Attr::Deprecated:
1519 break;
1520
1521 case Attr::Destructor:
1522 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1523 break;
1524
1525 case Attr::FastCall:
1526 break;
1527
1528 case Attr::Format: {
1529 const FormatAttr *Format = cast<FormatAttr>(Attr);
1530 AddString(Format->getType(), Record);
1531 Record.push_back(Format->getFormatIdx());
1532 Record.push_back(Format->getFirstArg());
1533 break;
1534 }
1535
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001536 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001537 case Attr::IBOutletKind:
1538 case Attr::NoReturn:
1539 case Attr::NoThrow:
1540 case Attr::Nodebug:
1541 case Attr::Noinline:
1542 break;
1543
1544 case Attr::NonNull: {
1545 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1546 Record.push_back(NonNull->size());
1547 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1548 break;
1549 }
1550
1551 case Attr::ObjCException:
1552 case Attr::ObjCNSObject:
Ted Kremenek203169f2009-04-27 19:36:56 +00001553 case Attr::ObjCOwnershipCFRelease:
1554 case Attr::ObjCOwnershipRelease:
Ted Kremenek15830ed2009-04-27 18:27:22 +00001555 case Attr::ObjCOwnershipCFRetain:
Ted Kremenekb98860c2009-04-25 00:17:17 +00001556 case Attr::ObjCOwnershipRetain:
Ted Kremenekaa6e3182009-04-24 23:09:54 +00001557 case Attr::ObjCOwnershipReturns:
Douglas Gregor1c507882009-04-15 21:30:51 +00001558 case Attr::Overloadable:
1559 break;
1560
1561 case Attr::Packed:
1562 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1563 break;
1564
1565 case Attr::Pure:
1566 break;
1567
1568 case Attr::Regparm:
1569 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1570 break;
1571
1572 case Attr::Section:
1573 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1574 break;
1575
1576 case Attr::StdCall:
1577 case Attr::TransparentUnion:
1578 case Attr::Unavailable:
1579 case Attr::Unused:
1580 case Attr::Used:
1581 break;
1582
1583 case Attr::Visibility:
1584 // FIXME: stable encoding
1585 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1586 break;
1587
1588 case Attr::WarnUnusedResult:
1589 case Attr::Weak:
1590 case Attr::WeakImport:
1591 break;
1592 }
1593 }
1594
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001595 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001596}
1597
1598void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1599 Record.push_back(Str.size());
1600 Record.insert(Record.end(), Str.begin(), Str.end());
1601}
1602
Douglas Gregorff9a6092009-04-20 20:36:09 +00001603/// \brief Note that the identifier II occurs at the given offset
1604/// within the identifier table.
1605void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001606 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001607}
1608
Douglas Gregor2d711832009-04-25 17:48:32 +00001609/// \brief Note that the selector Sel occurs at the given offset
1610/// within the method pool/selector table.
1611void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1612 unsigned ID = SelectorIDs[Sel];
1613 assert(ID && "Unknown selector");
1614 SelectorOffsets[ID - 1] = Offset;
1615}
1616
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001617PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001618 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001619 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1620 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001621
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001622void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001623 using namespace llvm;
1624
Douglas Gregor87887da2009-04-20 15:53:59 +00001625 ASTContext &Context = SemaRef.Context;
1626 Preprocessor &PP = SemaRef.PP;
1627
Douglas Gregorc34897d2009-04-09 22:27:44 +00001628 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001629 Stream.Emit((unsigned)'C', 8);
1630 Stream.Emit((unsigned)'P', 8);
1631 Stream.Emit((unsigned)'C', 8);
1632 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001633
1634 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001635
1636 // The translation unit is the first declaration we'll emit.
1637 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1638 DeclsToEmit.push(Context.getTranslationUnitDecl());
1639
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001640 // Make sure that we emit IdentifierInfos (and any attached
1641 // declarations) for builtins.
1642 {
1643 IdentifierTable &Table = PP.getIdentifierTable();
1644 llvm::SmallVector<const char *, 32> BuiltinNames;
1645 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1646 Context.getLangOptions().NoBuiltin);
1647 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1648 getIdentifierRef(&Table.get(BuiltinNames[I]));
1649 }
1650
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001651 // Build a record containing all of the tentative definitions in
1652 // this header file. Generally, this record will be empty.
1653 RecordData TentativeDefinitions;
1654 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1655 TD = SemaRef.TentativeDefinitions.begin(),
1656 TDEnd = SemaRef.TentativeDefinitions.end();
1657 TD != TDEnd; ++TD)
1658 AddDeclRef(TD->second, TentativeDefinitions);
1659
Douglas Gregor062d9482009-04-22 22:18:58 +00001660 // Build a record containing all of the locally-scoped external
1661 // declarations in this header file. Generally, this record will be
1662 // empty.
1663 RecordData LocallyScopedExternalDecls;
1664 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1665 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1666 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1667 TD != TDEnd; ++TD)
1668 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1669
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001670 // Build a record containing all of the ext_vector declarations.
1671 RecordData ExtVectorDecls;
1672 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1673 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1674
1675 // Build a record containing all of the Objective-C category
1676 // implementations.
1677 RecordData ObjCCategoryImpls;
1678 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1679 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1680
Douglas Gregorc34897d2009-04-09 22:27:44 +00001681 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001682 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001683 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb7064742009-04-27 22:23:34 +00001684 WriteMetadata(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001685 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001686 if (StatCalls)
1687 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001688 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001689 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001690
1691 // Keep writing types and declarations until all types and
1692 // declarations have been written.
1693 do {
1694 if (!DeclsToEmit.empty())
1695 WriteDeclsBlock(Context);
1696 if (!TypesToEmit.empty())
1697 WriteTypesBlock(Context);
1698 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1699
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001700 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001701 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001702
1703 // Write the type offsets array
1704 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1705 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1708 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1709 Record.clear();
1710 Record.push_back(pch::TYPE_OFFSET);
1711 Record.push_back(TypeOffsets.size());
1712 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1713 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001714 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001715
1716 // Write the declaration offsets array
1717 Abbrev = new BitCodeAbbrev();
1718 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1721 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1722 Record.clear();
1723 Record.push_back(pch::DECL_OFFSET);
1724 Record.push_back(DeclOffsets.size());
1725 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1726 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001727 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001728
1729 // Write the record of special types.
1730 Record.clear();
1731 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001732 AddTypeRef(Context.getObjCIdType(), Record);
1733 AddTypeRef(Context.getObjCSelType(), Record);
1734 AddTypeRef(Context.getObjCProtoType(), Record);
1735 AddTypeRef(Context.getObjCClassType(), Record);
1736 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1737 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001738 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1739
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001740 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001741 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001742 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001743
1744 // Write the record containing tentative definitions.
1745 if (!TentativeDefinitions.empty())
1746 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001747
1748 // Write the record containing locally-scoped external definitions.
1749 if (!LocallyScopedExternalDecls.empty())
1750 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1751 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001752
1753 // Write the record containing ext_vector type names.
1754 if (!ExtVectorDecls.empty())
1755 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1756
1757 // Write the record containing Objective-C category implementations.
1758 if (!ObjCCategoryImpls.empty())
1759 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001760
1761 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001762 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001763 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001764 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001765 Record.push_back(NumLexicalDeclContexts);
1766 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001767 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001768 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001769}
1770
1771void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1772 Record.push_back(Loc.getRawEncoding());
1773}
1774
1775void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1776 Record.push_back(Value.getBitWidth());
1777 unsigned N = Value.getNumWords();
1778 const uint64_t* Words = Value.getRawData();
1779 for (unsigned I = 0; I != N; ++I)
1780 Record.push_back(Words[I]);
1781}
1782
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001783void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1784 Record.push_back(Value.isUnsigned());
1785 AddAPInt(Value, Record);
1786}
1787
Douglas Gregore2f37202009-04-14 21:55:33 +00001788void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1789 AddAPInt(Value.bitcastToAPInt(), Record);
1790}
1791
Douglas Gregorc34897d2009-04-09 22:27:44 +00001792void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001793 Record.push_back(getIdentifierRef(II));
1794}
1795
1796pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1797 if (II == 0)
1798 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001799
1800 pch::IdentID &ID = IdentifierIDs[II];
1801 if (ID == 0)
1802 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001803 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001804}
1805
Steve Naroff9e84d782009-04-23 10:39:46 +00001806void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1807 if (SelRef.getAsOpaquePtr() == 0) {
1808 Record.push_back(0);
1809 return;
1810 }
1811
1812 pch::SelectorID &SID = SelectorIDs[SelRef];
1813 if (SID == 0) {
1814 SID = SelectorIDs.size();
1815 SelVector.push_back(SelRef);
1816 }
1817 Record.push_back(SID);
1818}
1819
Douglas Gregorc34897d2009-04-09 22:27:44 +00001820void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1821 if (T.isNull()) {
1822 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1823 return;
1824 }
1825
1826 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001827 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001828 switch (BT->getKind()) {
1829 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1830 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1831 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1832 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1833 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1834 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1835 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1836 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1837 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1838 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1839 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1840 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1841 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1842 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1843 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1844 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1845 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1846 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1847 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1848 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1849 }
1850
1851 Record.push_back((ID << 3) | T.getCVRQualifiers());
1852 return;
1853 }
1854
Douglas Gregorac8f2802009-04-10 17:25:41 +00001855 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001856 if (ID == 0) {
1857 // We haven't seen this type before. Assign it a new ID and put it
1858 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001859 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001860 TypesToEmit.push(T.getTypePtr());
1861 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001862
1863 // Encode the type qualifiers in the type reference.
1864 Record.push_back((ID << 3) | T.getCVRQualifiers());
1865}
1866
1867void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1868 if (D == 0) {
1869 Record.push_back(0);
1870 return;
1871 }
1872
Douglas Gregorac8f2802009-04-10 17:25:41 +00001873 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001874 if (ID == 0) {
1875 // We haven't seen this declaration before. Give it a new ID and
1876 // enqueue it in the list of declarations to emit.
1877 ID = DeclIDs.size();
1878 DeclsToEmit.push(const_cast<Decl *>(D));
1879 }
1880
1881 Record.push_back(ID);
1882}
1883
Douglas Gregorff9a6092009-04-20 20:36:09 +00001884pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1885 if (D == 0)
1886 return 0;
1887
1888 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1889 return DeclIDs[D];
1890}
1891
Douglas Gregorc34897d2009-04-09 22:27:44 +00001892void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001893 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001894 Record.push_back(Name.getNameKind());
1895 switch (Name.getNameKind()) {
1896 case DeclarationName::Identifier:
1897 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1898 break;
1899
1900 case DeclarationName::ObjCZeroArgSelector:
1901 case DeclarationName::ObjCOneArgSelector:
1902 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001903 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001904 break;
1905
1906 case DeclarationName::CXXConstructorName:
1907 case DeclarationName::CXXDestructorName:
1908 case DeclarationName::CXXConversionFunctionName:
1909 AddTypeRef(Name.getCXXNameType(), Record);
1910 break;
1911
1912 case DeclarationName::CXXOperatorName:
1913 Record.push_back(Name.getCXXOverloadedOperator());
1914 break;
1915
1916 case DeclarationName::CXXUsingDirective:
1917 // No extra data to emit
1918 break;
1919 }
1920}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001921