blob: 11f620279ca9917b31bdd588585700517e0f0d1c [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
Douglas Gregor179cfb12009-04-10 20:39:37 +0000481 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
482
483 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
484 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
485 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
486
487 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000488 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
489 Record.push_back(LangOpts.LaxVectorConversions);
490 Record.push_back(LangOpts.Exceptions); // Support exception handling.
491
492 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
493 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
494 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
495
Chris Lattnercd4da472009-04-27 07:35:58 +0000496 // Whether static initializers are protected by locks.
497 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000498 Record.push_back(LangOpts.Blocks); // block extension to C
499 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
500 // they are unused.
501 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
502 // (modulo the platform support).
503
504 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
505 // signed integer arithmetic overflows.
506
507 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
508 // may be ripped out at any time.
509
510 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
511 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
512 // defined.
513 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
514 // opposed to __DYNAMIC__).
515 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
516
517 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
518 // used (instead of C99 semantics).
519 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
520 Record.push_back(LangOpts.getGCMode());
521 Record.push_back(LangOpts.getVisibilityMode());
522 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000523 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000524}
525
Douglas Gregorab1cef72009-04-10 03:52:48 +0000526//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000527// stat cache Serialization
528//===----------------------------------------------------------------------===//
529
530namespace {
531// Trait used for the on-disk hash table of stat cache results.
532class VISIBILITY_HIDDEN PCHStatCacheTrait {
533public:
534 typedef const char * key_type;
535 typedef key_type key_type_ref;
536
537 typedef std::pair<int, struct stat> data_type;
538 typedef const data_type& data_type_ref;
539
540 static unsigned ComputeHash(const char *path) {
541 return BernsteinHash(path);
542 }
543
544 std::pair<unsigned,unsigned>
545 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
546 data_type_ref Data) {
547 unsigned StrLen = strlen(path);
548 clang::io::Emit16(Out, StrLen);
549 unsigned DataLen = 1; // result value
550 if (Data.first == 0)
551 DataLen += 4 + 4 + 2 + 8 + 8;
552 clang::io::Emit8(Out, DataLen);
553 return std::make_pair(StrLen + 1, DataLen);
554 }
555
556 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
557 Out.write(path, KeyLen);
558 }
559
560 void EmitData(llvm::raw_ostream& Out, key_type_ref,
561 data_type_ref Data, unsigned DataLen) {
562 using namespace clang::io;
563 uint64_t Start = Out.tell(); (void)Start;
564
565 // Result of stat()
566 Emit8(Out, Data.first? 1 : 0);
567
568 if (Data.first == 0) {
569 Emit32(Out, (uint32_t) Data.second.st_ino);
570 Emit32(Out, (uint32_t) Data.second.st_dev);
571 Emit16(Out, (uint16_t) Data.second.st_mode);
572 Emit64(Out, (uint64_t) Data.second.st_mtime);
573 Emit64(Out, (uint64_t) Data.second.st_size);
574 }
575
576 assert(Out.tell() - Start == DataLen && "Wrong data length");
577 }
578};
579} // end anonymous namespace
580
581/// \brief Write the stat() system call cache to the PCH file.
582void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
583 // Build the on-disk hash table containing information about every
584 // stat() call.
585 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
586 unsigned NumStatEntries = 0;
587 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
588 StatEnd = StatCalls.end();
589 Stat != StatEnd; ++Stat, ++NumStatEntries)
590 Generator.insert(Stat->first(), Stat->second);
591
592 // Create the on-disk hash table in a buffer.
593 llvm::SmallVector<char, 4096> StatCacheData;
594 uint32_t BucketOffset;
595 {
596 llvm::raw_svector_ostream Out(StatCacheData);
597 // Make sure that no bucket is at offset 0
598 clang::io::Emit32(Out, 0);
599 BucketOffset = Generator.Emit(Out);
600 }
601
602 // Create a blob abbreviation
603 using namespace llvm;
604 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
605 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
609 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
610
611 // Write the stat cache
612 RecordData Record;
613 Record.push_back(pch::STAT_CACHE);
614 Record.push_back(BucketOffset);
615 Record.push_back(NumStatEntries);
616 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
617 &StatCacheData.front(),
618 StatCacheData.size());
619}
620
621//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000622// Source Manager Serialization
623//===----------------------------------------------------------------------===//
624
625/// \brief Create an abbreviation for the SLocEntry that refers to a
626/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000627static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000628 using namespace llvm;
629 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
630 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
631 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
632 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
634 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000636 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000637}
638
639/// \brief Create an abbreviation for the SLocEntry that refers to a
640/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000641static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000642 using namespace llvm;
643 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
644 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000650 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000651}
652
653/// \brief Create an abbreviation for the SLocEntry that refers to a
654/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000655static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000656 using namespace llvm;
657 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
658 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000660 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000661}
662
663/// \brief Create an abbreviation for the SLocEntry that refers to an
664/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000665static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000666 using namespace llvm;
667 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
668 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
671 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000674 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000675}
676
677/// \brief Writes the block containing the serialized form of the
678/// source manager.
679///
680/// TODO: We should probably use an on-disk hash table (stored in a
681/// blob), indexed based on the file name, so that we only create
682/// entries for files that we actually need. In the common case (no
683/// errors), we probably won't have to create file entries for any of
684/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000685void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
686 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000687 RecordData Record;
688
Chris Lattner84b04f12009-04-10 17:16:57 +0000689 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000690 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000691
692 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000693 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
694 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
695 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
696 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000697
Douglas Gregor635f97f2009-04-13 16:31:14 +0000698 // Write the line table.
699 if (SourceMgr.hasLineTable()) {
700 LineTableInfo &LineTable = SourceMgr.getLineTable();
701
702 // Emit the file names
703 Record.push_back(LineTable.getNumFilenames());
704 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
705 // Emit the file name
706 const char *Filename = LineTable.getFilename(I);
707 unsigned FilenameLen = Filename? strlen(Filename) : 0;
708 Record.push_back(FilenameLen);
709 if (FilenameLen)
710 Record.insert(Record.end(), Filename, Filename + FilenameLen);
711 }
712
713 // Emit the line entries
714 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
715 L != LEnd; ++L) {
716 // Emit the file ID
717 Record.push_back(L->first);
718
719 // Emit the line entries
720 Record.push_back(L->second.size());
721 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
722 LEEnd = L->second.end();
723 LE != LEEnd; ++LE) {
724 Record.push_back(LE->FileOffset);
725 Record.push_back(LE->LineNo);
726 Record.push_back(LE->FilenameID);
727 Record.push_back((unsigned)LE->FileKind);
728 Record.push_back(LE->IncludeOffset);
729 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000730 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000731 }
732 }
733
Douglas Gregor32e231c2009-04-27 06:38:32 +0000734 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000735 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000736 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000737 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
738 E = HS.header_file_end();
739 I != E; ++I) {
740 Record.push_back(I->isImport);
741 Record.push_back(I->DirInfo);
742 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000743 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000744 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
745 Record.clear();
746 }
747
Douglas Gregor32e231c2009-04-27 06:38:32 +0000748 // Write out the source location entry table. We skip the first
749 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000750 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000751 RecordData PreloadSLocs;
752 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
753 for (SourceManager::sloc_entry_iterator
754 SLoc = SourceMgr.sloc_entry_begin() + 1,
755 SLocEnd = SourceMgr.sloc_entry_end();
756 SLoc != SLocEnd; ++SLoc) {
757 // Record the offset of this source-location entry.
758 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
759
760 // Figure out which record code to use.
761 unsigned Code;
762 if (SLoc->isFile()) {
763 if (SLoc->getFile().getContentCache()->Entry)
764 Code = pch::SM_SLOC_FILE_ENTRY;
765 else
766 Code = pch::SM_SLOC_BUFFER_ENTRY;
767 } else
768 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
769 Record.clear();
770 Record.push_back(Code);
771
772 Record.push_back(SLoc->getOffset());
773 if (SLoc->isFile()) {
774 const SrcMgr::FileInfo &File = SLoc->getFile();
775 Record.push_back(File.getIncludeLoc().getRawEncoding());
776 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
777 Record.push_back(File.hasLineDirectives());
778
779 const SrcMgr::ContentCache *Content = File.getContentCache();
780 if (Content->Entry) {
781 // The source location entry is a file. The blob associated
782 // with this entry is the file name.
783 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
784 Content->Entry->getName(),
785 strlen(Content->Entry->getName()));
786
787 // FIXME: For now, preload all file source locations, so that
788 // we get the appropriate File entries in the reader. This is
789 // a temporary measure.
790 PreloadSLocs.push_back(SLocEntryOffsets.size());
791 } else {
792 // The source location entry is a buffer. The blob associated
793 // with this entry contains the contents of the buffer.
794
795 // We add one to the size so that we capture the trailing NULL
796 // that is required by llvm::MemoryBuffer::getMemBuffer (on
797 // the reader side).
798 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
799 const char *Name = Buffer->getBufferIdentifier();
800 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
801 Record.clear();
802 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
803 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
804 Buffer->getBufferStart(),
805 Buffer->getBufferSize() + 1);
806
807 if (strcmp(Name, "<built-in>") == 0)
808 PreloadSLocs.push_back(SLocEntryOffsets.size());
809 }
810 } else {
811 // The source location entry is an instantiation.
812 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
813 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
814 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
815 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
816
817 // Compute the token length for this macro expansion.
818 unsigned NextOffset = SourceMgr.getNextOffset();
819 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
820 if (++NextSLoc != SLocEnd)
821 NextOffset = NextSLoc->getOffset();
822 Record.push_back(NextOffset - SLoc->getOffset() - 1);
823 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
824 }
825 }
826
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000827 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000828
829 if (SLocEntryOffsets.empty())
830 return;
831
832 // Write the source-location offsets table into the PCH block. This
833 // table is used for lazily loading source-location information.
834 using namespace llvm;
835 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
836 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
840 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
841
842 Record.clear();
843 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
844 Record.push_back(SLocEntryOffsets.size());
845 Record.push_back(SourceMgr.getNextOffset());
846 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
847 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000848 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000849
850 // Write the source location entry preloads array, telling the PCH
851 // reader which source locations entries it should load eagerly.
852 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000853}
854
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000855//===----------------------------------------------------------------------===//
856// Preprocessor Serialization
857//===----------------------------------------------------------------------===//
858
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000859/// \brief Writes the block containing the serialized form of the
860/// preprocessor.
861///
Chris Lattner850eabd2009-04-10 18:08:30 +0000862void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000863 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000864
Chris Lattner4b21c202009-04-13 01:29:17 +0000865 // If the preprocessor __COUNTER__ value has been bumped, remember it.
866 if (PP.getCounterValue() != 0) {
867 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000868 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000869 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000870 }
871
872 // Enter the preprocessor block.
873 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000874
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000875 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
876 // FIXME: use diagnostics subsystem for localization etc.
877 if (PP.SawDateOrTime())
878 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
879
Chris Lattner1b094952009-04-10 18:00:12 +0000880 // Loop over all the macro definitions that are live at the end of the file,
881 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000882 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
883 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000884 // FIXME: This emits macros in hash table order, we should do it in a stable
885 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000886 MacroInfo *MI = I->second;
887
888 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
889 // been redefined by the header (in which case they are not isBuiltinMacro).
890 if (MI->isBuiltinMacro())
891 continue;
892
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000893 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000894 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000895 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000896 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
897 Record.push_back(MI->isUsed());
898
899 unsigned Code;
900 if (MI->isObjectLike()) {
901 Code = pch::PP_MACRO_OBJECT_LIKE;
902 } else {
903 Code = pch::PP_MACRO_FUNCTION_LIKE;
904
905 Record.push_back(MI->isC99Varargs());
906 Record.push_back(MI->isGNUVarargs());
907 Record.push_back(MI->getNumArgs());
908 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
909 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000910 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000911 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000912 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000913 Record.clear();
914
Chris Lattner850eabd2009-04-10 18:08:30 +0000915 // Emit the tokens array.
916 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
917 // Note that we know that the preprocessor does not have any annotation
918 // tokens in it because they are created by the parser, and thus can't be
919 // in a macro definition.
920 const Token &Tok = MI->getReplacementToken(TokNo);
921
922 Record.push_back(Tok.getLocation().getRawEncoding());
923 Record.push_back(Tok.getLength());
924
Chris Lattner850eabd2009-04-10 18:08:30 +0000925 // FIXME: When reading literal tokens, reconstruct the literal pointer if
926 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000927 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000928
929 // FIXME: Should translate token kind to a stable encoding.
930 Record.push_back(Tok.getKind());
931 // FIXME: Should translate token flags to a stable encoding.
932 Record.push_back(Tok.getFlags());
933
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000934 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000935 Record.clear();
936 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000937 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000938 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000939 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000940}
941
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000942//===----------------------------------------------------------------------===//
943// Type Serialization
944//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000945
Douglas Gregorc34897d2009-04-09 22:27:44 +0000946/// \brief Write the representation of a type to the PCH stream.
947void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000948 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000949 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000950 ID = NextTypeID++;
951
952 // Record the offset for this type.
953 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000954 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000955 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
956 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000957 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000958 }
959
960 RecordData Record;
961
962 // Emit the type's representation.
963 PCHTypeWriter W(*this, Record);
964 switch (T->getTypeClass()) {
965 // For all of the concrete, non-dependent types, call the
966 // appropriate visitor function.
967#define TYPE(Class, Base) \
968 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
969#define ABSTRACT_TYPE(Class, Base)
970#define DEPENDENT_TYPE(Class, Base)
971#include "clang/AST/TypeNodes.def"
972
973 // For all of the dependent type nodes (which only occur in C++
974 // templates), produce an error.
975#define TYPE(Class, Base)
976#define DEPENDENT_TYPE(Class, Base) case Type::Class:
977#include "clang/AST/TypeNodes.def"
978 assert(false && "Cannot serialize dependent type nodes");
979 break;
980 }
981
982 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000983 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000984
985 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000986 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000987}
988
989/// \brief Write a block containing all of the types.
990void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000991 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000992 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000993
Douglas Gregore43f0972009-04-26 03:49:13 +0000994 // Emit all of the types that need to be emitted (so far).
995 while (!TypesToEmit.empty()) {
996 const Type *T = TypesToEmit.front();
997 TypesToEmit.pop();
998 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
999 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001000 }
1001
1002 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001003 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001004}
1005
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001006//===----------------------------------------------------------------------===//
1007// Declaration Serialization
1008//===----------------------------------------------------------------------===//
1009
Douglas Gregorc34897d2009-04-09 22:27:44 +00001010/// \brief Write the block containing all of the declaration IDs
1011/// lexically declared within the given DeclContext.
1012///
1013/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1014/// bistream, or 0 if no block was written.
1015uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1016 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001017 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001018 return 0;
1019
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001020 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001021 RecordData Record;
1022 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1023 DEnd = DC->decls_end(Context);
1024 D != DEnd; ++D)
1025 AddDeclRef(*D, Record);
1026
Douglas Gregoraf136d92009-04-22 22:34:57 +00001027 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001028 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001029 return Offset;
1030}
1031
1032/// \brief Write the block containing all of the declaration IDs
1033/// visible from the given DeclContext.
1034///
1035/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1036/// bistream, or 0 if no block was written.
1037uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1038 DeclContext *DC) {
1039 if (DC->getPrimaryContext() != DC)
1040 return 0;
1041
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001042 // Since there is no name lookup into functions or methods, and we
1043 // perform name lookup for the translation unit via the
1044 // IdentifierInfo chains, don't bother to build a
1045 // visible-declarations table for these entities.
1046 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001047 return 0;
1048
Douglas Gregorc34897d2009-04-09 22:27:44 +00001049 // Force the DeclContext to build a its name-lookup table.
1050 DC->lookup(Context, DeclarationName());
1051
1052 // Serialize the contents of the mapping used for lookup. Note that,
1053 // although we have two very different code paths, the serialized
1054 // representation is the same for both cases: a declaration name,
1055 // followed by a size, followed by references to the visible
1056 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001057 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001058 RecordData Record;
1059 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001060 if (!Map)
1061 return 0;
1062
Douglas Gregorc34897d2009-04-09 22:27:44 +00001063 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1064 D != DEnd; ++D) {
1065 AddDeclarationName(D->first, Record);
1066 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1067 Record.push_back(Result.second - Result.first);
1068 for(; Result.first != Result.second; ++Result.first)
1069 AddDeclRef(*Result.first, Record);
1070 }
1071
1072 if (Record.size() == 0)
1073 return 0;
1074
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001075 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001076 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001077 return Offset;
1078}
1079
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001080//===----------------------------------------------------------------------===//
1081// Global Method Pool and Selector Serialization
1082//===----------------------------------------------------------------------===//
1083
Douglas Gregorff9a6092009-04-20 20:36:09 +00001084namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001085// Trait used for the on-disk hash table used in the method pool.
1086class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1087 PCHWriter &Writer;
1088
1089public:
1090 typedef Selector key_type;
1091 typedef key_type key_type_ref;
1092
1093 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1094 typedef const data_type& data_type_ref;
1095
1096 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1097
1098 static unsigned ComputeHash(Selector Sel) {
1099 unsigned N = Sel.getNumArgs();
1100 if (N == 0)
1101 ++N;
1102 unsigned R = 5381;
1103 for (unsigned I = 0; I != N; ++I)
1104 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1105 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1106 return R;
1107 }
1108
1109 std::pair<unsigned,unsigned>
1110 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1111 data_type_ref Methods) {
1112 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1113 clang::io::Emit16(Out, KeyLen);
1114 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1115 for (const ObjCMethodList *Method = &Methods.first; Method;
1116 Method = Method->Next)
1117 if (Method->Method)
1118 DataLen += 4;
1119 for (const ObjCMethodList *Method = &Methods.second; Method;
1120 Method = Method->Next)
1121 if (Method->Method)
1122 DataLen += 4;
1123 clang::io::Emit16(Out, DataLen);
1124 return std::make_pair(KeyLen, DataLen);
1125 }
1126
Douglas Gregor2d711832009-04-25 17:48:32 +00001127 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1128 uint64_t Start = Out.tell();
1129 assert((Start >> 32) == 0 && "Selector key offset too large");
1130 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001131 unsigned N = Sel.getNumArgs();
1132 clang::io::Emit16(Out, N);
1133 if (N == 0)
1134 N = 1;
1135 for (unsigned I = 0; I != N; ++I)
1136 clang::io::Emit32(Out,
1137 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1138 }
1139
1140 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001141 data_type_ref Methods, unsigned DataLen) {
1142 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001143 unsigned NumInstanceMethods = 0;
1144 for (const ObjCMethodList *Method = &Methods.first; Method;
1145 Method = Method->Next)
1146 if (Method->Method)
1147 ++NumInstanceMethods;
1148
1149 unsigned NumFactoryMethods = 0;
1150 for (const ObjCMethodList *Method = &Methods.second; Method;
1151 Method = Method->Next)
1152 if (Method->Method)
1153 ++NumFactoryMethods;
1154
1155 clang::io::Emit16(Out, NumInstanceMethods);
1156 clang::io::Emit16(Out, NumFactoryMethods);
1157 for (const ObjCMethodList *Method = &Methods.first; Method;
1158 Method = Method->Next)
1159 if (Method->Method)
1160 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001161 for (const ObjCMethodList *Method = &Methods.second; Method;
1162 Method = Method->Next)
1163 if (Method->Method)
1164 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001165
1166 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001167 }
1168};
1169} // end anonymous namespace
1170
1171/// \brief Write the method pool into the PCH file.
1172///
1173/// The method pool contains both instance and factory methods, stored
1174/// in an on-disk hash table indexed by the selector.
1175void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1176 using namespace llvm;
1177
1178 // Create and write out the blob that contains the instance and
1179 // factor method pools.
1180 bool Empty = true;
1181 {
1182 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1183
1184 // Create the on-disk hash table representation. Start by
1185 // iterating through the instance method pool.
1186 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001187 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001188 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1189 Instance = SemaRef.InstanceMethodPool.begin(),
1190 InstanceEnd = SemaRef.InstanceMethodPool.end();
1191 Instance != InstanceEnd; ++Instance) {
1192 // Check whether there is a factory method with the same
1193 // selector.
1194 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1195 = SemaRef.FactoryMethodPool.find(Instance->first);
1196
1197 if (Factory == SemaRef.FactoryMethodPool.end())
1198 Generator.insert(Instance->first,
1199 std::make_pair(Instance->second,
1200 ObjCMethodList()));
1201 else
1202 Generator.insert(Instance->first,
1203 std::make_pair(Instance->second, Factory->second));
1204
Douglas Gregor2d711832009-04-25 17:48:32 +00001205 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001206 Empty = false;
1207 }
1208
1209 // Now iterate through the factory method pool, to pick up any
1210 // selectors that weren't already in the instance method pool.
1211 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1212 Factory = SemaRef.FactoryMethodPool.begin(),
1213 FactoryEnd = SemaRef.FactoryMethodPool.end();
1214 Factory != FactoryEnd; ++Factory) {
1215 // Check whether there is an instance method with the same
1216 // selector. If so, there is no work to do here.
1217 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1218 = SemaRef.InstanceMethodPool.find(Factory->first);
1219
Douglas Gregor2d711832009-04-25 17:48:32 +00001220 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001221 Generator.insert(Factory->first,
1222 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001223 ++NumSelectorsInMethodPool;
1224 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001225
1226 Empty = false;
1227 }
1228
Douglas Gregor2d711832009-04-25 17:48:32 +00001229 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001230 return;
1231
1232 // Create the on-disk hash table in a buffer.
1233 llvm::SmallVector<char, 4096> MethodPool;
1234 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001235 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001236 {
1237 PCHMethodPoolTrait Trait(*this);
1238 llvm::raw_svector_ostream Out(MethodPool);
1239 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001240 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001241 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001242
1243 // For every selector that we have seen but which was not
1244 // written into the hash table, write the selector itself and
1245 // record it's offset.
1246 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1247 if (SelectorOffsets[I] == 0)
1248 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001249 }
1250
1251 // Create a blob abbreviation
1252 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1253 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1257 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1258
Douglas Gregor2d711832009-04-25 17:48:32 +00001259 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001260 RecordData Record;
1261 Record.push_back(pch::METHOD_POOL);
1262 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001263 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001264 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1265 &MethodPool.front(),
1266 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001267
1268 // Create a blob abbreviation for the selector table offsets.
1269 Abbrev = new BitCodeAbbrev();
1270 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1273 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1274
1275 // Write the selector offsets table.
1276 Record.clear();
1277 Record.push_back(pch::SELECTOR_OFFSETS);
1278 Record.push_back(SelectorOffsets.size());
1279 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1280 (const char *)&SelectorOffsets.front(),
1281 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001282 }
1283}
1284
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001285//===----------------------------------------------------------------------===//
1286// Identifier Table Serialization
1287//===----------------------------------------------------------------------===//
1288
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001289namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001290class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1291 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001292 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001293
1294public:
1295 typedef const IdentifierInfo* key_type;
1296 typedef key_type key_type_ref;
1297
1298 typedef pch::IdentID data_type;
1299 typedef data_type data_type_ref;
1300
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001301 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1302 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001303
1304 static unsigned ComputeHash(const IdentifierInfo* II) {
1305 return clang::BernsteinHash(II->getName());
1306 }
1307
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001308 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001309 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1310 pch::IdentID ID) {
1311 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregorc713da92009-04-21 22:25:48 +00001312 unsigned DataLen = 4 + 4; // 4 bytes for token ID, builtin, flags
1313 // 4 bytes for the persistent ID
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001314 if (II->hasMacroDefinition() &&
1315 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1316 DataLen += 8;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001317 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1318 DEnd = IdentifierResolver::end();
1319 D != DEnd; ++D)
1320 DataLen += sizeof(pch::DeclID);
Douglas Gregorc713da92009-04-21 22:25:48 +00001321 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001322 // We emit the key length after the data length so that every
1323 // string is preceded by a 16-bit length. This matches the PTH
1324 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001325 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001326 return std::make_pair(KeyLen, DataLen);
1327 }
1328
1329 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1330 unsigned KeyLen) {
1331 // Record the location of the key data. This is used when generating
1332 // the mapping from persistent IDs to strings.
1333 Writer.SetIdentifierOffset(II, Out.tell());
1334 Out.write(II->getName(), KeyLen);
1335 }
1336
1337 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1338 pch::IdentID ID, unsigned) {
1339 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001340 bool hasMacroDefinition =
1341 II->hasMacroDefinition() &&
1342 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001343 Bits = Bits | (uint32_t)II->getTokenID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001344 Bits = (Bits << 10) | (uint32_t)II->getObjCOrBuiltinID();
1345 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001346 Bits = (Bits << 1) | II->isExtensionToken();
1347 Bits = (Bits << 1) | II->isPoisoned();
1348 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
1349 clang::io::Emit32(Out, Bits);
1350 clang::io::Emit32(Out, ID);
1351
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001352 if (hasMacroDefinition)
1353 clang::io::Emit64(Out, Writer.getMacroOffset(II));
1354
Douglas Gregorc713da92009-04-21 22:25:48 +00001355 // Emit the declaration IDs in reverse order, because the
1356 // IdentifierResolver provides the declarations as they would be
1357 // visible (e.g., the function "stat" would come before the struct
1358 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1359 // adds declarations to the end of the list (so we need to see the
1360 // struct "status" before the function "status").
1361 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1362 IdentifierResolver::end());
1363 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1364 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001365 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001366 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001367 }
1368};
1369} // end anonymous namespace
1370
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001371/// \brief Write the identifier table into the PCH file.
1372///
1373/// The identifier table consists of a blob containing string data
1374/// (the actual identifiers themselves) and a separate "offsets" index
1375/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001376void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001377 using namespace llvm;
1378
1379 // Create and write out the blob that contains the identifier
1380 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001381 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001382 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1383
Douglas Gregor91137812009-04-28 20:33:11 +00001384 // Look for any identifiers that were named while processing the
1385 // headers, but are otherwise not needed. We add these to the hash
1386 // table to enable checking of the predefines buffer in the case
1387 // where the user adds new macro definitions when building the PCH
1388 // file.
1389 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1390 IDEnd = PP.getIdentifierTable().end();
1391 ID != IDEnd; ++ID)
1392 getIdentifierRef(ID->second);
1393
Douglas Gregorff9a6092009-04-20 20:36:09 +00001394 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001395 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001396 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1397 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1398 ID != IDEnd; ++ID) {
1399 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001400 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001401 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001402
Douglas Gregorff9a6092009-04-20 20:36:09 +00001403 // Create the on-disk hash table in a buffer.
1404 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001405 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001406 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001407 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001408 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001409 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001410 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001411 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001412 }
1413
1414 // Create a blob abbreviation
1415 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1416 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001417 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001419 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001420
1421 // Write the identifier table
1422 RecordData Record;
1423 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001424 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001425 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1426 &IdentifierTable.front(),
1427 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001428 }
1429
1430 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001431 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1432 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1433 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1435 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1436
1437 RecordData Record;
1438 Record.push_back(pch::IDENTIFIER_OFFSET);
1439 Record.push_back(IdentifierOffsets.size());
1440 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1441 (const char *)&IdentifierOffsets.front(),
1442 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001443}
1444
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001445//===----------------------------------------------------------------------===//
1446// General Serialization Routines
1447//===----------------------------------------------------------------------===//
1448
Douglas Gregor1c507882009-04-15 21:30:51 +00001449/// \brief Write a record containing the given attributes.
1450void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1451 RecordData Record;
1452 for (; Attr; Attr = Attr->getNext()) {
1453 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1454 Record.push_back(Attr->isInherited());
1455 switch (Attr->getKind()) {
1456 case Attr::Alias:
1457 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1458 break;
1459
1460 case Attr::Aligned:
1461 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1462 break;
1463
1464 case Attr::AlwaysInline:
1465 break;
1466
1467 case Attr::AnalyzerNoReturn:
1468 break;
1469
1470 case Attr::Annotate:
1471 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1472 break;
1473
1474 case Attr::AsmLabel:
1475 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1476 break;
1477
1478 case Attr::Blocks:
1479 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1480 break;
1481
1482 case Attr::Cleanup:
1483 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1484 break;
1485
1486 case Attr::Const:
1487 break;
1488
1489 case Attr::Constructor:
1490 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1491 break;
1492
1493 case Attr::DLLExport:
1494 case Attr::DLLImport:
1495 case Attr::Deprecated:
1496 break;
1497
1498 case Attr::Destructor:
1499 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1500 break;
1501
1502 case Attr::FastCall:
1503 break;
1504
1505 case Attr::Format: {
1506 const FormatAttr *Format = cast<FormatAttr>(Attr);
1507 AddString(Format->getType(), Record);
1508 Record.push_back(Format->getFormatIdx());
1509 Record.push_back(Format->getFirstArg());
1510 break;
1511 }
1512
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001513 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001514 case Attr::IBOutletKind:
1515 case Attr::NoReturn:
1516 case Attr::NoThrow:
1517 case Attr::Nodebug:
1518 case Attr::Noinline:
1519 break;
1520
1521 case Attr::NonNull: {
1522 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1523 Record.push_back(NonNull->size());
1524 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1525 break;
1526 }
1527
1528 case Attr::ObjCException:
1529 case Attr::ObjCNSObject:
Ted Kremenek203169f2009-04-27 19:36:56 +00001530 case Attr::ObjCOwnershipCFRelease:
1531 case Attr::ObjCOwnershipRelease:
Ted Kremenek15830ed2009-04-27 18:27:22 +00001532 case Attr::ObjCOwnershipCFRetain:
Ted Kremenekb98860c2009-04-25 00:17:17 +00001533 case Attr::ObjCOwnershipRetain:
Ted Kremenekaa6e3182009-04-24 23:09:54 +00001534 case Attr::ObjCOwnershipReturns:
Douglas Gregor1c507882009-04-15 21:30:51 +00001535 case Attr::Overloadable:
1536 break;
1537
1538 case Attr::Packed:
1539 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1540 break;
1541
1542 case Attr::Pure:
1543 break;
1544
1545 case Attr::Regparm:
1546 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1547 break;
1548
1549 case Attr::Section:
1550 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1551 break;
1552
1553 case Attr::StdCall:
1554 case Attr::TransparentUnion:
1555 case Attr::Unavailable:
1556 case Attr::Unused:
1557 case Attr::Used:
1558 break;
1559
1560 case Attr::Visibility:
1561 // FIXME: stable encoding
1562 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1563 break;
1564
1565 case Attr::WarnUnusedResult:
1566 case Attr::Weak:
1567 case Attr::WeakImport:
1568 break;
1569 }
1570 }
1571
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001572 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001573}
1574
1575void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1576 Record.push_back(Str.size());
1577 Record.insert(Record.end(), Str.begin(), Str.end());
1578}
1579
Douglas Gregorff9a6092009-04-20 20:36:09 +00001580/// \brief Note that the identifier II occurs at the given offset
1581/// within the identifier table.
1582void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001583 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001584}
1585
Douglas Gregor2d711832009-04-25 17:48:32 +00001586/// \brief Note that the selector Sel occurs at the given offset
1587/// within the method pool/selector table.
1588void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1589 unsigned ID = SelectorIDs[Sel];
1590 assert(ID && "Unknown selector");
1591 SelectorOffsets[ID - 1] = Offset;
1592}
1593
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001594PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001595 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001596 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1597 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001598
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001599void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001600 using namespace llvm;
1601
Douglas Gregor87887da2009-04-20 15:53:59 +00001602 ASTContext &Context = SemaRef.Context;
1603 Preprocessor &PP = SemaRef.PP;
1604
Douglas Gregorc34897d2009-04-09 22:27:44 +00001605 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001606 Stream.Emit((unsigned)'C', 8);
1607 Stream.Emit((unsigned)'P', 8);
1608 Stream.Emit((unsigned)'C', 8);
1609 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001610
1611 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001612
1613 // The translation unit is the first declaration we'll emit.
1614 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1615 DeclsToEmit.push(Context.getTranslationUnitDecl());
1616
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001617 // Make sure that we emit IdentifierInfos (and any attached
1618 // declarations) for builtins.
1619 {
1620 IdentifierTable &Table = PP.getIdentifierTable();
1621 llvm::SmallVector<const char *, 32> BuiltinNames;
1622 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1623 Context.getLangOptions().NoBuiltin);
1624 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1625 getIdentifierRef(&Table.get(BuiltinNames[I]));
1626 }
1627
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001628 // Build a record containing all of the tentative definitions in
1629 // this header file. Generally, this record will be empty.
1630 RecordData TentativeDefinitions;
1631 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1632 TD = SemaRef.TentativeDefinitions.begin(),
1633 TDEnd = SemaRef.TentativeDefinitions.end();
1634 TD != TDEnd; ++TD)
1635 AddDeclRef(TD->second, TentativeDefinitions);
1636
Douglas Gregor062d9482009-04-22 22:18:58 +00001637 // Build a record containing all of the locally-scoped external
1638 // declarations in this header file. Generally, this record will be
1639 // empty.
1640 RecordData LocallyScopedExternalDecls;
1641 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1642 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1643 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1644 TD != TDEnd; ++TD)
1645 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1646
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001647 // Build a record containing all of the ext_vector declarations.
1648 RecordData ExtVectorDecls;
1649 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1650 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1651
1652 // Build a record containing all of the Objective-C category
1653 // implementations.
1654 RecordData ObjCCategoryImpls;
1655 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1656 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1657
Douglas Gregorc34897d2009-04-09 22:27:44 +00001658 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001659 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001660 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb7064742009-04-27 22:23:34 +00001661 WriteMetadata(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001662 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001663 if (StatCalls)
1664 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001665 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001666 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001667
1668 // Keep writing types and declarations until all types and
1669 // declarations have been written.
1670 do {
1671 if (!DeclsToEmit.empty())
1672 WriteDeclsBlock(Context);
1673 if (!TypesToEmit.empty())
1674 WriteTypesBlock(Context);
1675 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1676
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001677 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001678 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001679
1680 // Write the type offsets array
1681 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1682 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1685 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1686 Record.clear();
1687 Record.push_back(pch::TYPE_OFFSET);
1688 Record.push_back(TypeOffsets.size());
1689 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1690 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001691 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001692
1693 // Write the declaration offsets array
1694 Abbrev = new BitCodeAbbrev();
1695 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1698 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1699 Record.clear();
1700 Record.push_back(pch::DECL_OFFSET);
1701 Record.push_back(DeclOffsets.size());
1702 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1703 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001704 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001705
1706 // Write the record of special types.
1707 Record.clear();
1708 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001709 AddTypeRef(Context.getObjCIdType(), Record);
1710 AddTypeRef(Context.getObjCSelType(), Record);
1711 AddTypeRef(Context.getObjCProtoType(), Record);
1712 AddTypeRef(Context.getObjCClassType(), Record);
1713 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1714 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001715 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1716
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001717 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001718 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001719 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001720
1721 // Write the record containing tentative definitions.
1722 if (!TentativeDefinitions.empty())
1723 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001724
1725 // Write the record containing locally-scoped external definitions.
1726 if (!LocallyScopedExternalDecls.empty())
1727 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1728 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001729
1730 // Write the record containing ext_vector type names.
1731 if (!ExtVectorDecls.empty())
1732 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1733
1734 // Write the record containing Objective-C category implementations.
1735 if (!ObjCCategoryImpls.empty())
1736 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001737
1738 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001739 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001740 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001741 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001742 Record.push_back(NumLexicalDeclContexts);
1743 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001744 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001745 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001746}
1747
1748void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1749 Record.push_back(Loc.getRawEncoding());
1750}
1751
1752void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1753 Record.push_back(Value.getBitWidth());
1754 unsigned N = Value.getNumWords();
1755 const uint64_t* Words = Value.getRawData();
1756 for (unsigned I = 0; I != N; ++I)
1757 Record.push_back(Words[I]);
1758}
1759
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001760void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1761 Record.push_back(Value.isUnsigned());
1762 AddAPInt(Value, Record);
1763}
1764
Douglas Gregore2f37202009-04-14 21:55:33 +00001765void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1766 AddAPInt(Value.bitcastToAPInt(), Record);
1767}
1768
Douglas Gregorc34897d2009-04-09 22:27:44 +00001769void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001770 Record.push_back(getIdentifierRef(II));
1771}
1772
1773pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1774 if (II == 0)
1775 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001776
1777 pch::IdentID &ID = IdentifierIDs[II];
1778 if (ID == 0)
1779 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001780 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001781}
1782
Steve Naroff9e84d782009-04-23 10:39:46 +00001783void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1784 if (SelRef.getAsOpaquePtr() == 0) {
1785 Record.push_back(0);
1786 return;
1787 }
1788
1789 pch::SelectorID &SID = SelectorIDs[SelRef];
1790 if (SID == 0) {
1791 SID = SelectorIDs.size();
1792 SelVector.push_back(SelRef);
1793 }
1794 Record.push_back(SID);
1795}
1796
Douglas Gregorc34897d2009-04-09 22:27:44 +00001797void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1798 if (T.isNull()) {
1799 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1800 return;
1801 }
1802
1803 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001804 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001805 switch (BT->getKind()) {
1806 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1807 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1808 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1809 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1810 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1811 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1812 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1813 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1814 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1815 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1816 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1817 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1818 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1819 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1820 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1821 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1822 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1823 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1824 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1825 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1826 }
1827
1828 Record.push_back((ID << 3) | T.getCVRQualifiers());
1829 return;
1830 }
1831
Douglas Gregorac8f2802009-04-10 17:25:41 +00001832 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001833 if (ID == 0) {
1834 // We haven't seen this type before. Assign it a new ID and put it
1835 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001836 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001837 TypesToEmit.push(T.getTypePtr());
1838 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001839
1840 // Encode the type qualifiers in the type reference.
1841 Record.push_back((ID << 3) | T.getCVRQualifiers());
1842}
1843
1844void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1845 if (D == 0) {
1846 Record.push_back(0);
1847 return;
1848 }
1849
Douglas Gregorac8f2802009-04-10 17:25:41 +00001850 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001851 if (ID == 0) {
1852 // We haven't seen this declaration before. Give it a new ID and
1853 // enqueue it in the list of declarations to emit.
1854 ID = DeclIDs.size();
1855 DeclsToEmit.push(const_cast<Decl *>(D));
1856 }
1857
1858 Record.push_back(ID);
1859}
1860
Douglas Gregorff9a6092009-04-20 20:36:09 +00001861pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1862 if (D == 0)
1863 return 0;
1864
1865 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1866 return DeclIDs[D];
1867}
1868
Douglas Gregorc34897d2009-04-09 22:27:44 +00001869void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001870 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001871 Record.push_back(Name.getNameKind());
1872 switch (Name.getNameKind()) {
1873 case DeclarationName::Identifier:
1874 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1875 break;
1876
1877 case DeclarationName::ObjCZeroArgSelector:
1878 case DeclarationName::ObjCOneArgSelector:
1879 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001880 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001881 break;
1882
1883 case DeclarationName::CXXConstructorName:
1884 case DeclarationName::CXXDestructorName:
1885 case DeclarationName::CXXConversionFunctionName:
1886 AddTypeRef(Name.getCXXNameType(), Record);
1887 break;
1888
1889 case DeclarationName::CXXOperatorName:
1890 Record.push_back(Name.getCXXOverloadedOperator());
1891 break;
1892
1893 case DeclarationName::CXXUsingDirective:
1894 // No extra data to emit
1895 break;
1896 }
1897}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001898