blob: 2d3ca17036bb3a04b8c533ce70eaaafb4860f81e [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
165 Code = pch::TYPE_FUNCTION_PROTO;
166}
167
168void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
169 Writer.AddDeclRef(T->getDecl(), Record);
170 Code = pch::TYPE_TYPEDEF;
171}
172
173void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000174 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000175 Code = pch::TYPE_TYPEOF_EXPR;
176}
177
178void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
179 Writer.AddTypeRef(T->getUnderlyingType(), Record);
180 Code = pch::TYPE_TYPEOF;
181}
182
183void PCHTypeWriter::VisitTagType(const TagType *T) {
184 Writer.AddDeclRef(T->getDecl(), Record);
185 assert(!T->isBeingDefined() &&
186 "Cannot serialize in the middle of a type definition");
187}
188
189void PCHTypeWriter::VisitRecordType(const RecordType *T) {
190 VisitTagType(T);
191 Code = pch::TYPE_RECORD;
192}
193
194void PCHTypeWriter::VisitEnumType(const EnumType *T) {
195 VisitTagType(T);
196 Code = pch::TYPE_ENUM;
197}
198
199void
200PCHTypeWriter::VisitTemplateSpecializationType(
201 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000202 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000203 assert(false && "Cannot serialize template specialization types");
204}
205
206void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000207 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 assert(false && "Cannot serialize qualified name types");
209}
210
211void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
212 Writer.AddDeclRef(T->getDecl(), Record);
213 Code = pch::TYPE_OBJC_INTERFACE;
214}
215
216void
217PCHTypeWriter::VisitObjCQualifiedInterfaceType(
218 const ObjCQualifiedInterfaceType *T) {
219 VisitObjCInterfaceType(T);
220 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000221 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
222 E = T->qual_end(); I != E; ++I)
223 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000224 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
225}
226
227void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
228 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000229 for (ObjCQualifiedIdType::qual_iterator I = T->qual_begin(),
230 E = T->qual_end(); I != E; ++I)
231 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000232 Code = pch::TYPE_OBJC_QUALIFIED_ID;
233}
234
Chris Lattner80f83c62009-04-22 05:57:30 +0000235//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000236// PCHWriter Implementation
237//===----------------------------------------------------------------------===//
238
Chris Lattner920673a2009-04-26 22:26:21 +0000239static void EmitBlockID(unsigned ID, const char *Name,
240 llvm::BitstreamWriter &Stream,
241 PCHWriter::RecordData &Record) {
242 Record.clear();
243 Record.push_back(ID);
244 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
245
246 // Emit the block name if present.
247 if (Name == 0 || Name[0] == 0) return;
248 Record.clear();
249 while (*Name)
250 Record.push_back(*Name++);
251 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
252}
253
254static void EmitRecordID(unsigned ID, const char *Name,
255 llvm::BitstreamWriter &Stream,
256 PCHWriter::RecordData &Record) {
257 Record.clear();
258 Record.push_back(ID);
259 while (*Name)
260 Record.push_back(*Name++);
261 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000262}
263
264static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
265 PCHWriter::RecordData &Record) {
266#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
267 RECORD(STMT_STOP);
268 RECORD(STMT_NULL_PTR);
269 RECORD(STMT_NULL);
270 RECORD(STMT_COMPOUND);
271 RECORD(STMT_CASE);
272 RECORD(STMT_DEFAULT);
273 RECORD(STMT_LABEL);
274 RECORD(STMT_IF);
275 RECORD(STMT_SWITCH);
276 RECORD(STMT_WHILE);
277 RECORD(STMT_DO);
278 RECORD(STMT_FOR);
279 RECORD(STMT_GOTO);
280 RECORD(STMT_INDIRECT_GOTO);
281 RECORD(STMT_CONTINUE);
282 RECORD(STMT_BREAK);
283 RECORD(STMT_RETURN);
284 RECORD(STMT_DECL);
285 RECORD(STMT_ASM);
286 RECORD(EXPR_PREDEFINED);
287 RECORD(EXPR_DECL_REF);
288 RECORD(EXPR_INTEGER_LITERAL);
289 RECORD(EXPR_FLOATING_LITERAL);
290 RECORD(EXPR_IMAGINARY_LITERAL);
291 RECORD(EXPR_STRING_LITERAL);
292 RECORD(EXPR_CHARACTER_LITERAL);
293 RECORD(EXPR_PAREN);
294 RECORD(EXPR_UNARY_OPERATOR);
295 RECORD(EXPR_SIZEOF_ALIGN_OF);
296 RECORD(EXPR_ARRAY_SUBSCRIPT);
297 RECORD(EXPR_CALL);
298 RECORD(EXPR_MEMBER);
299 RECORD(EXPR_BINARY_OPERATOR);
300 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
301 RECORD(EXPR_CONDITIONAL_OPERATOR);
302 RECORD(EXPR_IMPLICIT_CAST);
303 RECORD(EXPR_CSTYLE_CAST);
304 RECORD(EXPR_COMPOUND_LITERAL);
305 RECORD(EXPR_EXT_VECTOR_ELEMENT);
306 RECORD(EXPR_INIT_LIST);
307 RECORD(EXPR_DESIGNATED_INIT);
308 RECORD(EXPR_IMPLICIT_VALUE_INIT);
309 RECORD(EXPR_VA_ARG);
310 RECORD(EXPR_ADDR_LABEL);
311 RECORD(EXPR_STMT);
312 RECORD(EXPR_TYPES_COMPATIBLE);
313 RECORD(EXPR_CHOOSE);
314 RECORD(EXPR_GNU_NULL);
315 RECORD(EXPR_SHUFFLE_VECTOR);
316 RECORD(EXPR_BLOCK);
317 RECORD(EXPR_BLOCK_DECL_REF);
318 RECORD(EXPR_OBJC_STRING_LITERAL);
319 RECORD(EXPR_OBJC_ENCODE);
320 RECORD(EXPR_OBJC_SELECTOR_EXPR);
321 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
322 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
323 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
324 RECORD(EXPR_OBJC_KVC_REF_EXPR);
325 RECORD(EXPR_OBJC_MESSAGE_EXPR);
326 RECORD(EXPR_OBJC_SUPER_EXPR);
327 RECORD(STMT_OBJC_FOR_COLLECTION);
328 RECORD(STMT_OBJC_CATCH);
329 RECORD(STMT_OBJC_FINALLY);
330 RECORD(STMT_OBJC_AT_TRY);
331 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
332 RECORD(STMT_OBJC_AT_THROW);
333#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000334}
335
336void PCHWriter::WriteBlockInfoBlock() {
337 RecordData Record;
338 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
339
Chris Lattner880f3f72009-04-27 00:40:25 +0000340#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000341#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
342
343 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000344 BLOCK(PCH_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000345 RECORD(TYPE_OFFSET);
346 RECORD(DECL_OFFSET);
347 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000348 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000349 RECORD(IDENTIFIER_OFFSET);
350 RECORD(IDENTIFIER_TABLE);
351 RECORD(EXTERNAL_DEFINITIONS);
352 RECORD(SPECIAL_TYPES);
353 RECORD(STATISTICS);
354 RECORD(TENTATIVE_DEFINITIONS);
355 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
356 RECORD(SELECTOR_OFFSETS);
357 RECORD(METHOD_POOL);
358 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000359 RECORD(SOURCE_LOCATION_OFFSETS);
360 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000361 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000362 RECORD(EXT_VECTOR_DECLS);
363 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000364
Chris Lattner920673a2009-04-26 22:26:21 +0000365 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000366 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000367 RECORD(SM_SLOC_FILE_ENTRY);
368 RECORD(SM_SLOC_BUFFER_ENTRY);
369 RECORD(SM_SLOC_BUFFER_BLOB);
370 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
371 RECORD(SM_LINE_TABLE);
372 RECORD(SM_HEADER_FILE_INFO);
373
374 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000375 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000376 RECORD(PP_MACRO_OBJECT_LIKE);
377 RECORD(PP_MACRO_FUNCTION_LIKE);
378 RECORD(PP_TOKEN);
379
380 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000381 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000382 RECORD(TYPE_EXT_QUAL);
383 RECORD(TYPE_FIXED_WIDTH_INT);
384 RECORD(TYPE_COMPLEX);
385 RECORD(TYPE_POINTER);
386 RECORD(TYPE_BLOCK_POINTER);
387 RECORD(TYPE_LVALUE_REFERENCE);
388 RECORD(TYPE_RVALUE_REFERENCE);
389 RECORD(TYPE_MEMBER_POINTER);
390 RECORD(TYPE_CONSTANT_ARRAY);
391 RECORD(TYPE_INCOMPLETE_ARRAY);
392 RECORD(TYPE_VARIABLE_ARRAY);
393 RECORD(TYPE_VECTOR);
394 RECORD(TYPE_EXT_VECTOR);
395 RECORD(TYPE_FUNCTION_PROTO);
396 RECORD(TYPE_FUNCTION_NO_PROTO);
397 RECORD(TYPE_TYPEDEF);
398 RECORD(TYPE_TYPEOF_EXPR);
399 RECORD(TYPE_TYPEOF);
400 RECORD(TYPE_RECORD);
401 RECORD(TYPE_ENUM);
402 RECORD(TYPE_OBJC_INTERFACE);
403 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
404 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000405 // Statements and Exprs can occur in the Types block.
406 AddStmtsExprs(Stream, Record);
407
Chris Lattner920673a2009-04-26 22:26:21 +0000408 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000409 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000410 RECORD(DECL_ATTR);
411 RECORD(DECL_TRANSLATION_UNIT);
412 RECORD(DECL_TYPEDEF);
413 RECORD(DECL_ENUM);
414 RECORD(DECL_RECORD);
415 RECORD(DECL_ENUM_CONSTANT);
416 RECORD(DECL_FUNCTION);
417 RECORD(DECL_OBJC_METHOD);
418 RECORD(DECL_OBJC_INTERFACE);
419 RECORD(DECL_OBJC_PROTOCOL);
420 RECORD(DECL_OBJC_IVAR);
421 RECORD(DECL_OBJC_AT_DEFS_FIELD);
422 RECORD(DECL_OBJC_CLASS);
423 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
424 RECORD(DECL_OBJC_CATEGORY);
425 RECORD(DECL_OBJC_CATEGORY_IMPL);
426 RECORD(DECL_OBJC_IMPLEMENTATION);
427 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
428 RECORD(DECL_OBJC_PROPERTY);
429 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000430 RECORD(DECL_FIELD);
431 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000432 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000433 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000434 RECORD(DECL_ORIGINAL_PARM_VAR);
435 RECORD(DECL_FILE_SCOPE_ASM);
436 RECORD(DECL_BLOCK);
437 RECORD(DECL_CONTEXT_LEXICAL);
438 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000439 // Statements and Exprs can occur in the Decls block.
440 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000441#undef RECORD
442#undef BLOCK
443 Stream.ExitBlock();
444}
445
446
Douglas Gregorb7064742009-04-27 22:23:34 +0000447/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000448void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000449 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000450
451 // Original file name
452 SourceManager &SM = Context.getSourceManager();
453 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
454 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
455 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
456 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
457 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
458
459 llvm::sys::Path MainFilePath(MainFile->getName());
460 std::string MainFileName;
461
462 if (!MainFilePath.isAbsolute()) {
463 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
464 P.appendComponent(MainFilePath.toString());
465 MainFileName = P.toString();
466 } else {
467 MainFileName = MainFilePath.toString();
468 }
469
470 RecordData Record;
471 Record.push_back(pch::ORIGINAL_FILE_NAME);
472 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
473 MainFileName.size());
474 }
475
476 // Metadata
477 const TargetInfo &Target = Context.Target;
478 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
479 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
480 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
481 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
482 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
483 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
484 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
485 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000486
487 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000488 Record.push_back(pch::METADATA);
489 Record.push_back(pch::VERSION_MAJOR);
490 Record.push_back(pch::VERSION_MINOR);
491 Record.push_back(CLANG_VERSION_MAJOR);
492 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000493 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000494 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000495}
496
497/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000498void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
499 RecordData Record;
500 Record.push_back(LangOpts.Trigraphs);
501 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
502 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
503 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
504 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
505 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
506 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
507 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
508 Record.push_back(LangOpts.C99); // C99 Support
509 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
510 Record.push_back(LangOpts.CPlusPlus); // C++ Support
511 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000512 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
513
514 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
515 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
516 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
517
518 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000519 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
520 Record.push_back(LangOpts.LaxVectorConversions);
521 Record.push_back(LangOpts.Exceptions); // Support exception handling.
522
523 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
524 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
525 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
526
Chris Lattnercd4da472009-04-27 07:35:58 +0000527 // Whether static initializers are protected by locks.
528 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000529 Record.push_back(LangOpts.Blocks); // block extension to C
530 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
531 // they are unused.
532 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
533 // (modulo the platform support).
534
535 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
536 // signed integer arithmetic overflows.
537
538 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
539 // may be ripped out at any time.
540
541 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
542 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
543 // defined.
544 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
545 // opposed to __DYNAMIC__).
546 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
547
548 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
549 // used (instead of C99 semantics).
550 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000551 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
552 // be enabled.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000553 Record.push_back(LangOpts.getGCMode());
554 Record.push_back(LangOpts.getVisibilityMode());
555 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000556 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000557}
558
Douglas Gregorab1cef72009-04-10 03:52:48 +0000559//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000560// stat cache Serialization
561//===----------------------------------------------------------------------===//
562
563namespace {
564// Trait used for the on-disk hash table of stat cache results.
565class VISIBILITY_HIDDEN PCHStatCacheTrait {
566public:
567 typedef const char * key_type;
568 typedef key_type key_type_ref;
569
570 typedef std::pair<int, struct stat> data_type;
571 typedef const data_type& data_type_ref;
572
573 static unsigned ComputeHash(const char *path) {
574 return BernsteinHash(path);
575 }
576
577 std::pair<unsigned,unsigned>
578 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
579 data_type_ref Data) {
580 unsigned StrLen = strlen(path);
581 clang::io::Emit16(Out, StrLen);
582 unsigned DataLen = 1; // result value
583 if (Data.first == 0)
584 DataLen += 4 + 4 + 2 + 8 + 8;
585 clang::io::Emit8(Out, DataLen);
586 return std::make_pair(StrLen + 1, DataLen);
587 }
588
589 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
590 Out.write(path, KeyLen);
591 }
592
593 void EmitData(llvm::raw_ostream& Out, key_type_ref,
594 data_type_ref Data, unsigned DataLen) {
595 using namespace clang::io;
596 uint64_t Start = Out.tell(); (void)Start;
597
598 // Result of stat()
599 Emit8(Out, Data.first? 1 : 0);
600
601 if (Data.first == 0) {
602 Emit32(Out, (uint32_t) Data.second.st_ino);
603 Emit32(Out, (uint32_t) Data.second.st_dev);
604 Emit16(Out, (uint16_t) Data.second.st_mode);
605 Emit64(Out, (uint64_t) Data.second.st_mtime);
606 Emit64(Out, (uint64_t) Data.second.st_size);
607 }
608
609 assert(Out.tell() - Start == DataLen && "Wrong data length");
610 }
611};
612} // end anonymous namespace
613
614/// \brief Write the stat() system call cache to the PCH file.
615void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
616 // Build the on-disk hash table containing information about every
617 // stat() call.
618 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
619 unsigned NumStatEntries = 0;
620 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
621 StatEnd = StatCalls.end();
622 Stat != StatEnd; ++Stat, ++NumStatEntries)
623 Generator.insert(Stat->first(), Stat->second);
624
625 // Create the on-disk hash table in a buffer.
626 llvm::SmallVector<char, 4096> StatCacheData;
627 uint32_t BucketOffset;
628 {
629 llvm::raw_svector_ostream Out(StatCacheData);
630 // Make sure that no bucket is at offset 0
631 clang::io::Emit32(Out, 0);
632 BucketOffset = Generator.Emit(Out);
633 }
634
635 // Create a blob abbreviation
636 using namespace llvm;
637 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
638 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
641 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
642 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
643
644 // Write the stat cache
645 RecordData Record;
646 Record.push_back(pch::STAT_CACHE);
647 Record.push_back(BucketOffset);
648 Record.push_back(NumStatEntries);
649 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
650 &StatCacheData.front(),
651 StatCacheData.size());
652}
653
654//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000655// Source Manager Serialization
656//===----------------------------------------------------------------------===//
657
658/// \brief Create an abbreviation for the SLocEntry that refers to a
659/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000660static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000661 using namespace llvm;
662 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
663 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000669 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000670}
671
672/// \brief Create an abbreviation for the SLocEntry that refers to a
673/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000674static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000675 using namespace llvm;
676 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
677 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000683 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000684}
685
686/// \brief Create an abbreviation for the SLocEntry that refers to a
687/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000688static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000689 using namespace llvm;
690 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
691 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
692 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000693 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000694}
695
696/// \brief Create an abbreviation for the SLocEntry that refers to an
697/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000698static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000699 using namespace llvm;
700 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
701 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000707 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000708}
709
710/// \brief Writes the block containing the serialized form of the
711/// source manager.
712///
713/// TODO: We should probably use an on-disk hash table (stored in a
714/// blob), indexed based on the file name, so that we only create
715/// entries for files that we actually need. In the common case (no
716/// errors), we probably won't have to create file entries for any of
717/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000718void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
719 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000720 RecordData Record;
721
Chris Lattner84b04f12009-04-10 17:16:57 +0000722 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000723 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000724
725 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000726 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
727 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
728 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
729 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000730
Douglas Gregor635f97f2009-04-13 16:31:14 +0000731 // Write the line table.
732 if (SourceMgr.hasLineTable()) {
733 LineTableInfo &LineTable = SourceMgr.getLineTable();
734
735 // Emit the file names
736 Record.push_back(LineTable.getNumFilenames());
737 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
738 // Emit the file name
739 const char *Filename = LineTable.getFilename(I);
740 unsigned FilenameLen = Filename? strlen(Filename) : 0;
741 Record.push_back(FilenameLen);
742 if (FilenameLen)
743 Record.insert(Record.end(), Filename, Filename + FilenameLen);
744 }
745
746 // Emit the line entries
747 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
748 L != LEnd; ++L) {
749 // Emit the file ID
750 Record.push_back(L->first);
751
752 // Emit the line entries
753 Record.push_back(L->second.size());
754 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
755 LEEnd = L->second.end();
756 LE != LEEnd; ++LE) {
757 Record.push_back(LE->FileOffset);
758 Record.push_back(LE->LineNo);
759 Record.push_back(LE->FilenameID);
760 Record.push_back((unsigned)LE->FileKind);
761 Record.push_back(LE->IncludeOffset);
762 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000763 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000764 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000765 }
766
Douglas Gregor32e231c2009-04-27 06:38:32 +0000767 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000768 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000769 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000770 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
771 E = HS.header_file_end();
772 I != E; ++I) {
773 Record.push_back(I->isImport);
774 Record.push_back(I->DirInfo);
775 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000776 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000777 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
778 Record.clear();
779 }
780
Douglas Gregor32e231c2009-04-27 06:38:32 +0000781 // Write out the source location entry table. We skip the first
782 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000783 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000784 RecordData PreloadSLocs;
785 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
786 for (SourceManager::sloc_entry_iterator
787 SLoc = SourceMgr.sloc_entry_begin() + 1,
788 SLocEnd = SourceMgr.sloc_entry_end();
789 SLoc != SLocEnd; ++SLoc) {
790 // Record the offset of this source-location entry.
791 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
792
793 // Figure out which record code to use.
794 unsigned Code;
795 if (SLoc->isFile()) {
796 if (SLoc->getFile().getContentCache()->Entry)
797 Code = pch::SM_SLOC_FILE_ENTRY;
798 else
799 Code = pch::SM_SLOC_BUFFER_ENTRY;
800 } else
801 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
802 Record.clear();
803 Record.push_back(Code);
804
805 Record.push_back(SLoc->getOffset());
806 if (SLoc->isFile()) {
807 const SrcMgr::FileInfo &File = SLoc->getFile();
808 Record.push_back(File.getIncludeLoc().getRawEncoding());
809 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
810 Record.push_back(File.hasLineDirectives());
811
812 const SrcMgr::ContentCache *Content = File.getContentCache();
813 if (Content->Entry) {
814 // The source location entry is a file. The blob associated
815 // with this entry is the file name.
816 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
817 Content->Entry->getName(),
818 strlen(Content->Entry->getName()));
819
820 // FIXME: For now, preload all file source locations, so that
821 // we get the appropriate File entries in the reader. This is
822 // a temporary measure.
823 PreloadSLocs.push_back(SLocEntryOffsets.size());
824 } else {
825 // The source location entry is a buffer. The blob associated
826 // with this entry contains the contents of the buffer.
827
828 // We add one to the size so that we capture the trailing NULL
829 // that is required by llvm::MemoryBuffer::getMemBuffer (on
830 // the reader side).
831 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
832 const char *Name = Buffer->getBufferIdentifier();
833 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
834 Record.clear();
835 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
836 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
837 Buffer->getBufferStart(),
838 Buffer->getBufferSize() + 1);
839
840 if (strcmp(Name, "<built-in>") == 0)
841 PreloadSLocs.push_back(SLocEntryOffsets.size());
842 }
843 } else {
844 // The source location entry is an instantiation.
845 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
846 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
847 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
848 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
849
850 // Compute the token length for this macro expansion.
851 unsigned NextOffset = SourceMgr.getNextOffset();
852 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
853 if (++NextSLoc != SLocEnd)
854 NextOffset = NextSLoc->getOffset();
855 Record.push_back(NextOffset - SLoc->getOffset() - 1);
856 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
857 }
858 }
859
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000860 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000861
862 if (SLocEntryOffsets.empty())
863 return;
864
865 // Write the source-location offsets table into the PCH block. This
866 // table is used for lazily loading source-location information.
867 using namespace llvm;
868 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
869 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
873 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
874
875 Record.clear();
876 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
877 Record.push_back(SLocEntryOffsets.size());
878 Record.push_back(SourceMgr.getNextOffset());
879 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
880 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000881 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000882
883 // Write the source location entry preloads array, telling the PCH
884 // reader which source locations entries it should load eagerly.
885 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000886}
887
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000888//===----------------------------------------------------------------------===//
889// Preprocessor Serialization
890//===----------------------------------------------------------------------===//
891
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000892/// \brief Writes the block containing the serialized form of the
893/// preprocessor.
894///
Chris Lattner850eabd2009-04-10 18:08:30 +0000895void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000896 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000897
Chris Lattner4b21c202009-04-13 01:29:17 +0000898 // If the preprocessor __COUNTER__ value has been bumped, remember it.
899 if (PP.getCounterValue() != 0) {
900 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000901 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000902 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000903 }
904
905 // Enter the preprocessor block.
906 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000907
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000908 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
909 // FIXME: use diagnostics subsystem for localization etc.
910 if (PP.SawDateOrTime())
911 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
912
Chris Lattner1b094952009-04-10 18:00:12 +0000913 // Loop over all the macro definitions that are live at the end of the file,
914 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000915 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
916 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000917 // FIXME: This emits macros in hash table order, we should do it in a stable
918 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000919 MacroInfo *MI = I->second;
920
921 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
922 // been redefined by the header (in which case they are not isBuiltinMacro).
923 if (MI->isBuiltinMacro())
924 continue;
925
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000926 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000927 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000928 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000929 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
930 Record.push_back(MI->isUsed());
931
932 unsigned Code;
933 if (MI->isObjectLike()) {
934 Code = pch::PP_MACRO_OBJECT_LIKE;
935 } else {
936 Code = pch::PP_MACRO_FUNCTION_LIKE;
937
938 Record.push_back(MI->isC99Varargs());
939 Record.push_back(MI->isGNUVarargs());
940 Record.push_back(MI->getNumArgs());
941 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
942 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000943 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000944 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000945 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000946 Record.clear();
947
Chris Lattner850eabd2009-04-10 18:08:30 +0000948 // Emit the tokens array.
949 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
950 // Note that we know that the preprocessor does not have any annotation
951 // tokens in it because they are created by the parser, and thus can't be
952 // in a macro definition.
953 const Token &Tok = MI->getReplacementToken(TokNo);
954
955 Record.push_back(Tok.getLocation().getRawEncoding());
956 Record.push_back(Tok.getLength());
957
Chris Lattner850eabd2009-04-10 18:08:30 +0000958 // FIXME: When reading literal tokens, reconstruct the literal pointer if
959 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000960 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000961
962 // FIXME: Should translate token kind to a stable encoding.
963 Record.push_back(Tok.getKind());
964 // FIXME: Should translate token flags to a stable encoding.
965 Record.push_back(Tok.getFlags());
966
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000967 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000968 Record.clear();
969 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000970 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000971 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000972 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000973}
974
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000975//===----------------------------------------------------------------------===//
976// Type Serialization
977//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000978
Douglas Gregorc34897d2009-04-09 22:27:44 +0000979/// \brief Write the representation of a type to the PCH stream.
980void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000981 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000982 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000983 ID = NextTypeID++;
984
985 // Record the offset for this type.
986 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000987 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000988 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
989 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000990 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000991 }
992
993 RecordData Record;
994
995 // Emit the type's representation.
996 PCHTypeWriter W(*this, Record);
997 switch (T->getTypeClass()) {
998 // For all of the concrete, non-dependent types, call the
999 // appropriate visitor function.
1000#define TYPE(Class, Base) \
1001 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1002#define ABSTRACT_TYPE(Class, Base)
1003#define DEPENDENT_TYPE(Class, Base)
1004#include "clang/AST/TypeNodes.def"
1005
1006 // For all of the dependent type nodes (which only occur in C++
1007 // templates), produce an error.
1008#define TYPE(Class, Base)
1009#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1010#include "clang/AST/TypeNodes.def"
1011 assert(false && "Cannot serialize dependent type nodes");
1012 break;
1013 }
1014
1015 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001016 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001017
1018 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001019 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001020}
1021
1022/// \brief Write a block containing all of the types.
1023void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001024 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001025 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001026
Douglas Gregore43f0972009-04-26 03:49:13 +00001027 // Emit all of the types that need to be emitted (so far).
1028 while (!TypesToEmit.empty()) {
1029 const Type *T = TypesToEmit.front();
1030 TypesToEmit.pop();
1031 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1032 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001033 }
1034
1035 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001036 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001037}
1038
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001039//===----------------------------------------------------------------------===//
1040// Declaration Serialization
1041//===----------------------------------------------------------------------===//
1042
Douglas Gregorc34897d2009-04-09 22:27:44 +00001043/// \brief Write the block containing all of the declaration IDs
1044/// lexically declared within the given DeclContext.
1045///
1046/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1047/// bistream, or 0 if no block was written.
1048uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1049 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001050 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001051 return 0;
1052
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001053 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001054 RecordData Record;
1055 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1056 DEnd = DC->decls_end(Context);
1057 D != DEnd; ++D)
1058 AddDeclRef(*D, Record);
1059
Douglas Gregoraf136d92009-04-22 22:34:57 +00001060 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001061 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001062 return Offset;
1063}
1064
1065/// \brief Write the block containing all of the declaration IDs
1066/// visible from the given DeclContext.
1067///
1068/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1069/// bistream, or 0 if no block was written.
1070uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1071 DeclContext *DC) {
1072 if (DC->getPrimaryContext() != DC)
1073 return 0;
1074
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001075 // Since there is no name lookup into functions or methods, and we
1076 // perform name lookup for the translation unit via the
1077 // IdentifierInfo chains, don't bother to build a
1078 // visible-declarations table for these entities.
1079 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001080 return 0;
1081
Douglas Gregorc34897d2009-04-09 22:27:44 +00001082 // Force the DeclContext to build a its name-lookup table.
1083 DC->lookup(Context, DeclarationName());
1084
1085 // Serialize the contents of the mapping used for lookup. Note that,
1086 // although we have two very different code paths, the serialized
1087 // representation is the same for both cases: a declaration name,
1088 // followed by a size, followed by references to the visible
1089 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001090 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001091 RecordData Record;
1092 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001093 if (!Map)
1094 return 0;
1095
Douglas Gregorc34897d2009-04-09 22:27:44 +00001096 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1097 D != DEnd; ++D) {
1098 AddDeclarationName(D->first, Record);
1099 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1100 Record.push_back(Result.second - Result.first);
1101 for(; Result.first != Result.second; ++Result.first)
1102 AddDeclRef(*Result.first, Record);
1103 }
1104
1105 if (Record.size() == 0)
1106 return 0;
1107
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001108 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001109 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001110 return Offset;
1111}
1112
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001113//===----------------------------------------------------------------------===//
1114// Global Method Pool and Selector Serialization
1115//===----------------------------------------------------------------------===//
1116
Douglas Gregorff9a6092009-04-20 20:36:09 +00001117namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001118// Trait used for the on-disk hash table used in the method pool.
1119class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1120 PCHWriter &Writer;
1121
1122public:
1123 typedef Selector key_type;
1124 typedef key_type key_type_ref;
1125
1126 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1127 typedef const data_type& data_type_ref;
1128
1129 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1130
1131 static unsigned ComputeHash(Selector Sel) {
1132 unsigned N = Sel.getNumArgs();
1133 if (N == 0)
1134 ++N;
1135 unsigned R = 5381;
1136 for (unsigned I = 0; I != N; ++I)
1137 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1138 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1139 return R;
1140 }
1141
1142 std::pair<unsigned,unsigned>
1143 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1144 data_type_ref Methods) {
1145 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1146 clang::io::Emit16(Out, KeyLen);
1147 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1148 for (const ObjCMethodList *Method = &Methods.first; Method;
1149 Method = Method->Next)
1150 if (Method->Method)
1151 DataLen += 4;
1152 for (const ObjCMethodList *Method = &Methods.second; Method;
1153 Method = Method->Next)
1154 if (Method->Method)
1155 DataLen += 4;
1156 clang::io::Emit16(Out, DataLen);
1157 return std::make_pair(KeyLen, DataLen);
1158 }
1159
Douglas Gregor2d711832009-04-25 17:48:32 +00001160 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1161 uint64_t Start = Out.tell();
1162 assert((Start >> 32) == 0 && "Selector key offset too large");
1163 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001164 unsigned N = Sel.getNumArgs();
1165 clang::io::Emit16(Out, N);
1166 if (N == 0)
1167 N = 1;
1168 for (unsigned I = 0; I != N; ++I)
1169 clang::io::Emit32(Out,
1170 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1171 }
1172
1173 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001174 data_type_ref Methods, unsigned DataLen) {
1175 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001176 unsigned NumInstanceMethods = 0;
1177 for (const ObjCMethodList *Method = &Methods.first; Method;
1178 Method = Method->Next)
1179 if (Method->Method)
1180 ++NumInstanceMethods;
1181
1182 unsigned NumFactoryMethods = 0;
1183 for (const ObjCMethodList *Method = &Methods.second; Method;
1184 Method = Method->Next)
1185 if (Method->Method)
1186 ++NumFactoryMethods;
1187
1188 clang::io::Emit16(Out, NumInstanceMethods);
1189 clang::io::Emit16(Out, NumFactoryMethods);
1190 for (const ObjCMethodList *Method = &Methods.first; Method;
1191 Method = Method->Next)
1192 if (Method->Method)
1193 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001194 for (const ObjCMethodList *Method = &Methods.second; Method;
1195 Method = Method->Next)
1196 if (Method->Method)
1197 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001198
1199 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001200 }
1201};
1202} // end anonymous namespace
1203
1204/// \brief Write the method pool into the PCH file.
1205///
1206/// The method pool contains both instance and factory methods, stored
1207/// in an on-disk hash table indexed by the selector.
1208void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1209 using namespace llvm;
1210
1211 // Create and write out the blob that contains the instance and
1212 // factor method pools.
1213 bool Empty = true;
1214 {
1215 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1216
1217 // Create the on-disk hash table representation. Start by
1218 // iterating through the instance method pool.
1219 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001220 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001221 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1222 Instance = SemaRef.InstanceMethodPool.begin(),
1223 InstanceEnd = SemaRef.InstanceMethodPool.end();
1224 Instance != InstanceEnd; ++Instance) {
1225 // Check whether there is a factory method with the same
1226 // selector.
1227 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1228 = SemaRef.FactoryMethodPool.find(Instance->first);
1229
1230 if (Factory == SemaRef.FactoryMethodPool.end())
1231 Generator.insert(Instance->first,
1232 std::make_pair(Instance->second,
1233 ObjCMethodList()));
1234 else
1235 Generator.insert(Instance->first,
1236 std::make_pair(Instance->second, Factory->second));
1237
Douglas Gregor2d711832009-04-25 17:48:32 +00001238 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001239 Empty = false;
1240 }
1241
1242 // Now iterate through the factory method pool, to pick up any
1243 // selectors that weren't already in the instance method pool.
1244 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1245 Factory = SemaRef.FactoryMethodPool.begin(),
1246 FactoryEnd = SemaRef.FactoryMethodPool.end();
1247 Factory != FactoryEnd; ++Factory) {
1248 // Check whether there is an instance method with the same
1249 // selector. If so, there is no work to do here.
1250 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1251 = SemaRef.InstanceMethodPool.find(Factory->first);
1252
Douglas Gregor2d711832009-04-25 17:48:32 +00001253 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001254 Generator.insert(Factory->first,
1255 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001256 ++NumSelectorsInMethodPool;
1257 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001258
1259 Empty = false;
1260 }
1261
Douglas Gregor2d711832009-04-25 17:48:32 +00001262 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001263 return;
1264
1265 // Create the on-disk hash table in a buffer.
1266 llvm::SmallVector<char, 4096> MethodPool;
1267 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001268 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001269 {
1270 PCHMethodPoolTrait Trait(*this);
1271 llvm::raw_svector_ostream Out(MethodPool);
1272 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001273 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001274 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001275
1276 // For every selector that we have seen but which was not
1277 // written into the hash table, write the selector itself and
1278 // record it's offset.
1279 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1280 if (SelectorOffsets[I] == 0)
1281 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001282 }
1283
1284 // Create a blob abbreviation
1285 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1286 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001288 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001289 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1290 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1291
Douglas Gregor2d711832009-04-25 17:48:32 +00001292 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001293 RecordData Record;
1294 Record.push_back(pch::METHOD_POOL);
1295 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001296 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001297 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1298 &MethodPool.front(),
1299 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001300
1301 // Create a blob abbreviation for the selector table offsets.
1302 Abbrev = new BitCodeAbbrev();
1303 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1306 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1307
1308 // Write the selector offsets table.
1309 Record.clear();
1310 Record.push_back(pch::SELECTOR_OFFSETS);
1311 Record.push_back(SelectorOffsets.size());
1312 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1313 (const char *)&SelectorOffsets.front(),
1314 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001315 }
1316}
1317
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001318//===----------------------------------------------------------------------===//
1319// Identifier Table Serialization
1320//===----------------------------------------------------------------------===//
1321
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001322namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001323class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1324 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001325 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001326
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001327 /// \brief Determines whether this is an "interesting" identifier
1328 /// that needs a full IdentifierInfo structure written into the hash
1329 /// table.
1330 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1331 return II->isPoisoned() ||
1332 II->isExtensionToken() ||
1333 II->hasMacroDefinition() ||
1334 II->getObjCOrBuiltinID() ||
1335 II->getFETokenInfo<void>();
1336 }
1337
Douglas Gregorff9a6092009-04-20 20:36:09 +00001338public:
1339 typedef const IdentifierInfo* key_type;
1340 typedef key_type key_type_ref;
1341
1342 typedef pch::IdentID data_type;
1343 typedef data_type data_type_ref;
1344
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001345 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1346 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001347
1348 static unsigned ComputeHash(const IdentifierInfo* II) {
1349 return clang::BernsteinHash(II->getName());
1350 }
1351
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001352 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001353 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1354 pch::IdentID ID) {
1355 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001356 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1357 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001358 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001359 if (II->hasMacroDefinition() &&
1360 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001361 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001362 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1363 DEnd = IdentifierResolver::end();
1364 D != DEnd; ++D)
1365 DataLen += sizeof(pch::DeclID);
1366 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001367 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001368 // We emit the key length after the data length so that every
1369 // string is preceded by a 16-bit length. This matches the PTH
1370 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001371 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001372 return std::make_pair(KeyLen, DataLen);
1373 }
1374
1375 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1376 unsigned KeyLen) {
1377 // Record the location of the key data. This is used when generating
1378 // the mapping from persistent IDs to strings.
1379 Writer.SetIdentifierOffset(II, Out.tell());
1380 Out.write(II->getName(), KeyLen);
1381 }
1382
1383 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1384 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001385 if (!isInterestingIdentifier(II)) {
1386 clang::io::Emit32(Out, ID << 1);
1387 return;
1388 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001389
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001390 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001391 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001392 bool hasMacroDefinition =
1393 II->hasMacroDefinition() &&
1394 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001395 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001396 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001397 Bits = (Bits << 1) | II->isExtensionToken();
1398 Bits = (Bits << 1) | II->isPoisoned();
1399 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001400 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001401
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001402 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001403 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001404
Douglas Gregorc713da92009-04-21 22:25:48 +00001405 // Emit the declaration IDs in reverse order, because the
1406 // IdentifierResolver provides the declarations as they would be
1407 // visible (e.g., the function "stat" would come before the struct
1408 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1409 // adds declarations to the end of the list (so we need to see the
1410 // struct "status" before the function "status").
1411 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1412 IdentifierResolver::end());
1413 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1414 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001415 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001416 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001417 }
1418};
1419} // end anonymous namespace
1420
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001421/// \brief Write the identifier table into the PCH file.
1422///
1423/// The identifier table consists of a blob containing string data
1424/// (the actual identifiers themselves) and a separate "offsets" index
1425/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001426void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001427 using namespace llvm;
1428
1429 // Create and write out the blob that contains the identifier
1430 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001431 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001432 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1433
Douglas Gregor91137812009-04-28 20:33:11 +00001434 // Look for any identifiers that were named while processing the
1435 // headers, but are otherwise not needed. We add these to the hash
1436 // table to enable checking of the predefines buffer in the case
1437 // where the user adds new macro definitions when building the PCH
1438 // file.
1439 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1440 IDEnd = PP.getIdentifierTable().end();
1441 ID != IDEnd; ++ID)
1442 getIdentifierRef(ID->second);
1443
Douglas Gregorff9a6092009-04-20 20:36:09 +00001444 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001445 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001446 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1447 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1448 ID != IDEnd; ++ID) {
1449 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001450 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001451 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001452
Douglas Gregorff9a6092009-04-20 20:36:09 +00001453 // Create the on-disk hash table in a buffer.
1454 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001455 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001456 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001457 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001458 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001459 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001460 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001461 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001462 }
1463
1464 // Create a blob abbreviation
1465 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1466 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001467 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001469 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001470
1471 // Write the identifier table
1472 RecordData Record;
1473 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001474 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001475 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1476 &IdentifierTable.front(),
1477 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001478 }
1479
1480 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001481 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1482 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1485 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1486
1487 RecordData Record;
1488 Record.push_back(pch::IDENTIFIER_OFFSET);
1489 Record.push_back(IdentifierOffsets.size());
1490 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1491 (const char *)&IdentifierOffsets.front(),
1492 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001493}
1494
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001495//===----------------------------------------------------------------------===//
1496// General Serialization Routines
1497//===----------------------------------------------------------------------===//
1498
Douglas Gregor1c507882009-04-15 21:30:51 +00001499/// \brief Write a record containing the given attributes.
1500void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1501 RecordData Record;
1502 for (; Attr; Attr = Attr->getNext()) {
1503 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1504 Record.push_back(Attr->isInherited());
1505 switch (Attr->getKind()) {
1506 case Attr::Alias:
1507 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1508 break;
1509
1510 case Attr::Aligned:
1511 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1512 break;
1513
1514 case Attr::AlwaysInline:
1515 break;
1516
1517 case Attr::AnalyzerNoReturn:
1518 break;
1519
1520 case Attr::Annotate:
1521 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1522 break;
1523
1524 case Attr::AsmLabel:
1525 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1526 break;
1527
1528 case Attr::Blocks:
1529 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1530 break;
1531
1532 case Attr::Cleanup:
1533 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1534 break;
1535
1536 case Attr::Const:
1537 break;
1538
1539 case Attr::Constructor:
1540 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1541 break;
1542
1543 case Attr::DLLExport:
1544 case Attr::DLLImport:
1545 case Attr::Deprecated:
1546 break;
1547
1548 case Attr::Destructor:
1549 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1550 break;
1551
1552 case Attr::FastCall:
1553 break;
1554
1555 case Attr::Format: {
1556 const FormatAttr *Format = cast<FormatAttr>(Attr);
1557 AddString(Format->getType(), Record);
1558 Record.push_back(Format->getFormatIdx());
1559 Record.push_back(Format->getFirstArg());
1560 break;
1561 }
1562
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001563 case Attr::FormatArg: {
1564 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1565 Record.push_back(Format->getFormatIdx());
1566 break;
1567 }
1568
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001569 case Attr::Sentinel : {
1570 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1571 Record.push_back(Sentinel->getSentinel());
1572 Record.push_back(Sentinel->getNullPos());
1573 break;
1574 }
1575
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001576 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001577 case Attr::IBOutletKind:
1578 case Attr::NoReturn:
1579 case Attr::NoThrow:
1580 case Attr::Nodebug:
1581 case Attr::Noinline:
1582 break;
1583
1584 case Attr::NonNull: {
1585 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1586 Record.push_back(NonNull->size());
1587 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1588 break;
1589 }
1590
1591 case Attr::ObjCException:
1592 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001593 case Attr::CFReturnsRetained:
1594 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001595 case Attr::Overloadable:
1596 break;
1597
1598 case Attr::Packed:
1599 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1600 break;
1601
1602 case Attr::Pure:
1603 break;
1604
1605 case Attr::Regparm:
1606 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1607 break;
1608
1609 case Attr::Section:
1610 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1611 break;
1612
1613 case Attr::StdCall:
1614 case Attr::TransparentUnion:
1615 case Attr::Unavailable:
1616 case Attr::Unused:
1617 case Attr::Used:
1618 break;
1619
1620 case Attr::Visibility:
1621 // FIXME: stable encoding
1622 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1623 break;
1624
1625 case Attr::WarnUnusedResult:
1626 case Attr::Weak:
1627 case Attr::WeakImport:
1628 break;
1629 }
1630 }
1631
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001632 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001633}
1634
1635void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1636 Record.push_back(Str.size());
1637 Record.insert(Record.end(), Str.begin(), Str.end());
1638}
1639
Douglas Gregorff9a6092009-04-20 20:36:09 +00001640/// \brief Note that the identifier II occurs at the given offset
1641/// within the identifier table.
1642void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001643 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001644}
1645
Douglas Gregor2d711832009-04-25 17:48:32 +00001646/// \brief Note that the selector Sel occurs at the given offset
1647/// within the method pool/selector table.
1648void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1649 unsigned ID = SelectorIDs[Sel];
1650 assert(ID && "Unknown selector");
1651 SelectorOffsets[ID - 1] = Offset;
1652}
1653
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001654PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001655 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001656 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1657 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001658
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001659void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001660 using namespace llvm;
1661
Douglas Gregor87887da2009-04-20 15:53:59 +00001662 ASTContext &Context = SemaRef.Context;
1663 Preprocessor &PP = SemaRef.PP;
1664
Douglas Gregorc34897d2009-04-09 22:27:44 +00001665 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001666 Stream.Emit((unsigned)'C', 8);
1667 Stream.Emit((unsigned)'P', 8);
1668 Stream.Emit((unsigned)'C', 8);
1669 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001670
1671 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001672
1673 // The translation unit is the first declaration we'll emit.
1674 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1675 DeclsToEmit.push(Context.getTranslationUnitDecl());
1676
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001677 // Make sure that we emit IdentifierInfos (and any attached
1678 // declarations) for builtins.
1679 {
1680 IdentifierTable &Table = PP.getIdentifierTable();
1681 llvm::SmallVector<const char *, 32> BuiltinNames;
1682 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1683 Context.getLangOptions().NoBuiltin);
1684 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1685 getIdentifierRef(&Table.get(BuiltinNames[I]));
1686 }
1687
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001688 // Build a record containing all of the tentative definitions in
1689 // this header file. Generally, this record will be empty.
1690 RecordData TentativeDefinitions;
1691 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1692 TD = SemaRef.TentativeDefinitions.begin(),
1693 TDEnd = SemaRef.TentativeDefinitions.end();
1694 TD != TDEnd; ++TD)
1695 AddDeclRef(TD->second, TentativeDefinitions);
1696
Douglas Gregor062d9482009-04-22 22:18:58 +00001697 // Build a record containing all of the locally-scoped external
1698 // declarations in this header file. Generally, this record will be
1699 // empty.
1700 RecordData LocallyScopedExternalDecls;
1701 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1702 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1703 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1704 TD != TDEnd; ++TD)
1705 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1706
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001707 // Build a record containing all of the ext_vector declarations.
1708 RecordData ExtVectorDecls;
1709 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1710 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1711
1712 // Build a record containing all of the Objective-C category
1713 // implementations.
1714 RecordData ObjCCategoryImpls;
1715 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1716 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1717
Douglas Gregorc34897d2009-04-09 22:27:44 +00001718 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001719 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001720 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001721 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001722 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001723 if (StatCalls)
1724 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001725 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001726 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001727
1728 // Keep writing types and declarations until all types and
1729 // declarations have been written.
1730 do {
1731 if (!DeclsToEmit.empty())
1732 WriteDeclsBlock(Context);
1733 if (!TypesToEmit.empty())
1734 WriteTypesBlock(Context);
1735 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1736
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001737 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001738 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001739
1740 // Write the type offsets array
1741 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1742 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1744 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1745 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1746 Record.clear();
1747 Record.push_back(pch::TYPE_OFFSET);
1748 Record.push_back(TypeOffsets.size());
1749 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1750 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001751 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001752
1753 // Write the declaration offsets array
1754 Abbrev = new BitCodeAbbrev();
1755 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1756 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1758 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1759 Record.clear();
1760 Record.push_back(pch::DECL_OFFSET);
1761 Record.push_back(DeclOffsets.size());
1762 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1763 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001764 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001765
1766 // Write the record of special types.
1767 Record.clear();
1768 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001769 AddTypeRef(Context.getObjCIdType(), Record);
1770 AddTypeRef(Context.getObjCSelType(), Record);
1771 AddTypeRef(Context.getObjCProtoType(), Record);
1772 AddTypeRef(Context.getObjCClassType(), Record);
1773 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1774 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001775 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1776
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001777 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001778 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001779 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001780
1781 // Write the record containing tentative definitions.
1782 if (!TentativeDefinitions.empty())
1783 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001784
1785 // Write the record containing locally-scoped external definitions.
1786 if (!LocallyScopedExternalDecls.empty())
1787 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1788 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001789
1790 // Write the record containing ext_vector type names.
1791 if (!ExtVectorDecls.empty())
1792 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1793
1794 // Write the record containing Objective-C category implementations.
1795 if (!ObjCCategoryImpls.empty())
1796 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001797
1798 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001799 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001800 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001801 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001802 Record.push_back(NumLexicalDeclContexts);
1803 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001804 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001805 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001806}
1807
1808void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1809 Record.push_back(Loc.getRawEncoding());
1810}
1811
1812void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1813 Record.push_back(Value.getBitWidth());
1814 unsigned N = Value.getNumWords();
1815 const uint64_t* Words = Value.getRawData();
1816 for (unsigned I = 0; I != N; ++I)
1817 Record.push_back(Words[I]);
1818}
1819
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001820void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1821 Record.push_back(Value.isUnsigned());
1822 AddAPInt(Value, Record);
1823}
1824
Douglas Gregore2f37202009-04-14 21:55:33 +00001825void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1826 AddAPInt(Value.bitcastToAPInt(), Record);
1827}
1828
Douglas Gregorc34897d2009-04-09 22:27:44 +00001829void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001830 Record.push_back(getIdentifierRef(II));
1831}
1832
1833pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1834 if (II == 0)
1835 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001836
1837 pch::IdentID &ID = IdentifierIDs[II];
1838 if (ID == 0)
1839 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001840 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001841}
1842
Steve Naroff9e84d782009-04-23 10:39:46 +00001843void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1844 if (SelRef.getAsOpaquePtr() == 0) {
1845 Record.push_back(0);
1846 return;
1847 }
1848
1849 pch::SelectorID &SID = SelectorIDs[SelRef];
1850 if (SID == 0) {
1851 SID = SelectorIDs.size();
1852 SelVector.push_back(SelRef);
1853 }
1854 Record.push_back(SID);
1855}
1856
Douglas Gregorc34897d2009-04-09 22:27:44 +00001857void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1858 if (T.isNull()) {
1859 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1860 return;
1861 }
1862
1863 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001864 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001865 switch (BT->getKind()) {
1866 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1867 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1868 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1869 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1870 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1871 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1872 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1873 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001874 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001875 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1876 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1877 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1878 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1879 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1880 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1881 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001882 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001883 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1884 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1885 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001886 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001887 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1888 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1889 }
1890
1891 Record.push_back((ID << 3) | T.getCVRQualifiers());
1892 return;
1893 }
1894
Douglas Gregorac8f2802009-04-10 17:25:41 +00001895 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001896 if (ID == 0) {
1897 // We haven't seen this type before. Assign it a new ID and put it
1898 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001899 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001900 TypesToEmit.push(T.getTypePtr());
1901 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001902
1903 // Encode the type qualifiers in the type reference.
1904 Record.push_back((ID << 3) | T.getCVRQualifiers());
1905}
1906
1907void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1908 if (D == 0) {
1909 Record.push_back(0);
1910 return;
1911 }
1912
Douglas Gregorac8f2802009-04-10 17:25:41 +00001913 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001914 if (ID == 0) {
1915 // We haven't seen this declaration before. Give it a new ID and
1916 // enqueue it in the list of declarations to emit.
1917 ID = DeclIDs.size();
1918 DeclsToEmit.push(const_cast<Decl *>(D));
1919 }
1920
1921 Record.push_back(ID);
1922}
1923
Douglas Gregorff9a6092009-04-20 20:36:09 +00001924pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1925 if (D == 0)
1926 return 0;
1927
1928 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1929 return DeclIDs[D];
1930}
1931
Douglas Gregorc34897d2009-04-09 22:27:44 +00001932void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001933 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001934 Record.push_back(Name.getNameKind());
1935 switch (Name.getNameKind()) {
1936 case DeclarationName::Identifier:
1937 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1938 break;
1939
1940 case DeclarationName::ObjCZeroArgSelector:
1941 case DeclarationName::ObjCOneArgSelector:
1942 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001943 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001944 break;
1945
1946 case DeclarationName::CXXConstructorName:
1947 case DeclarationName::CXXDestructorName:
1948 case DeclarationName::CXXConversionFunctionName:
1949 AddTypeRef(Name.getCXXNameType(), Record);
1950 break;
1951
1952 case DeclarationName::CXXOperatorName:
1953 Record.push_back(Name.getCXXOverloadedOperator());
1954 break;
1955
1956 case DeclarationName::CXXUsingDirective:
1957 // No extra data to emit
1958 break;
1959 }
1960}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001961