blob: 2d4d8e44477ee12736bc5dfbd44708e52e2dd9a6 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregor3251ceb2009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000036#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000037using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// Type serialization
41//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000042
Douglas Gregor2cf26342009-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 Gregor4fed3f42009-04-27 18:38:38 +000053 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-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 Gregorc9490c02009-04-16 22:23:12 +0000133 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-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());
Sebastian Redl7b9a2ee2009-04-30 19:20:55 +0000164 Record.push_back(T->hasExceptionSpec());
165 Record.push_back(T->hasAnyExceptionSpec());
166 Record.push_back(T->getNumExceptions());
167 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
168 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000169 Code = pch::TYPE_FUNCTION_PROTO;
170}
171
172void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
173 Writer.AddDeclRef(T->getDecl(), Record);
174 Code = pch::TYPE_TYPEDEF;
175}
176
177void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000178 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000179 Code = pch::TYPE_TYPEOF_EXPR;
180}
181
182void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
183 Writer.AddTypeRef(T->getUnderlyingType(), Record);
184 Code = pch::TYPE_TYPEOF;
185}
186
187void PCHTypeWriter::VisitTagType(const TagType *T) {
188 Writer.AddDeclRef(T->getDecl(), Record);
189 assert(!T->isBeingDefined() &&
190 "Cannot serialize in the middle of a type definition");
191}
192
193void PCHTypeWriter::VisitRecordType(const RecordType *T) {
194 VisitTagType(T);
195 Code = pch::TYPE_RECORD;
196}
197
198void PCHTypeWriter::VisitEnumType(const EnumType *T) {
199 VisitTagType(T);
200 Code = pch::TYPE_ENUM;
201}
202
203void
204PCHTypeWriter::VisitTemplateSpecializationType(
205 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000206 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000207 assert(false && "Cannot serialize template specialization types");
208}
209
210void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000211 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000212 assert(false && "Cannot serialize qualified name types");
213}
214
215void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
216 Writer.AddDeclRef(T->getDecl(), Record);
217 Code = pch::TYPE_OBJC_INTERFACE;
218}
219
220void
221PCHTypeWriter::VisitObjCQualifiedInterfaceType(
222 const ObjCQualifiedInterfaceType *T) {
223 VisitObjCInterfaceType(T);
224 Record.push_back(T->getNumProtocols());
225 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
226 Writer.AddDeclRef(T->getProtocol(I), Record);
227 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
228}
229
230void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
231 Record.push_back(T->getNumProtocols());
232 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
233 Writer.AddDeclRef(T->getProtocols(I), Record);
234 Code = pch::TYPE_OBJC_QUALIFIED_ID;
235}
236
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000237//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000238// PCHWriter Implementation
239//===----------------------------------------------------------------------===//
240
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000241static void EmitBlockID(unsigned ID, const char *Name,
242 llvm::BitstreamWriter &Stream,
243 PCHWriter::RecordData &Record) {
244 Record.clear();
245 Record.push_back(ID);
246 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
247
248 // Emit the block name if present.
249 if (Name == 0 || Name[0] == 0) return;
250 Record.clear();
251 while (*Name)
252 Record.push_back(*Name++);
253 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
254}
255
256static void EmitRecordID(unsigned ID, const char *Name,
257 llvm::BitstreamWriter &Stream,
258 PCHWriter::RecordData &Record) {
259 Record.clear();
260 Record.push_back(ID);
261 while (*Name)
262 Record.push_back(*Name++);
263 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000264}
265
266static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
267 PCHWriter::RecordData &Record) {
268#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
269 RECORD(STMT_STOP);
270 RECORD(STMT_NULL_PTR);
271 RECORD(STMT_NULL);
272 RECORD(STMT_COMPOUND);
273 RECORD(STMT_CASE);
274 RECORD(STMT_DEFAULT);
275 RECORD(STMT_LABEL);
276 RECORD(STMT_IF);
277 RECORD(STMT_SWITCH);
278 RECORD(STMT_WHILE);
279 RECORD(STMT_DO);
280 RECORD(STMT_FOR);
281 RECORD(STMT_GOTO);
282 RECORD(STMT_INDIRECT_GOTO);
283 RECORD(STMT_CONTINUE);
284 RECORD(STMT_BREAK);
285 RECORD(STMT_RETURN);
286 RECORD(STMT_DECL);
287 RECORD(STMT_ASM);
288 RECORD(EXPR_PREDEFINED);
289 RECORD(EXPR_DECL_REF);
290 RECORD(EXPR_INTEGER_LITERAL);
291 RECORD(EXPR_FLOATING_LITERAL);
292 RECORD(EXPR_IMAGINARY_LITERAL);
293 RECORD(EXPR_STRING_LITERAL);
294 RECORD(EXPR_CHARACTER_LITERAL);
295 RECORD(EXPR_PAREN);
296 RECORD(EXPR_UNARY_OPERATOR);
297 RECORD(EXPR_SIZEOF_ALIGN_OF);
298 RECORD(EXPR_ARRAY_SUBSCRIPT);
299 RECORD(EXPR_CALL);
300 RECORD(EXPR_MEMBER);
301 RECORD(EXPR_BINARY_OPERATOR);
302 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
303 RECORD(EXPR_CONDITIONAL_OPERATOR);
304 RECORD(EXPR_IMPLICIT_CAST);
305 RECORD(EXPR_CSTYLE_CAST);
306 RECORD(EXPR_COMPOUND_LITERAL);
307 RECORD(EXPR_EXT_VECTOR_ELEMENT);
308 RECORD(EXPR_INIT_LIST);
309 RECORD(EXPR_DESIGNATED_INIT);
310 RECORD(EXPR_IMPLICIT_VALUE_INIT);
311 RECORD(EXPR_VA_ARG);
312 RECORD(EXPR_ADDR_LABEL);
313 RECORD(EXPR_STMT);
314 RECORD(EXPR_TYPES_COMPATIBLE);
315 RECORD(EXPR_CHOOSE);
316 RECORD(EXPR_GNU_NULL);
317 RECORD(EXPR_SHUFFLE_VECTOR);
318 RECORD(EXPR_BLOCK);
319 RECORD(EXPR_BLOCK_DECL_REF);
320 RECORD(EXPR_OBJC_STRING_LITERAL);
321 RECORD(EXPR_OBJC_ENCODE);
322 RECORD(EXPR_OBJC_SELECTOR_EXPR);
323 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
324 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
325 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
326 RECORD(EXPR_OBJC_KVC_REF_EXPR);
327 RECORD(EXPR_OBJC_MESSAGE_EXPR);
328 RECORD(EXPR_OBJC_SUPER_EXPR);
329 RECORD(STMT_OBJC_FOR_COLLECTION);
330 RECORD(STMT_OBJC_CATCH);
331 RECORD(STMT_OBJC_FINALLY);
332 RECORD(STMT_OBJC_AT_TRY);
333 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
334 RECORD(STMT_OBJC_AT_THROW);
335#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000336}
337
338void PCHWriter::WriteBlockInfoBlock() {
339 RecordData Record;
340 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
341
Chris Lattner2f4efd12009-04-27 00:40:25 +0000342#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000343#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
344
345 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000346 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000347 RECORD(TYPE_OFFSET);
348 RECORD(DECL_OFFSET);
349 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000350 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000351 RECORD(IDENTIFIER_OFFSET);
352 RECORD(IDENTIFIER_TABLE);
353 RECORD(EXTERNAL_DEFINITIONS);
354 RECORD(SPECIAL_TYPES);
355 RECORD(STATISTICS);
356 RECORD(TENTATIVE_DEFINITIONS);
357 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
358 RECORD(SELECTOR_OFFSETS);
359 RECORD(METHOD_POOL);
360 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000361 RECORD(SOURCE_LOCATION_OFFSETS);
362 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000363 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000364 RECORD(EXT_VECTOR_DECLS);
365 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000366
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000367 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000368 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000369 RECORD(SM_SLOC_FILE_ENTRY);
370 RECORD(SM_SLOC_BUFFER_ENTRY);
371 RECORD(SM_SLOC_BUFFER_BLOB);
372 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
373 RECORD(SM_LINE_TABLE);
374 RECORD(SM_HEADER_FILE_INFO);
375
376 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000377 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000378 RECORD(PP_MACRO_OBJECT_LIKE);
379 RECORD(PP_MACRO_FUNCTION_LIKE);
380 RECORD(PP_TOKEN);
381
382 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000383 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000384 RECORD(TYPE_EXT_QUAL);
385 RECORD(TYPE_FIXED_WIDTH_INT);
386 RECORD(TYPE_COMPLEX);
387 RECORD(TYPE_POINTER);
388 RECORD(TYPE_BLOCK_POINTER);
389 RECORD(TYPE_LVALUE_REFERENCE);
390 RECORD(TYPE_RVALUE_REFERENCE);
391 RECORD(TYPE_MEMBER_POINTER);
392 RECORD(TYPE_CONSTANT_ARRAY);
393 RECORD(TYPE_INCOMPLETE_ARRAY);
394 RECORD(TYPE_VARIABLE_ARRAY);
395 RECORD(TYPE_VECTOR);
396 RECORD(TYPE_EXT_VECTOR);
397 RECORD(TYPE_FUNCTION_PROTO);
398 RECORD(TYPE_FUNCTION_NO_PROTO);
399 RECORD(TYPE_TYPEDEF);
400 RECORD(TYPE_TYPEOF_EXPR);
401 RECORD(TYPE_TYPEOF);
402 RECORD(TYPE_RECORD);
403 RECORD(TYPE_ENUM);
404 RECORD(TYPE_OBJC_INTERFACE);
405 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
406 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000407 // Statements and Exprs can occur in the Types block.
408 AddStmtsExprs(Stream, Record);
409
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000410 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000411 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000412 RECORD(DECL_ATTR);
413 RECORD(DECL_TRANSLATION_UNIT);
414 RECORD(DECL_TYPEDEF);
415 RECORD(DECL_ENUM);
416 RECORD(DECL_RECORD);
417 RECORD(DECL_ENUM_CONSTANT);
418 RECORD(DECL_FUNCTION);
419 RECORD(DECL_OBJC_METHOD);
420 RECORD(DECL_OBJC_INTERFACE);
421 RECORD(DECL_OBJC_PROTOCOL);
422 RECORD(DECL_OBJC_IVAR);
423 RECORD(DECL_OBJC_AT_DEFS_FIELD);
424 RECORD(DECL_OBJC_CLASS);
425 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
426 RECORD(DECL_OBJC_CATEGORY);
427 RECORD(DECL_OBJC_CATEGORY_IMPL);
428 RECORD(DECL_OBJC_IMPLEMENTATION);
429 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
430 RECORD(DECL_OBJC_PROPERTY);
431 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000432 RECORD(DECL_FIELD);
433 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000434 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000435 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000436 RECORD(DECL_ORIGINAL_PARM_VAR);
437 RECORD(DECL_FILE_SCOPE_ASM);
438 RECORD(DECL_BLOCK);
439 RECORD(DECL_CONTEXT_LEXICAL);
440 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000441 // Statements and Exprs can occur in the Decls block.
442 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000443#undef RECORD
444#undef BLOCK
445 Stream.ExitBlock();
446}
447
448
Douglas Gregorab41e632009-04-27 22:23:34 +0000449/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
450void PCHWriter::WriteMetadata(const TargetInfo &Target) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000451 using namespace llvm;
452 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Douglas Gregorab41e632009-04-27 22:23:34 +0000453 Abbrev->Add(BitCodeAbbrevOp(pch::METADATA));
454 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
459 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000460
461 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000462 Record.push_back(pch::METADATA);
463 Record.push_back(pch::VERSION_MAJOR);
464 Record.push_back(pch::VERSION_MINOR);
465 Record.push_back(CLANG_VERSION_MAJOR);
466 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000467 const char *Triple = Target.getTargetTriple();
Douglas Gregorab41e632009-04-27 22:23:34 +0000468 Stream.EmitRecordWithBlob(AbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000469}
470
471/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000472void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
473 RecordData Record;
474 Record.push_back(LangOpts.Trigraphs);
475 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
476 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
477 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
478 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
479 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
480 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
481 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
482 Record.push_back(LangOpts.C99); // C99 Support
483 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
484 Record.push_back(LangOpts.CPlusPlus); // C++ Support
485 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000486 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
487
488 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
489 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
490 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
491
492 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000493 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
494 Record.push_back(LangOpts.LaxVectorConversions);
495 Record.push_back(LangOpts.Exceptions); // Support exception handling.
496
497 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
498 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
499 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
500
Chris Lattnerea5ce472009-04-27 07:35:58 +0000501 // Whether static initializers are protected by locks.
502 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000503 Record.push_back(LangOpts.Blocks); // block extension to C
504 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
505 // they are unused.
506 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
507 // (modulo the platform support).
508
509 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
510 // signed integer arithmetic overflows.
511
512 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
513 // may be ripped out at any time.
514
515 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
516 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
517 // defined.
518 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
519 // opposed to __DYNAMIC__).
520 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
521
522 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
523 // used (instead of C99 semantics).
524 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
525 Record.push_back(LangOpts.getGCMode());
526 Record.push_back(LangOpts.getVisibilityMode());
527 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000528 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000529}
530
Douglas Gregor14f79002009-04-10 03:52:48 +0000531//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000532// stat cache Serialization
533//===----------------------------------------------------------------------===//
534
535namespace {
536// Trait used for the on-disk hash table of stat cache results.
537class VISIBILITY_HIDDEN PCHStatCacheTrait {
538public:
539 typedef const char * key_type;
540 typedef key_type key_type_ref;
541
542 typedef std::pair<int, struct stat> data_type;
543 typedef const data_type& data_type_ref;
544
545 static unsigned ComputeHash(const char *path) {
546 return BernsteinHash(path);
547 }
548
549 std::pair<unsigned,unsigned>
550 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
551 data_type_ref Data) {
552 unsigned StrLen = strlen(path);
553 clang::io::Emit16(Out, StrLen);
554 unsigned DataLen = 1; // result value
555 if (Data.first == 0)
556 DataLen += 4 + 4 + 2 + 8 + 8;
557 clang::io::Emit8(Out, DataLen);
558 return std::make_pair(StrLen + 1, DataLen);
559 }
560
561 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
562 Out.write(path, KeyLen);
563 }
564
565 void EmitData(llvm::raw_ostream& Out, key_type_ref,
566 data_type_ref Data, unsigned DataLen) {
567 using namespace clang::io;
568 uint64_t Start = Out.tell(); (void)Start;
569
570 // Result of stat()
571 Emit8(Out, Data.first? 1 : 0);
572
573 if (Data.first == 0) {
574 Emit32(Out, (uint32_t) Data.second.st_ino);
575 Emit32(Out, (uint32_t) Data.second.st_dev);
576 Emit16(Out, (uint16_t) Data.second.st_mode);
577 Emit64(Out, (uint64_t) Data.second.st_mtime);
578 Emit64(Out, (uint64_t) Data.second.st_size);
579 }
580
581 assert(Out.tell() - Start == DataLen && "Wrong data length");
582 }
583};
584} // end anonymous namespace
585
586/// \brief Write the stat() system call cache to the PCH file.
587void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
588 // Build the on-disk hash table containing information about every
589 // stat() call.
590 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
591 unsigned NumStatEntries = 0;
592 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
593 StatEnd = StatCalls.end();
594 Stat != StatEnd; ++Stat, ++NumStatEntries)
595 Generator.insert(Stat->first(), Stat->second);
596
597 // Create the on-disk hash table in a buffer.
598 llvm::SmallVector<char, 4096> StatCacheData;
599 uint32_t BucketOffset;
600 {
601 llvm::raw_svector_ostream Out(StatCacheData);
602 // Make sure that no bucket is at offset 0
603 clang::io::Emit32(Out, 0);
604 BucketOffset = Generator.Emit(Out);
605 }
606
607 // Create a blob abbreviation
608 using namespace llvm;
609 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
610 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
611 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
612 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
614 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
615
616 // Write the stat cache
617 RecordData Record;
618 Record.push_back(pch::STAT_CACHE);
619 Record.push_back(BucketOffset);
620 Record.push_back(NumStatEntries);
621 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
622 &StatCacheData.front(),
623 StatCacheData.size());
624}
625
626//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000627// Source Manager Serialization
628//===----------------------------------------------------------------------===//
629
630/// \brief Create an abbreviation for the SLocEntry that refers to a
631/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000632static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000633 using namespace llvm;
634 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
635 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
638 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000641 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000642}
643
644/// \brief Create an abbreviation for the SLocEntry that refers to a
645/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000646static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000647 using namespace llvm;
648 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
649 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000655 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000656}
657
658/// \brief Create an abbreviation for the SLocEntry that refers to a
659/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000660static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000661 using namespace llvm;
662 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
663 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000665 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000666}
667
668/// \brief Create an abbreviation for the SLocEntry that refers to an
669/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000670static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000671 using namespace llvm;
672 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
673 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000679 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000680}
681
682/// \brief Writes the block containing the serialized form of the
683/// source manager.
684///
685/// TODO: We should probably use an on-disk hash table (stored in a
686/// blob), indexed based on the file name, so that we only create
687/// entries for files that we actually need. In the common case (no
688/// errors), we probably won't have to create file entries for any of
689/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000690void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
691 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000692 RecordData Record;
693
Chris Lattnerf04ad692009-04-10 17:16:57 +0000694 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000695 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000696
697 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000698 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
699 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
700 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
701 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000702
Douglas Gregorbd945002009-04-13 16:31:14 +0000703 // Write the line table.
704 if (SourceMgr.hasLineTable()) {
705 LineTableInfo &LineTable = SourceMgr.getLineTable();
706
707 // Emit the file names
708 Record.push_back(LineTable.getNumFilenames());
709 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
710 // Emit the file name
711 const char *Filename = LineTable.getFilename(I);
712 unsigned FilenameLen = Filename? strlen(Filename) : 0;
713 Record.push_back(FilenameLen);
714 if (FilenameLen)
715 Record.insert(Record.end(), Filename, Filename + FilenameLen);
716 }
717
718 // Emit the line entries
719 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
720 L != LEnd; ++L) {
721 // Emit the file ID
722 Record.push_back(L->first);
723
724 // Emit the line entries
725 Record.push_back(L->second.size());
726 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
727 LEEnd = L->second.end();
728 LE != LEEnd; ++LE) {
729 Record.push_back(LE->FileOffset);
730 Record.push_back(LE->LineNo);
731 Record.push_back(LE->FilenameID);
732 Record.push_back((unsigned)LE->FileKind);
733 Record.push_back(LE->IncludeOffset);
734 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000735 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000736 }
737 }
738
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000739 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000740 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000741 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000742 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
743 E = HS.header_file_end();
744 I != E; ++I) {
745 Record.push_back(I->isImport);
746 Record.push_back(I->DirInfo);
747 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000748 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000749 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
750 Record.clear();
751 }
752
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000753 // Write out the source location entry table. We skip the first
754 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000755 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000756 RecordData PreloadSLocs;
757 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
758 for (SourceManager::sloc_entry_iterator
759 SLoc = SourceMgr.sloc_entry_begin() + 1,
760 SLocEnd = SourceMgr.sloc_entry_end();
761 SLoc != SLocEnd; ++SLoc) {
762 // Record the offset of this source-location entry.
763 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
764
765 // Figure out which record code to use.
766 unsigned Code;
767 if (SLoc->isFile()) {
768 if (SLoc->getFile().getContentCache()->Entry)
769 Code = pch::SM_SLOC_FILE_ENTRY;
770 else
771 Code = pch::SM_SLOC_BUFFER_ENTRY;
772 } else
773 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
774 Record.clear();
775 Record.push_back(Code);
776
777 Record.push_back(SLoc->getOffset());
778 if (SLoc->isFile()) {
779 const SrcMgr::FileInfo &File = SLoc->getFile();
780 Record.push_back(File.getIncludeLoc().getRawEncoding());
781 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
782 Record.push_back(File.hasLineDirectives());
783
784 const SrcMgr::ContentCache *Content = File.getContentCache();
785 if (Content->Entry) {
786 // The source location entry is a file. The blob associated
787 // with this entry is the file name.
788 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
789 Content->Entry->getName(),
790 strlen(Content->Entry->getName()));
791
792 // FIXME: For now, preload all file source locations, so that
793 // we get the appropriate File entries in the reader. This is
794 // a temporary measure.
795 PreloadSLocs.push_back(SLocEntryOffsets.size());
796 } else {
797 // The source location entry is a buffer. The blob associated
798 // with this entry contains the contents of the buffer.
799
800 // We add one to the size so that we capture the trailing NULL
801 // that is required by llvm::MemoryBuffer::getMemBuffer (on
802 // the reader side).
803 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
804 const char *Name = Buffer->getBufferIdentifier();
805 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
806 Record.clear();
807 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
808 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
809 Buffer->getBufferStart(),
810 Buffer->getBufferSize() + 1);
811
812 if (strcmp(Name, "<built-in>") == 0)
813 PreloadSLocs.push_back(SLocEntryOffsets.size());
814 }
815 } else {
816 // The source location entry is an instantiation.
817 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
818 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
819 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
820 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
821
822 // Compute the token length for this macro expansion.
823 unsigned NextOffset = SourceMgr.getNextOffset();
824 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
825 if (++NextSLoc != SLocEnd)
826 NextOffset = NextSLoc->getOffset();
827 Record.push_back(NextOffset - SLoc->getOffset() - 1);
828 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
829 }
830 }
831
Douglas Gregorc9490c02009-04-16 22:23:12 +0000832 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000833
834 if (SLocEntryOffsets.empty())
835 return;
836
837 // Write the source-location offsets table into the PCH block. This
838 // table is used for lazily loading source-location information.
839 using namespace llvm;
840 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
841 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
843 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
845 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
846
847 Record.clear();
848 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
849 Record.push_back(SLocEntryOffsets.size());
850 Record.push_back(SourceMgr.getNextOffset());
851 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
852 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000853 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000854
855 // Write the source location entry preloads array, telling the PCH
856 // reader which source locations entries it should load eagerly.
857 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000858}
859
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000860//===----------------------------------------------------------------------===//
861// Preprocessor Serialization
862//===----------------------------------------------------------------------===//
863
Chris Lattner0b1fb982009-04-10 17:15:23 +0000864/// \brief Writes the block containing the serialized form of the
865/// preprocessor.
866///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000867void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000868 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000869
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000870 // If the preprocessor __COUNTER__ value has been bumped, remember it.
871 if (PP.getCounterValue() != 0) {
872 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000873 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000874 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000875 }
876
877 // Enter the preprocessor block.
878 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000879
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000880 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
881 // FIXME: use diagnostics subsystem for localization etc.
882 if (PP.SawDateOrTime())
883 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
884
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000885 // Loop over all the macro definitions that are live at the end of the file,
886 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000887 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
888 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000889 // FIXME: This emits macros in hash table order, we should do it in a stable
890 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000891 MacroInfo *MI = I->second;
892
893 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
894 // been redefined by the header (in which case they are not isBuiltinMacro).
895 if (MI->isBuiltinMacro())
896 continue;
897
Douglas Gregor37e26842009-04-21 23:56:24 +0000898 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000899 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000900 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000901 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
902 Record.push_back(MI->isUsed());
903
904 unsigned Code;
905 if (MI->isObjectLike()) {
906 Code = pch::PP_MACRO_OBJECT_LIKE;
907 } else {
908 Code = pch::PP_MACRO_FUNCTION_LIKE;
909
910 Record.push_back(MI->isC99Varargs());
911 Record.push_back(MI->isGNUVarargs());
912 Record.push_back(MI->getNumArgs());
913 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
914 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000915 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000916 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000917 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000918 Record.clear();
919
Chris Lattnerdf961c22009-04-10 18:08:30 +0000920 // Emit the tokens array.
921 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
922 // Note that we know that the preprocessor does not have any annotation
923 // tokens in it because they are created by the parser, and thus can't be
924 // in a macro definition.
925 const Token &Tok = MI->getReplacementToken(TokNo);
926
927 Record.push_back(Tok.getLocation().getRawEncoding());
928 Record.push_back(Tok.getLength());
929
Chris Lattnerdf961c22009-04-10 18:08:30 +0000930 // FIXME: When reading literal tokens, reconstruct the literal pointer if
931 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000932 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000933
934 // FIXME: Should translate token kind to a stable encoding.
935 Record.push_back(Tok.getKind());
936 // FIXME: Should translate token flags to a stable encoding.
937 Record.push_back(Tok.getFlags());
938
Douglas Gregorc9490c02009-04-16 22:23:12 +0000939 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000940 Record.clear();
941 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000942 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000943 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000944 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000945}
946
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000947//===----------------------------------------------------------------------===//
948// Type Serialization
949//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000950
Douglas Gregor2cf26342009-04-09 22:27:44 +0000951/// \brief Write the representation of a type to the PCH stream.
952void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000953 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000954 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000955 ID = NextTypeID++;
956
957 // Record the offset for this type.
958 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000959 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000960 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
961 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000962 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000963 }
964
965 RecordData Record;
966
967 // Emit the type's representation.
968 PCHTypeWriter W(*this, Record);
969 switch (T->getTypeClass()) {
970 // For all of the concrete, non-dependent types, call the
971 // appropriate visitor function.
972#define TYPE(Class, Base) \
973 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
974#define ABSTRACT_TYPE(Class, Base)
975#define DEPENDENT_TYPE(Class, Base)
976#include "clang/AST/TypeNodes.def"
977
978 // For all of the dependent type nodes (which only occur in C++
979 // templates), produce an error.
980#define TYPE(Class, Base)
981#define DEPENDENT_TYPE(Class, Base) case Type::Class:
982#include "clang/AST/TypeNodes.def"
983 assert(false && "Cannot serialize dependent type nodes");
984 break;
985 }
986
987 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000988 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +0000989
990 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000991 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000992}
993
994/// \brief Write a block containing all of the types.
995void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000996 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000997 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000998
Douglas Gregor366809a2009-04-26 03:49:13 +0000999 // Emit all of the types that need to be emitted (so far).
1000 while (!TypesToEmit.empty()) {
1001 const Type *T = TypesToEmit.front();
1002 TypesToEmit.pop();
1003 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1004 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 }
1006
1007 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001008 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001009}
1010
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001011//===----------------------------------------------------------------------===//
1012// Declaration Serialization
1013//===----------------------------------------------------------------------===//
1014
Douglas Gregor2cf26342009-04-09 22:27:44 +00001015/// \brief Write the block containing all of the declaration IDs
1016/// lexically declared within the given DeclContext.
1017///
1018/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1019/// bistream, or 0 if no block was written.
1020uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1021 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001022 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001023 return 0;
1024
Douglas Gregorc9490c02009-04-16 22:23:12 +00001025 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001026 RecordData Record;
1027 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1028 DEnd = DC->decls_end(Context);
1029 D != DEnd; ++D)
1030 AddDeclRef(*D, Record);
1031
Douglas Gregor25123082009-04-22 22:34:57 +00001032 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001033 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001034 return Offset;
1035}
1036
1037/// \brief Write the block containing all of the declaration IDs
1038/// visible from the given DeclContext.
1039///
1040/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1041/// bistream, or 0 if no block was written.
1042uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1043 DeclContext *DC) {
1044 if (DC->getPrimaryContext() != DC)
1045 return 0;
1046
Douglas Gregoraff22df2009-04-21 22:32:33 +00001047 // Since there is no name lookup into functions or methods, and we
1048 // perform name lookup for the translation unit via the
1049 // IdentifierInfo chains, don't bother to build a
1050 // visible-declarations table for these entities.
1051 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001052 return 0;
1053
Douglas Gregor2cf26342009-04-09 22:27:44 +00001054 // Force the DeclContext to build a its name-lookup table.
1055 DC->lookup(Context, DeclarationName());
1056
1057 // Serialize the contents of the mapping used for lookup. Note that,
1058 // although we have two very different code paths, the serialized
1059 // representation is the same for both cases: a declaration name,
1060 // followed by a size, followed by references to the visible
1061 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001062 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001063 RecordData Record;
1064 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001065 if (!Map)
1066 return 0;
1067
Douglas Gregor2cf26342009-04-09 22:27:44 +00001068 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1069 D != DEnd; ++D) {
1070 AddDeclarationName(D->first, Record);
1071 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1072 Record.push_back(Result.second - Result.first);
1073 for(; Result.first != Result.second; ++Result.first)
1074 AddDeclRef(*Result.first, Record);
1075 }
1076
1077 if (Record.size() == 0)
1078 return 0;
1079
Douglas Gregorc9490c02009-04-16 22:23:12 +00001080 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001081 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001082 return Offset;
1083}
1084
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001085//===----------------------------------------------------------------------===//
1086// Global Method Pool and Selector Serialization
1087//===----------------------------------------------------------------------===//
1088
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001089namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001090// Trait used for the on-disk hash table used in the method pool.
1091class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1092 PCHWriter &Writer;
1093
1094public:
1095 typedef Selector key_type;
1096 typedef key_type key_type_ref;
1097
1098 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1099 typedef const data_type& data_type_ref;
1100
1101 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1102
1103 static unsigned ComputeHash(Selector Sel) {
1104 unsigned N = Sel.getNumArgs();
1105 if (N == 0)
1106 ++N;
1107 unsigned R = 5381;
1108 for (unsigned I = 0; I != N; ++I)
1109 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1110 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1111 return R;
1112 }
1113
1114 std::pair<unsigned,unsigned>
1115 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1116 data_type_ref Methods) {
1117 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1118 clang::io::Emit16(Out, KeyLen);
1119 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1120 for (const ObjCMethodList *Method = &Methods.first; Method;
1121 Method = Method->Next)
1122 if (Method->Method)
1123 DataLen += 4;
1124 for (const ObjCMethodList *Method = &Methods.second; Method;
1125 Method = Method->Next)
1126 if (Method->Method)
1127 DataLen += 4;
1128 clang::io::Emit16(Out, DataLen);
1129 return std::make_pair(KeyLen, DataLen);
1130 }
1131
Douglas Gregor83941df2009-04-25 17:48:32 +00001132 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1133 uint64_t Start = Out.tell();
1134 assert((Start >> 32) == 0 && "Selector key offset too large");
1135 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001136 unsigned N = Sel.getNumArgs();
1137 clang::io::Emit16(Out, N);
1138 if (N == 0)
1139 N = 1;
1140 for (unsigned I = 0; I != N; ++I)
1141 clang::io::Emit32(Out,
1142 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1143 }
1144
1145 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001146 data_type_ref Methods, unsigned DataLen) {
1147 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001148 unsigned NumInstanceMethods = 0;
1149 for (const ObjCMethodList *Method = &Methods.first; Method;
1150 Method = Method->Next)
1151 if (Method->Method)
1152 ++NumInstanceMethods;
1153
1154 unsigned NumFactoryMethods = 0;
1155 for (const ObjCMethodList *Method = &Methods.second; Method;
1156 Method = Method->Next)
1157 if (Method->Method)
1158 ++NumFactoryMethods;
1159
1160 clang::io::Emit16(Out, NumInstanceMethods);
1161 clang::io::Emit16(Out, NumFactoryMethods);
1162 for (const ObjCMethodList *Method = &Methods.first; Method;
1163 Method = Method->Next)
1164 if (Method->Method)
1165 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001166 for (const ObjCMethodList *Method = &Methods.second; Method;
1167 Method = Method->Next)
1168 if (Method->Method)
1169 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001170
1171 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001172 }
1173};
1174} // end anonymous namespace
1175
1176/// \brief Write the method pool into the PCH file.
1177///
1178/// The method pool contains both instance and factory methods, stored
1179/// in an on-disk hash table indexed by the selector.
1180void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1181 using namespace llvm;
1182
1183 // Create and write out the blob that contains the instance and
1184 // factor method pools.
1185 bool Empty = true;
1186 {
1187 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1188
1189 // Create the on-disk hash table representation. Start by
1190 // iterating through the instance method pool.
1191 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001192 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001193 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1194 Instance = SemaRef.InstanceMethodPool.begin(),
1195 InstanceEnd = SemaRef.InstanceMethodPool.end();
1196 Instance != InstanceEnd; ++Instance) {
1197 // Check whether there is a factory method with the same
1198 // selector.
1199 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1200 = SemaRef.FactoryMethodPool.find(Instance->first);
1201
1202 if (Factory == SemaRef.FactoryMethodPool.end())
1203 Generator.insert(Instance->first,
1204 std::make_pair(Instance->second,
1205 ObjCMethodList()));
1206 else
1207 Generator.insert(Instance->first,
1208 std::make_pair(Instance->second, Factory->second));
1209
Douglas Gregor83941df2009-04-25 17:48:32 +00001210 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001211 Empty = false;
1212 }
1213
1214 // Now iterate through the factory method pool, to pick up any
1215 // selectors that weren't already in the instance method pool.
1216 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1217 Factory = SemaRef.FactoryMethodPool.begin(),
1218 FactoryEnd = SemaRef.FactoryMethodPool.end();
1219 Factory != FactoryEnd; ++Factory) {
1220 // Check whether there is an instance method with the same
1221 // selector. If so, there is no work to do here.
1222 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1223 = SemaRef.InstanceMethodPool.find(Factory->first);
1224
Douglas Gregor83941df2009-04-25 17:48:32 +00001225 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001226 Generator.insert(Factory->first,
1227 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001228 ++NumSelectorsInMethodPool;
1229 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001230
1231 Empty = false;
1232 }
1233
Douglas Gregor83941df2009-04-25 17:48:32 +00001234 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001235 return;
1236
1237 // Create the on-disk hash table in a buffer.
1238 llvm::SmallVector<char, 4096> MethodPool;
1239 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001240 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001241 {
1242 PCHMethodPoolTrait Trait(*this);
1243 llvm::raw_svector_ostream Out(MethodPool);
1244 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001245 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001246 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001247
1248 // For every selector that we have seen but which was not
1249 // written into the hash table, write the selector itself and
1250 // record it's offset.
1251 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1252 if (SelectorOffsets[I] == 0)
1253 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001254 }
1255
1256 // Create a blob abbreviation
1257 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1258 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1259 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001260 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1262 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1263
Douglas Gregor83941df2009-04-25 17:48:32 +00001264 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001265 RecordData Record;
1266 Record.push_back(pch::METHOD_POOL);
1267 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001268 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001269 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1270 &MethodPool.front(),
1271 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001272
1273 // Create a blob abbreviation for the selector table offsets.
1274 Abbrev = new BitCodeAbbrev();
1275 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1276 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1277 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1278 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1279
1280 // Write the selector offsets table.
1281 Record.clear();
1282 Record.push_back(pch::SELECTOR_OFFSETS);
1283 Record.push_back(SelectorOffsets.size());
1284 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1285 (const char *)&SelectorOffsets.front(),
1286 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001287 }
1288}
1289
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001290//===----------------------------------------------------------------------===//
1291// Identifier Table Serialization
1292//===----------------------------------------------------------------------===//
1293
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001294namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001295class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1296 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001297 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001298
Douglas Gregora92193e2009-04-28 21:18:29 +00001299 /// \brief Determines whether this is an "interesting" identifier
1300 /// that needs a full IdentifierInfo structure written into the hash
1301 /// table.
1302 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1303 return II->isPoisoned() ||
1304 II->isExtensionToken() ||
1305 II->hasMacroDefinition() ||
1306 II->getObjCOrBuiltinID() ||
1307 II->getFETokenInfo<void>();
1308 }
1309
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001310public:
1311 typedef const IdentifierInfo* key_type;
1312 typedef key_type key_type_ref;
1313
1314 typedef pch::IdentID data_type;
1315 typedef data_type data_type_ref;
1316
Douglas Gregor37e26842009-04-21 23:56:24 +00001317 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1318 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001319
1320 static unsigned ComputeHash(const IdentifierInfo* II) {
1321 return clang::BernsteinHash(II->getName());
1322 }
1323
Douglas Gregor37e26842009-04-21 23:56:24 +00001324 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001325 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1326 pch::IdentID ID) {
1327 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001328 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1329 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001330 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001331 if (II->hasMacroDefinition() &&
1332 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001333 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001334 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1335 DEnd = IdentifierResolver::end();
1336 D != DEnd; ++D)
1337 DataLen += sizeof(pch::DeclID);
1338 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001339 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001340 // We emit the key length after the data length so that every
1341 // string is preceded by a 16-bit length. This matches the PTH
1342 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001343 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001344 return std::make_pair(KeyLen, DataLen);
1345 }
1346
1347 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1348 unsigned KeyLen) {
1349 // Record the location of the key data. This is used when generating
1350 // the mapping from persistent IDs to strings.
1351 Writer.SetIdentifierOffset(II, Out.tell());
1352 Out.write(II->getName(), KeyLen);
1353 }
1354
1355 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1356 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001357 if (!isInterestingIdentifier(II)) {
1358 clang::io::Emit32(Out, ID << 1);
1359 return;
1360 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001361
Douglas Gregora92193e2009-04-28 21:18:29 +00001362 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001363 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001364 bool hasMacroDefinition =
1365 II->hasMacroDefinition() &&
1366 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001367 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001368 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001369 Bits = (Bits << 1) | II->isExtensionToken();
1370 Bits = (Bits << 1) | II->isPoisoned();
1371 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001372 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001373
Douglas Gregor37e26842009-04-21 23:56:24 +00001374 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001375 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001376
Douglas Gregor668c1a42009-04-21 22:25:48 +00001377 // Emit the declaration IDs in reverse order, because the
1378 // IdentifierResolver provides the declarations as they would be
1379 // visible (e.g., the function "stat" would come before the struct
1380 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1381 // adds declarations to the end of the list (so we need to see the
1382 // struct "status" before the function "status").
1383 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1384 IdentifierResolver::end());
1385 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1386 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001387 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001388 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001389 }
1390};
1391} // end anonymous namespace
1392
Douglas Gregorafaf3082009-04-11 00:14:32 +00001393/// \brief Write the identifier table into the PCH file.
1394///
1395/// The identifier table consists of a blob containing string data
1396/// (the actual identifiers themselves) and a separate "offsets" index
1397/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001398void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001399 using namespace llvm;
1400
1401 // Create and write out the blob that contains the identifier
1402 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001403 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001404 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1405
Douglas Gregor92b059e2009-04-28 20:33:11 +00001406 // Look for any identifiers that were named while processing the
1407 // headers, but are otherwise not needed. We add these to the hash
1408 // table to enable checking of the predefines buffer in the case
1409 // where the user adds new macro definitions when building the PCH
1410 // file.
1411 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1412 IDEnd = PP.getIdentifierTable().end();
1413 ID != IDEnd; ++ID)
1414 getIdentifierRef(ID->second);
1415
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001416 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001417 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001418 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1419 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1420 ID != IDEnd; ++ID) {
1421 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001422 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001423 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001424
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001425 // Create the on-disk hash table in a buffer.
1426 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001427 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001428 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001429 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001430 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001431 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001432 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001433 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001434 }
1435
1436 // Create a blob abbreviation
1437 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1438 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001439 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001440 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001441 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001442
1443 // Write the identifier table
1444 RecordData Record;
1445 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001446 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001447 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1448 &IdentifierTable.front(),
1449 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001450 }
1451
1452 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001453 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1454 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1457 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1458
1459 RecordData Record;
1460 Record.push_back(pch::IDENTIFIER_OFFSET);
1461 Record.push_back(IdentifierOffsets.size());
1462 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1463 (const char *)&IdentifierOffsets.front(),
1464 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001465}
1466
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001467//===----------------------------------------------------------------------===//
1468// General Serialization Routines
1469//===----------------------------------------------------------------------===//
1470
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001471/// \brief Write a record containing the given attributes.
1472void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1473 RecordData Record;
1474 for (; Attr; Attr = Attr->getNext()) {
1475 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1476 Record.push_back(Attr->isInherited());
1477 switch (Attr->getKind()) {
1478 case Attr::Alias:
1479 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1480 break;
1481
1482 case Attr::Aligned:
1483 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1484 break;
1485
1486 case Attr::AlwaysInline:
1487 break;
1488
1489 case Attr::AnalyzerNoReturn:
1490 break;
1491
1492 case Attr::Annotate:
1493 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1494 break;
1495
1496 case Attr::AsmLabel:
1497 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1498 break;
1499
1500 case Attr::Blocks:
1501 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1502 break;
1503
1504 case Attr::Cleanup:
1505 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1506 break;
1507
1508 case Attr::Const:
1509 break;
1510
1511 case Attr::Constructor:
1512 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1513 break;
1514
1515 case Attr::DLLExport:
1516 case Attr::DLLImport:
1517 case Attr::Deprecated:
1518 break;
1519
1520 case Attr::Destructor:
1521 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1522 break;
1523
1524 case Attr::FastCall:
1525 break;
1526
1527 case Attr::Format: {
1528 const FormatAttr *Format = cast<FormatAttr>(Attr);
1529 AddString(Format->getType(), Record);
1530 Record.push_back(Format->getFormatIdx());
1531 Record.push_back(Format->getFirstArg());
1532 break;
1533 }
1534
Chris Lattnercf2a7212009-04-20 19:12:28 +00001535 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001536 case Attr::IBOutletKind:
1537 case Attr::NoReturn:
1538 case Attr::NoThrow:
1539 case Attr::Nodebug:
1540 case Attr::Noinline:
1541 break;
1542
1543 case Attr::NonNull: {
1544 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1545 Record.push_back(NonNull->size());
1546 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1547 break;
1548 }
1549
1550 case Attr::ObjCException:
1551 case Attr::ObjCNSObject:
Ted Kremenek31c215e2009-05-04 17:29:57 +00001552 case Attr::CFOwnershipRelease:
1553 case Attr::CFOwnershipRetain:
Ted Kremenek75494ff2009-05-04 19:10:19 +00001554 case Attr::NSOwnershipMakeCollectable:
1555 case Attr::NSOwnershipRelease:
1556 case Attr::NSOwnershipRetain:
1557 case Attr::NSOwnershipReturns:
Douglas Gregor68a2eb02009-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 Gregorc9490c02009-04-16 22:23:12 +00001595 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-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 Gregor3251ceb2009-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 Gregor2b3a5a82009-04-25 19:10:14 +00001606 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001607}
1608
Douglas Gregor83941df2009-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 Gregorc9490c02009-04-16 22:23:12 +00001617PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001618 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001619 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1620 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001621
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001622void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001623 using namespace llvm;
1624
Douglas Gregore7785042009-04-20 15:53:59 +00001625 ASTContext &Context = SemaRef.Context;
1626 Preprocessor &PP = SemaRef.PP;
1627
Douglas Gregor2cf26342009-04-09 22:27:44 +00001628 // Emit the file header.
Douglas Gregorc9490c02009-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 Lattnerb145b1e2009-04-26 22:26:21 +00001633
1634 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-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 Gregor2deaea32009-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 Gregor4c0e86b2009-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 Gregor14c22f22009-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 Gregorb81c1702009-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 Gregor2cf26342009-04-09 22:27:44 +00001681 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001682 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001683 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorab41e632009-04-27 22:23:34 +00001684 WriteMetadata(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001685 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001686 if (StatCalls)
1687 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001688 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001689 WritePreprocessor(PP);
Douglas Gregor366809a2009-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 Gregorf0aaf7a2009-04-24 21:10:55 +00001700 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001701 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-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 Lattnerc732f5a2009-04-27 18:24:17 +00001714 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-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 Lattnerc732f5a2009-04-27 18:24:17 +00001727 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001728
1729 // Write the record of special types.
1730 Record.clear();
1731 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-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 Gregorad1de002009-04-18 05:55:16 +00001738 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1739
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001740 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001741 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001742 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-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 Gregor14c22f22009-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 Gregorb81c1702009-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 Gregor3e1af842009-04-17 22:13:46 +00001760
1761 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001762 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001763 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001764 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001765 Record.push_back(NumLexicalDeclContexts);
1766 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001767 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001768 Stream.ExitBlock();
Douglas Gregor2cf26342009-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 Gregor0a2b45e2009-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 Gregor17fc2232009-04-14 21:55:33 +00001788void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1789 AddAPInt(Value.bitcastToAPInt(), Record);
1790}
1791
Douglas Gregor2cf26342009-04-09 22:27:44 +00001792void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-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 Gregorafaf3082009-04-11 00:14:32 +00001799
1800 pch::IdentID &ID = IdentifierIDs[II];
1801 if (ID == 0)
1802 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001803 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001804}
1805
Steve Naroff90cd1bb2009-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 Gregor2cf26342009-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 Gregore1d918e2009-04-10 23:10:45 +00001827 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-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;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001837 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001838 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1839 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1840 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1841 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1842 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1843 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1844 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001845 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001846 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1847 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1848 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1849 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1850 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1851 }
1852
1853 Record.push_back((ID << 3) | T.getCVRQualifiers());
1854 return;
1855 }
1856
Douglas Gregor8038d512009-04-10 17:25:41 +00001857 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001858 if (ID == 0) {
1859 // We haven't seen this type before. Assign it a new ID and put it
1860 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001861 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001862 TypesToEmit.push(T.getTypePtr());
1863 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001864
1865 // Encode the type qualifiers in the type reference.
1866 Record.push_back((ID << 3) | T.getCVRQualifiers());
1867}
1868
1869void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1870 if (D == 0) {
1871 Record.push_back(0);
1872 return;
1873 }
1874
Douglas Gregor8038d512009-04-10 17:25:41 +00001875 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001876 if (ID == 0) {
1877 // We haven't seen this declaration before. Give it a new ID and
1878 // enqueue it in the list of declarations to emit.
1879 ID = DeclIDs.size();
1880 DeclsToEmit.push(const_cast<Decl *>(D));
1881 }
1882
1883 Record.push_back(ID);
1884}
1885
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001886pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1887 if (D == 0)
1888 return 0;
1889
1890 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1891 return DeclIDs[D];
1892}
1893
Douglas Gregor2cf26342009-04-09 22:27:44 +00001894void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001895 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001896 Record.push_back(Name.getNameKind());
1897 switch (Name.getNameKind()) {
1898 case DeclarationName::Identifier:
1899 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1900 break;
1901
1902 case DeclarationName::ObjCZeroArgSelector:
1903 case DeclarationName::ObjCOneArgSelector:
1904 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001905 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001906 break;
1907
1908 case DeclarationName::CXXConstructorName:
1909 case DeclarationName::CXXDestructorName:
1910 case DeclarationName::CXXConversionFunctionName:
1911 AddTypeRef(Name.getCXXNameType(), Record);
1912 break;
1913
1914 case DeclarationName::CXXOperatorName:
1915 Record.push_back(Name.getCXXOverloadedOperator());
1916 break;
1917
1918 case DeclarationName::CXXUsingDirective:
1919 // No extra data to emit
1920 break;
1921 }
1922}
Douglas Gregor0b748912009-04-14 21:18:50 +00001923