blob: 41a50254558899873f171e7e9b7c3f8d6a8efa1f [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"
Douglas Gregorb64c1932009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000043
Douglas Gregor2cf26342009-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 Gregor4fed3f42009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-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 Gregorc9490c02009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
Sebastian Redl465226e2009-05-27 22:11:52 +0000165 Record.push_back(T->hasExceptionSpec());
166 Record.push_back(T->hasAnyExceptionSpec());
167 Record.push_back(T->getNumExceptions());
168 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
169 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000170 Code = pch::TYPE_FUNCTION_PROTO;
171}
172
173void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
174 Writer.AddDeclRef(T->getDecl(), Record);
175 Code = pch::TYPE_TYPEDEF;
176}
177
178void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000180 Code = pch::TYPE_TYPEOF_EXPR;
181}
182
183void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
184 Writer.AddTypeRef(T->getUnderlyingType(), Record);
185 Code = pch::TYPE_TYPEOF;
186}
187
Anders Carlsson395b4752009-06-24 19:06:50 +0000188void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
189 Writer.AddStmt(T->getUnderlyingExpr());
190 Code = pch::TYPE_DECLTYPE;
191}
192
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193void PCHTypeWriter::VisitTagType(const TagType *T) {
194 Writer.AddDeclRef(T->getDecl(), Record);
195 assert(!T->isBeingDefined() &&
196 "Cannot serialize in the middle of a type definition");
197}
198
199void PCHTypeWriter::VisitRecordType(const RecordType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_RECORD;
202}
203
204void PCHTypeWriter::VisitEnumType(const EnumType *T) {
205 VisitTagType(T);
206 Code = pch::TYPE_ENUM;
207}
208
209void
210PCHTypeWriter::VisitTemplateSpecializationType(
211 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize template specialization types");
214}
215
216void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000217 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000218 assert(false && "Cannot serialize qualified name types");
219}
220
221void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
222 Writer.AddDeclRef(T->getDecl(), Record);
223 Code = pch::TYPE_OBJC_INTERFACE;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedInterfaceType(
228 const ObjCQualifiedInterfaceType *T) {
229 VisitObjCInterfaceType(T);
230 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000231 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
232 E = T->qual_end(); I != E; ++I)
233 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000234 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
235}
236
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000237void
238PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
239 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000240 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000241 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000242 E = T->qual_end(); I != E; ++I)
243 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000244 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000245}
246
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000247//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000248// PCHWriter Implementation
249//===----------------------------------------------------------------------===//
250
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000251static void EmitBlockID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
257
258 // Emit the block name if present.
259 if (Name == 0 || Name[0] == 0) return;
260 Record.clear();
261 while (*Name)
262 Record.push_back(*Name++);
263 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
264}
265
266static void EmitRecordID(unsigned ID, const char *Name,
267 llvm::BitstreamWriter &Stream,
268 PCHWriter::RecordData &Record) {
269 Record.clear();
270 Record.push_back(ID);
271 while (*Name)
272 Record.push_back(*Name++);
273 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000274}
275
276static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
277 PCHWriter::RecordData &Record) {
278#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
279 RECORD(STMT_STOP);
280 RECORD(STMT_NULL_PTR);
281 RECORD(STMT_NULL);
282 RECORD(STMT_COMPOUND);
283 RECORD(STMT_CASE);
284 RECORD(STMT_DEFAULT);
285 RECORD(STMT_LABEL);
286 RECORD(STMT_IF);
287 RECORD(STMT_SWITCH);
288 RECORD(STMT_WHILE);
289 RECORD(STMT_DO);
290 RECORD(STMT_FOR);
291 RECORD(STMT_GOTO);
292 RECORD(STMT_INDIRECT_GOTO);
293 RECORD(STMT_CONTINUE);
294 RECORD(STMT_BREAK);
295 RECORD(STMT_RETURN);
296 RECORD(STMT_DECL);
297 RECORD(STMT_ASM);
298 RECORD(EXPR_PREDEFINED);
299 RECORD(EXPR_DECL_REF);
300 RECORD(EXPR_INTEGER_LITERAL);
301 RECORD(EXPR_FLOATING_LITERAL);
302 RECORD(EXPR_IMAGINARY_LITERAL);
303 RECORD(EXPR_STRING_LITERAL);
304 RECORD(EXPR_CHARACTER_LITERAL);
305 RECORD(EXPR_PAREN);
306 RECORD(EXPR_UNARY_OPERATOR);
307 RECORD(EXPR_SIZEOF_ALIGN_OF);
308 RECORD(EXPR_ARRAY_SUBSCRIPT);
309 RECORD(EXPR_CALL);
310 RECORD(EXPR_MEMBER);
311 RECORD(EXPR_BINARY_OPERATOR);
312 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
313 RECORD(EXPR_CONDITIONAL_OPERATOR);
314 RECORD(EXPR_IMPLICIT_CAST);
315 RECORD(EXPR_CSTYLE_CAST);
316 RECORD(EXPR_COMPOUND_LITERAL);
317 RECORD(EXPR_EXT_VECTOR_ELEMENT);
318 RECORD(EXPR_INIT_LIST);
319 RECORD(EXPR_DESIGNATED_INIT);
320 RECORD(EXPR_IMPLICIT_VALUE_INIT);
321 RECORD(EXPR_VA_ARG);
322 RECORD(EXPR_ADDR_LABEL);
323 RECORD(EXPR_STMT);
324 RECORD(EXPR_TYPES_COMPATIBLE);
325 RECORD(EXPR_CHOOSE);
326 RECORD(EXPR_GNU_NULL);
327 RECORD(EXPR_SHUFFLE_VECTOR);
328 RECORD(EXPR_BLOCK);
329 RECORD(EXPR_BLOCK_DECL_REF);
330 RECORD(EXPR_OBJC_STRING_LITERAL);
331 RECORD(EXPR_OBJC_ENCODE);
332 RECORD(EXPR_OBJC_SELECTOR_EXPR);
333 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
334 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
335 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
336 RECORD(EXPR_OBJC_KVC_REF_EXPR);
337 RECORD(EXPR_OBJC_MESSAGE_EXPR);
338 RECORD(EXPR_OBJC_SUPER_EXPR);
339 RECORD(STMT_OBJC_FOR_COLLECTION);
340 RECORD(STMT_OBJC_CATCH);
341 RECORD(STMT_OBJC_FINALLY);
342 RECORD(STMT_OBJC_AT_TRY);
343 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
344 RECORD(STMT_OBJC_AT_THROW);
345#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000346}
347
348void PCHWriter::WriteBlockInfoBlock() {
349 RecordData Record;
350 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
351
Chris Lattner2f4efd12009-04-27 00:40:25 +0000352#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000353#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
354
355 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000356 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000357 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000358 RECORD(TYPE_OFFSET);
359 RECORD(DECL_OFFSET);
360 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000361 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000362 RECORD(IDENTIFIER_OFFSET);
363 RECORD(IDENTIFIER_TABLE);
364 RECORD(EXTERNAL_DEFINITIONS);
365 RECORD(SPECIAL_TYPES);
366 RECORD(STATISTICS);
367 RECORD(TENTATIVE_DEFINITIONS);
368 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
369 RECORD(SELECTOR_OFFSETS);
370 RECORD(METHOD_POOL);
371 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000372 RECORD(SOURCE_LOCATION_OFFSETS);
373 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000374 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000375 RECORD(EXT_VECTOR_DECLS);
376 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000377
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000378 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000379 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000380 RECORD(SM_SLOC_FILE_ENTRY);
381 RECORD(SM_SLOC_BUFFER_ENTRY);
382 RECORD(SM_SLOC_BUFFER_BLOB);
383 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
384 RECORD(SM_LINE_TABLE);
385 RECORD(SM_HEADER_FILE_INFO);
386
387 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000388 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000389 RECORD(PP_MACRO_OBJECT_LIKE);
390 RECORD(PP_MACRO_FUNCTION_LIKE);
391 RECORD(PP_TOKEN);
392
393 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000394 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000395 RECORD(TYPE_EXT_QUAL);
396 RECORD(TYPE_FIXED_WIDTH_INT);
397 RECORD(TYPE_COMPLEX);
398 RECORD(TYPE_POINTER);
399 RECORD(TYPE_BLOCK_POINTER);
400 RECORD(TYPE_LVALUE_REFERENCE);
401 RECORD(TYPE_RVALUE_REFERENCE);
402 RECORD(TYPE_MEMBER_POINTER);
403 RECORD(TYPE_CONSTANT_ARRAY);
404 RECORD(TYPE_INCOMPLETE_ARRAY);
405 RECORD(TYPE_VARIABLE_ARRAY);
406 RECORD(TYPE_VECTOR);
407 RECORD(TYPE_EXT_VECTOR);
408 RECORD(TYPE_FUNCTION_PROTO);
409 RECORD(TYPE_FUNCTION_NO_PROTO);
410 RECORD(TYPE_TYPEDEF);
411 RECORD(TYPE_TYPEOF_EXPR);
412 RECORD(TYPE_TYPEOF);
413 RECORD(TYPE_RECORD);
414 RECORD(TYPE_ENUM);
415 RECORD(TYPE_OBJC_INTERFACE);
416 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000417 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000418 // Statements and Exprs can occur in the Types block.
419 AddStmtsExprs(Stream, Record);
420
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000421 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000422 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000423 RECORD(DECL_ATTR);
424 RECORD(DECL_TRANSLATION_UNIT);
425 RECORD(DECL_TYPEDEF);
426 RECORD(DECL_ENUM);
427 RECORD(DECL_RECORD);
428 RECORD(DECL_ENUM_CONSTANT);
429 RECORD(DECL_FUNCTION);
430 RECORD(DECL_OBJC_METHOD);
431 RECORD(DECL_OBJC_INTERFACE);
432 RECORD(DECL_OBJC_PROTOCOL);
433 RECORD(DECL_OBJC_IVAR);
434 RECORD(DECL_OBJC_AT_DEFS_FIELD);
435 RECORD(DECL_OBJC_CLASS);
436 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
437 RECORD(DECL_OBJC_CATEGORY);
438 RECORD(DECL_OBJC_CATEGORY_IMPL);
439 RECORD(DECL_OBJC_IMPLEMENTATION);
440 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
441 RECORD(DECL_OBJC_PROPERTY);
442 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000443 RECORD(DECL_FIELD);
444 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000445 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000446 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000447 RECORD(DECL_ORIGINAL_PARM_VAR);
448 RECORD(DECL_FILE_SCOPE_ASM);
449 RECORD(DECL_BLOCK);
450 RECORD(DECL_CONTEXT_LEXICAL);
451 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000452 // Statements and Exprs can occur in the Decls block.
453 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000454#undef RECORD
455#undef BLOCK
456 Stream.ExitBlock();
457}
458
459
Douglas Gregorab41e632009-04-27 22:23:34 +0000460/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregorb64c1932009-05-12 01:31:05 +0000461void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000462 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000463
464 // Original file name
465 SourceManager &SM = Context.getSourceManager();
466 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
467 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
468 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
469 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
470 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
471
472 llvm::sys::Path MainFilePath(MainFile->getName());
473 std::string MainFileName;
474
475 if (!MainFilePath.isAbsolute()) {
476 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
477 P.appendComponent(MainFilePath.toString());
478 MainFileName = P.toString();
479 } else {
480 MainFileName = MainFilePath.toString();
481 }
482
483 RecordData Record;
484 Record.push_back(pch::ORIGINAL_FILE_NAME);
485 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
486 MainFileName.size());
487 }
488
489 // Metadata
490 const TargetInfo &Target = Context.Target;
491 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
492 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
493 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
494 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
495 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
496 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
497 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
498 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000499
500 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000501 Record.push_back(pch::METADATA);
502 Record.push_back(pch::VERSION_MAJOR);
503 Record.push_back(pch::VERSION_MINOR);
504 Record.push_back(CLANG_VERSION_MAJOR);
505 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000506 const char *Triple = Target.getTargetTriple();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000507 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000508}
509
510/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000511void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
512 RecordData Record;
513 Record.push_back(LangOpts.Trigraphs);
514 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
515 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
516 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
517 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
518 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
519 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
520 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
521 Record.push_back(LangOpts.C99); // C99 Support
522 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
523 Record.push_back(LangOpts.CPlusPlus); // C++ Support
524 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000525 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
526
527 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
528 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
529 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
530
531 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000532 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
533 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000534 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000535 Record.push_back(LangOpts.Exceptions); // Support exception handling.
536
537 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
538 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
539 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
540
Chris Lattnerea5ce472009-04-27 07:35:58 +0000541 // Whether static initializers are protected by locks.
542 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000543 Record.push_back(LangOpts.Blocks); // block extension to C
544 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
545 // they are unused.
546 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
547 // (modulo the platform support).
548
549 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
550 // signed integer arithmetic overflows.
551
552 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
553 // may be ripped out at any time.
554
555 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
556 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
557 // defined.
558 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
559 // opposed to __DYNAMIC__).
560 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
561
562 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
563 // used (instead of C99 semantics).
564 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000565 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
566 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000567 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
568 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000569 Record.push_back(LangOpts.getGCMode());
570 Record.push_back(LangOpts.getVisibilityMode());
571 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000572 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000573 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000574}
575
Douglas Gregor14f79002009-04-10 03:52:48 +0000576//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000577// stat cache Serialization
578//===----------------------------------------------------------------------===//
579
580namespace {
581// Trait used for the on-disk hash table of stat cache results.
582class VISIBILITY_HIDDEN PCHStatCacheTrait {
583public:
584 typedef const char * key_type;
585 typedef key_type key_type_ref;
586
587 typedef std::pair<int, struct stat> data_type;
588 typedef const data_type& data_type_ref;
589
590 static unsigned ComputeHash(const char *path) {
591 return BernsteinHash(path);
592 }
593
594 std::pair<unsigned,unsigned>
595 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
596 data_type_ref Data) {
597 unsigned StrLen = strlen(path);
598 clang::io::Emit16(Out, StrLen);
599 unsigned DataLen = 1; // result value
600 if (Data.first == 0)
601 DataLen += 4 + 4 + 2 + 8 + 8;
602 clang::io::Emit8(Out, DataLen);
603 return std::make_pair(StrLen + 1, DataLen);
604 }
605
606 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
607 Out.write(path, KeyLen);
608 }
609
610 void EmitData(llvm::raw_ostream& Out, key_type_ref,
611 data_type_ref Data, unsigned DataLen) {
612 using namespace clang::io;
613 uint64_t Start = Out.tell(); (void)Start;
614
615 // Result of stat()
616 Emit8(Out, Data.first? 1 : 0);
617
618 if (Data.first == 0) {
619 Emit32(Out, (uint32_t) Data.second.st_ino);
620 Emit32(Out, (uint32_t) Data.second.st_dev);
621 Emit16(Out, (uint16_t) Data.second.st_mode);
622 Emit64(Out, (uint64_t) Data.second.st_mtime);
623 Emit64(Out, (uint64_t) Data.second.st_size);
624 }
625
626 assert(Out.tell() - Start == DataLen && "Wrong data length");
627 }
628};
629} // end anonymous namespace
630
631/// \brief Write the stat() system call cache to the PCH file.
632void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
633 // Build the on-disk hash table containing information about every
634 // stat() call.
635 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
636 unsigned NumStatEntries = 0;
637 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
638 StatEnd = StatCalls.end();
639 Stat != StatEnd; ++Stat, ++NumStatEntries)
640 Generator.insert(Stat->first(), Stat->second);
641
642 // Create the on-disk hash table in a buffer.
643 llvm::SmallVector<char, 4096> StatCacheData;
644 uint32_t BucketOffset;
645 {
646 llvm::raw_svector_ostream Out(StatCacheData);
647 // Make sure that no bucket is at offset 0
648 clang::io::Emit32(Out, 0);
649 BucketOffset = Generator.Emit(Out);
650 }
651
652 // Create a blob abbreviation
653 using namespace llvm;
654 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
655 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
657 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
659 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
660
661 // Write the stat cache
662 RecordData Record;
663 Record.push_back(pch::STAT_CACHE);
664 Record.push_back(BucketOffset);
665 Record.push_back(NumStatEntries);
666 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
667 &StatCacheData.front(),
668 StatCacheData.size());
669}
670
671//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000672// Source Manager Serialization
673//===----------------------------------------------------------------------===//
674
675/// \brief Create an abbreviation for the SLocEntry that refers to a
676/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000677static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000678 using namespace llvm;
679 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
680 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000686 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000687}
688
689/// \brief Create an abbreviation for the SLocEntry that refers to a
690/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000691static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000692 using namespace llvm;
693 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
694 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000700 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000701}
702
703/// \brief Create an abbreviation for the SLocEntry that refers to a
704/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000705static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000706 using namespace llvm;
707 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
708 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000710 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000711}
712
713/// \brief Create an abbreviation for the SLocEntry that refers to an
714/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000715static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000716 using namespace llvm;
717 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
718 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000724 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000725}
726
727/// \brief Writes the block containing the serialized form of the
728/// source manager.
729///
730/// TODO: We should probably use an on-disk hash table (stored in a
731/// blob), indexed based on the file name, so that we only create
732/// entries for files that we actually need. In the common case (no
733/// errors), we probably won't have to create file entries for any of
734/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000735void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
736 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000737 RecordData Record;
738
Chris Lattnerf04ad692009-04-10 17:16:57 +0000739 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000740 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000741
742 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000743 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
744 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
745 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
746 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000747
Douglas Gregorbd945002009-04-13 16:31:14 +0000748 // Write the line table.
749 if (SourceMgr.hasLineTable()) {
750 LineTableInfo &LineTable = SourceMgr.getLineTable();
751
752 // Emit the file names
753 Record.push_back(LineTable.getNumFilenames());
754 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
755 // Emit the file name
756 const char *Filename = LineTable.getFilename(I);
757 unsigned FilenameLen = Filename? strlen(Filename) : 0;
758 Record.push_back(FilenameLen);
759 if (FilenameLen)
760 Record.insert(Record.end(), Filename, Filename + FilenameLen);
761 }
762
763 // Emit the line entries
764 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
765 L != LEnd; ++L) {
766 // Emit the file ID
767 Record.push_back(L->first);
768
769 // Emit the line entries
770 Record.push_back(L->second.size());
771 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
772 LEEnd = L->second.end();
773 LE != LEEnd; ++LE) {
774 Record.push_back(LE->FileOffset);
775 Record.push_back(LE->LineNo);
776 Record.push_back(LE->FilenameID);
777 Record.push_back((unsigned)LE->FileKind);
778 Record.push_back(LE->IncludeOffset);
779 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000780 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000781 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000782 }
783
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000784 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000785 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000786 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000787 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
788 E = HS.header_file_end();
789 I != E; ++I) {
790 Record.push_back(I->isImport);
791 Record.push_back(I->DirInfo);
792 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000793 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000794 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
795 Record.clear();
796 }
797
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000798 // Write out the source location entry table. We skip the first
799 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000800 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000801 RecordData PreloadSLocs;
802 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
803 for (SourceManager::sloc_entry_iterator
804 SLoc = SourceMgr.sloc_entry_begin() + 1,
805 SLocEnd = SourceMgr.sloc_entry_end();
806 SLoc != SLocEnd; ++SLoc) {
807 // Record the offset of this source-location entry.
808 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
809
810 // Figure out which record code to use.
811 unsigned Code;
812 if (SLoc->isFile()) {
813 if (SLoc->getFile().getContentCache()->Entry)
814 Code = pch::SM_SLOC_FILE_ENTRY;
815 else
816 Code = pch::SM_SLOC_BUFFER_ENTRY;
817 } else
818 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
819 Record.clear();
820 Record.push_back(Code);
821
822 Record.push_back(SLoc->getOffset());
823 if (SLoc->isFile()) {
824 const SrcMgr::FileInfo &File = SLoc->getFile();
825 Record.push_back(File.getIncludeLoc().getRawEncoding());
826 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
827 Record.push_back(File.hasLineDirectives());
828
829 const SrcMgr::ContentCache *Content = File.getContentCache();
830 if (Content->Entry) {
831 // The source location entry is a file. The blob associated
832 // with this entry is the file name.
833 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
834 Content->Entry->getName(),
835 strlen(Content->Entry->getName()));
836
837 // FIXME: For now, preload all file source locations, so that
838 // we get the appropriate File entries in the reader. This is
839 // a temporary measure.
840 PreloadSLocs.push_back(SLocEntryOffsets.size());
841 } else {
842 // The source location entry is a buffer. The blob associated
843 // with this entry contains the contents of the buffer.
844
845 // We add one to the size so that we capture the trailing NULL
846 // that is required by llvm::MemoryBuffer::getMemBuffer (on
847 // the reader side).
848 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
849 const char *Name = Buffer->getBufferIdentifier();
850 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
851 Record.clear();
852 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
853 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
854 Buffer->getBufferStart(),
855 Buffer->getBufferSize() + 1);
856
857 if (strcmp(Name, "<built-in>") == 0)
858 PreloadSLocs.push_back(SLocEntryOffsets.size());
859 }
860 } else {
861 // The source location entry is an instantiation.
862 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
863 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
864 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
865 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
866
867 // Compute the token length for this macro expansion.
868 unsigned NextOffset = SourceMgr.getNextOffset();
869 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
870 if (++NextSLoc != SLocEnd)
871 NextOffset = NextSLoc->getOffset();
872 Record.push_back(NextOffset - SLoc->getOffset() - 1);
873 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
874 }
875 }
876
Douglas Gregorc9490c02009-04-16 22:23:12 +0000877 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000878
879 if (SLocEntryOffsets.empty())
880 return;
881
882 // Write the source-location offsets table into the PCH block. This
883 // table is used for lazily loading source-location information.
884 using namespace llvm;
885 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
886 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
888 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
890 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
891
892 Record.clear();
893 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
894 Record.push_back(SLocEntryOffsets.size());
895 Record.push_back(SourceMgr.getNextOffset());
896 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
897 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000898 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000899
900 // Write the source location entry preloads array, telling the PCH
901 // reader which source locations entries it should load eagerly.
902 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000903}
904
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000905//===----------------------------------------------------------------------===//
906// Preprocessor Serialization
907//===----------------------------------------------------------------------===//
908
Chris Lattner0b1fb982009-04-10 17:15:23 +0000909/// \brief Writes the block containing the serialized form of the
910/// preprocessor.
911///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000912void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000913 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000914
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000915 // If the preprocessor __COUNTER__ value has been bumped, remember it.
916 if (PP.getCounterValue() != 0) {
917 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000918 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000919 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000920 }
921
922 // Enter the preprocessor block.
923 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000924
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000925 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
926 // FIXME: use diagnostics subsystem for localization etc.
927 if (PP.SawDateOrTime())
928 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
929
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000930 // Loop over all the macro definitions that are live at the end of the file,
931 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000932 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
933 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000934 // FIXME: This emits macros in hash table order, we should do it in a stable
935 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000936 MacroInfo *MI = I->second;
937
938 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
939 // been redefined by the header (in which case they are not isBuiltinMacro).
940 if (MI->isBuiltinMacro())
941 continue;
942
Douglas Gregor37e26842009-04-21 23:56:24 +0000943 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000944 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000945 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000946 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
947 Record.push_back(MI->isUsed());
948
949 unsigned Code;
950 if (MI->isObjectLike()) {
951 Code = pch::PP_MACRO_OBJECT_LIKE;
952 } else {
953 Code = pch::PP_MACRO_FUNCTION_LIKE;
954
955 Record.push_back(MI->isC99Varargs());
956 Record.push_back(MI->isGNUVarargs());
957 Record.push_back(MI->getNumArgs());
958 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
959 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000960 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000961 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000962 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000963 Record.clear();
964
Chris Lattnerdf961c22009-04-10 18:08:30 +0000965 // Emit the tokens array.
966 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
967 // Note that we know that the preprocessor does not have any annotation
968 // tokens in it because they are created by the parser, and thus can't be
969 // in a macro definition.
970 const Token &Tok = MI->getReplacementToken(TokNo);
971
972 Record.push_back(Tok.getLocation().getRawEncoding());
973 Record.push_back(Tok.getLength());
974
Chris Lattnerdf961c22009-04-10 18:08:30 +0000975 // FIXME: When reading literal tokens, reconstruct the literal pointer if
976 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000977 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000978
979 // FIXME: Should translate token kind to a stable encoding.
980 Record.push_back(Tok.getKind());
981 // FIXME: Should translate token flags to a stable encoding.
982 Record.push_back(Tok.getFlags());
983
Douglas Gregorc9490c02009-04-16 22:23:12 +0000984 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000985 Record.clear();
986 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000987 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000988 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000989 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000990}
991
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000992//===----------------------------------------------------------------------===//
993// Type Serialization
994//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000995
Douglas Gregor2cf26342009-04-09 22:27:44 +0000996/// \brief Write the representation of a type to the PCH stream.
997void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000998 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000999 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001000 ID = NextTypeID++;
1001
1002 // Record the offset for this type.
1003 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001004 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1006 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001007 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001008 }
1009
1010 RecordData Record;
1011
1012 // Emit the type's representation.
1013 PCHTypeWriter W(*this, Record);
1014 switch (T->getTypeClass()) {
1015 // For all of the concrete, non-dependent types, call the
1016 // appropriate visitor function.
1017#define TYPE(Class, Base) \
1018 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1019#define ABSTRACT_TYPE(Class, Base)
1020#define DEPENDENT_TYPE(Class, Base)
1021#include "clang/AST/TypeNodes.def"
1022
1023 // For all of the dependent type nodes (which only occur in C++
1024 // templates), produce an error.
1025#define TYPE(Class, Base)
1026#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1027#include "clang/AST/TypeNodes.def"
1028 assert(false && "Cannot serialize dependent type nodes");
1029 break;
1030 }
1031
1032 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001033 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001034
1035 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001036 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001037}
1038
1039/// \brief Write a block containing all of the types.
1040void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001041 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001042 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001043
Douglas Gregor366809a2009-04-26 03:49:13 +00001044 // Emit all of the types that need to be emitted (so far).
1045 while (!TypesToEmit.empty()) {
1046 const Type *T = TypesToEmit.front();
1047 TypesToEmit.pop();
1048 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1049 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001050 }
1051
1052 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001053 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001054}
1055
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001056//===----------------------------------------------------------------------===//
1057// Declaration Serialization
1058//===----------------------------------------------------------------------===//
1059
Douglas Gregor2cf26342009-04-09 22:27:44 +00001060/// \brief Write the block containing all of the declaration IDs
1061/// lexically declared within the given DeclContext.
1062///
1063/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1064/// bistream, or 0 if no block was written.
1065uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1066 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001067 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001068 return 0;
1069
Douglas Gregorc9490c02009-04-16 22:23:12 +00001070 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001071 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001072 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1073 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001074 AddDeclRef(*D, Record);
1075
Douglas Gregor25123082009-04-22 22:34:57 +00001076 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001077 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001078 return Offset;
1079}
1080
1081/// \brief Write the block containing all of the declaration IDs
1082/// visible from the given DeclContext.
1083///
1084/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1085/// bistream, or 0 if no block was written.
1086uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1087 DeclContext *DC) {
1088 if (DC->getPrimaryContext() != DC)
1089 return 0;
1090
Douglas Gregoraff22df2009-04-21 22:32:33 +00001091 // Since there is no name lookup into functions or methods, and we
1092 // perform name lookup for the translation unit via the
1093 // IdentifierInfo chains, don't bother to build a
1094 // visible-declarations table for these entities.
1095 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001096 return 0;
1097
Douglas Gregor2cf26342009-04-09 22:27:44 +00001098 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001099 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001100
1101 // Serialize the contents of the mapping used for lookup. Note that,
1102 // although we have two very different code paths, the serialized
1103 // representation is the same for both cases: a declaration name,
1104 // followed by a size, followed by references to the visible
1105 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001106 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001107 RecordData Record;
1108 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001109 if (!Map)
1110 return 0;
1111
Douglas Gregor2cf26342009-04-09 22:27:44 +00001112 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1113 D != DEnd; ++D) {
1114 AddDeclarationName(D->first, Record);
1115 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1116 Record.push_back(Result.second - Result.first);
1117 for(; Result.first != Result.second; ++Result.first)
1118 AddDeclRef(*Result.first, Record);
1119 }
1120
1121 if (Record.size() == 0)
1122 return 0;
1123
Douglas Gregorc9490c02009-04-16 22:23:12 +00001124 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001125 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001126 return Offset;
1127}
1128
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001129//===----------------------------------------------------------------------===//
1130// Global Method Pool and Selector Serialization
1131//===----------------------------------------------------------------------===//
1132
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001133namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001134// Trait used for the on-disk hash table used in the method pool.
1135class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1136 PCHWriter &Writer;
1137
1138public:
1139 typedef Selector key_type;
1140 typedef key_type key_type_ref;
1141
1142 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1143 typedef const data_type& data_type_ref;
1144
1145 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1146
1147 static unsigned ComputeHash(Selector Sel) {
1148 unsigned N = Sel.getNumArgs();
1149 if (N == 0)
1150 ++N;
1151 unsigned R = 5381;
1152 for (unsigned I = 0; I != N; ++I)
1153 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1154 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1155 return R;
1156 }
1157
1158 std::pair<unsigned,unsigned>
1159 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1160 data_type_ref Methods) {
1161 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1162 clang::io::Emit16(Out, KeyLen);
1163 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1164 for (const ObjCMethodList *Method = &Methods.first; Method;
1165 Method = Method->Next)
1166 if (Method->Method)
1167 DataLen += 4;
1168 for (const ObjCMethodList *Method = &Methods.second; Method;
1169 Method = Method->Next)
1170 if (Method->Method)
1171 DataLen += 4;
1172 clang::io::Emit16(Out, DataLen);
1173 return std::make_pair(KeyLen, DataLen);
1174 }
1175
Douglas Gregor83941df2009-04-25 17:48:32 +00001176 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1177 uint64_t Start = Out.tell();
1178 assert((Start >> 32) == 0 && "Selector key offset too large");
1179 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001180 unsigned N = Sel.getNumArgs();
1181 clang::io::Emit16(Out, N);
1182 if (N == 0)
1183 N = 1;
1184 for (unsigned I = 0; I != N; ++I)
1185 clang::io::Emit32(Out,
1186 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1187 }
1188
1189 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001190 data_type_ref Methods, unsigned DataLen) {
1191 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001192 unsigned NumInstanceMethods = 0;
1193 for (const ObjCMethodList *Method = &Methods.first; Method;
1194 Method = Method->Next)
1195 if (Method->Method)
1196 ++NumInstanceMethods;
1197
1198 unsigned NumFactoryMethods = 0;
1199 for (const ObjCMethodList *Method = &Methods.second; Method;
1200 Method = Method->Next)
1201 if (Method->Method)
1202 ++NumFactoryMethods;
1203
1204 clang::io::Emit16(Out, NumInstanceMethods);
1205 clang::io::Emit16(Out, NumFactoryMethods);
1206 for (const ObjCMethodList *Method = &Methods.first; Method;
1207 Method = Method->Next)
1208 if (Method->Method)
1209 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001210 for (const ObjCMethodList *Method = &Methods.second; Method;
1211 Method = Method->Next)
1212 if (Method->Method)
1213 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001214
1215 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001216 }
1217};
1218} // end anonymous namespace
1219
1220/// \brief Write the method pool into the PCH file.
1221///
1222/// The method pool contains both instance and factory methods, stored
1223/// in an on-disk hash table indexed by the selector.
1224void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1225 using namespace llvm;
1226
1227 // Create and write out the blob that contains the instance and
1228 // factor method pools.
1229 bool Empty = true;
1230 {
1231 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1232
1233 // Create the on-disk hash table representation. Start by
1234 // iterating through the instance method pool.
1235 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001236 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001237 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1238 Instance = SemaRef.InstanceMethodPool.begin(),
1239 InstanceEnd = SemaRef.InstanceMethodPool.end();
1240 Instance != InstanceEnd; ++Instance) {
1241 // Check whether there is a factory method with the same
1242 // selector.
1243 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1244 = SemaRef.FactoryMethodPool.find(Instance->first);
1245
1246 if (Factory == SemaRef.FactoryMethodPool.end())
1247 Generator.insert(Instance->first,
1248 std::make_pair(Instance->second,
1249 ObjCMethodList()));
1250 else
1251 Generator.insert(Instance->first,
1252 std::make_pair(Instance->second, Factory->second));
1253
Douglas Gregor83941df2009-04-25 17:48:32 +00001254 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001255 Empty = false;
1256 }
1257
1258 // Now iterate through the factory method pool, to pick up any
1259 // selectors that weren't already in the instance method pool.
1260 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1261 Factory = SemaRef.FactoryMethodPool.begin(),
1262 FactoryEnd = SemaRef.FactoryMethodPool.end();
1263 Factory != FactoryEnd; ++Factory) {
1264 // Check whether there is an instance method with the same
1265 // selector. If so, there is no work to do here.
1266 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1267 = SemaRef.InstanceMethodPool.find(Factory->first);
1268
Douglas Gregor83941df2009-04-25 17:48:32 +00001269 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001270 Generator.insert(Factory->first,
1271 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001272 ++NumSelectorsInMethodPool;
1273 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001274
1275 Empty = false;
1276 }
1277
Douglas Gregor83941df2009-04-25 17:48:32 +00001278 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001279 return;
1280
1281 // Create the on-disk hash table in a buffer.
1282 llvm::SmallVector<char, 4096> MethodPool;
1283 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001284 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001285 {
1286 PCHMethodPoolTrait Trait(*this);
1287 llvm::raw_svector_ostream Out(MethodPool);
1288 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001289 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001290 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001291
1292 // For every selector that we have seen but which was not
1293 // written into the hash table, write the selector itself and
1294 // record it's offset.
1295 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1296 if (SelectorOffsets[I] == 0)
1297 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001298 }
1299
1300 // Create a blob abbreviation
1301 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1302 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1306 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1307
Douglas Gregor83941df2009-04-25 17:48:32 +00001308 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001309 RecordData Record;
1310 Record.push_back(pch::METHOD_POOL);
1311 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001312 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001313 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1314 &MethodPool.front(),
1315 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001316
1317 // Create a blob abbreviation for the selector table offsets.
1318 Abbrev = new BitCodeAbbrev();
1319 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1320 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1321 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1322 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1323
1324 // Write the selector offsets table.
1325 Record.clear();
1326 Record.push_back(pch::SELECTOR_OFFSETS);
1327 Record.push_back(SelectorOffsets.size());
1328 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1329 (const char *)&SelectorOffsets.front(),
1330 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001331 }
1332}
1333
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001334//===----------------------------------------------------------------------===//
1335// Identifier Table Serialization
1336//===----------------------------------------------------------------------===//
1337
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001338namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001339class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1340 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001341 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001342
Douglas Gregora92193e2009-04-28 21:18:29 +00001343 /// \brief Determines whether this is an "interesting" identifier
1344 /// that needs a full IdentifierInfo structure written into the hash
1345 /// table.
1346 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1347 return II->isPoisoned() ||
1348 II->isExtensionToken() ||
1349 II->hasMacroDefinition() ||
1350 II->getObjCOrBuiltinID() ||
1351 II->getFETokenInfo<void>();
1352 }
1353
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001354public:
1355 typedef const IdentifierInfo* key_type;
1356 typedef key_type key_type_ref;
1357
1358 typedef pch::IdentID data_type;
1359 typedef data_type data_type_ref;
1360
Douglas Gregor37e26842009-04-21 23:56:24 +00001361 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1362 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001363
1364 static unsigned ComputeHash(const IdentifierInfo* II) {
1365 return clang::BernsteinHash(II->getName());
1366 }
1367
Douglas Gregor37e26842009-04-21 23:56:24 +00001368 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001369 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1370 pch::IdentID ID) {
1371 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001372 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1373 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001374 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001375 if (II->hasMacroDefinition() &&
1376 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001377 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001378 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1379 DEnd = IdentifierResolver::end();
1380 D != DEnd; ++D)
1381 DataLen += sizeof(pch::DeclID);
1382 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001383 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001384 // We emit the key length after the data length so that every
1385 // string is preceded by a 16-bit length. This matches the PTH
1386 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001387 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001388 return std::make_pair(KeyLen, DataLen);
1389 }
1390
1391 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1392 unsigned KeyLen) {
1393 // Record the location of the key data. This is used when generating
1394 // the mapping from persistent IDs to strings.
1395 Writer.SetIdentifierOffset(II, Out.tell());
1396 Out.write(II->getName(), KeyLen);
1397 }
1398
1399 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1400 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001401 if (!isInterestingIdentifier(II)) {
1402 clang::io::Emit32(Out, ID << 1);
1403 return;
1404 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001405
Douglas Gregora92193e2009-04-28 21:18:29 +00001406 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001407 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001408 bool hasMacroDefinition =
1409 II->hasMacroDefinition() &&
1410 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001411 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001412 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001413 Bits = (Bits << 1) | II->isExtensionToken();
1414 Bits = (Bits << 1) | II->isPoisoned();
1415 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001416 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001417
Douglas Gregor37e26842009-04-21 23:56:24 +00001418 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001419 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001420
Douglas Gregor668c1a42009-04-21 22:25:48 +00001421 // Emit the declaration IDs in reverse order, because the
1422 // IdentifierResolver provides the declarations as they would be
1423 // visible (e.g., the function "stat" would come before the struct
1424 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1425 // adds declarations to the end of the list (so we need to see the
1426 // struct "status" before the function "status").
1427 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1428 IdentifierResolver::end());
1429 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1430 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001431 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001432 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001433 }
1434};
1435} // end anonymous namespace
1436
Douglas Gregorafaf3082009-04-11 00:14:32 +00001437/// \brief Write the identifier table into the PCH file.
1438///
1439/// The identifier table consists of a blob containing string data
1440/// (the actual identifiers themselves) and a separate "offsets" index
1441/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001442void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001443 using namespace llvm;
1444
1445 // Create and write out the blob that contains the identifier
1446 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001447 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001448 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1449
Douglas Gregor92b059e2009-04-28 20:33:11 +00001450 // Look for any identifiers that were named while processing the
1451 // headers, but are otherwise not needed. We add these to the hash
1452 // table to enable checking of the predefines buffer in the case
1453 // where the user adds new macro definitions when building the PCH
1454 // file.
1455 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1456 IDEnd = PP.getIdentifierTable().end();
1457 ID != IDEnd; ++ID)
1458 getIdentifierRef(ID->second);
1459
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001460 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001461 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001462 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1463 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1464 ID != IDEnd; ++ID) {
1465 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001466 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001467 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001468
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001469 // Create the on-disk hash table in a buffer.
1470 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001471 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001472 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001473 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001474 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001475 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001476 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001477 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001478 }
1479
1480 // Create a blob abbreviation
1481 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1482 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001485 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001486
1487 // Write the identifier table
1488 RecordData Record;
1489 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001490 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001491 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1492 &IdentifierTable.front(),
1493 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001494 }
1495
1496 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001497 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1498 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1499 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1501 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1502
1503 RecordData Record;
1504 Record.push_back(pch::IDENTIFIER_OFFSET);
1505 Record.push_back(IdentifierOffsets.size());
1506 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1507 (const char *)&IdentifierOffsets.front(),
1508 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001509}
1510
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001511//===----------------------------------------------------------------------===//
1512// General Serialization Routines
1513//===----------------------------------------------------------------------===//
1514
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001515/// \brief Write a record containing the given attributes.
1516void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1517 RecordData Record;
1518 for (; Attr; Attr = Attr->getNext()) {
1519 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1520 Record.push_back(Attr->isInherited());
1521 switch (Attr->getKind()) {
1522 case Attr::Alias:
1523 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1524 break;
1525
1526 case Attr::Aligned:
1527 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1528 break;
1529
1530 case Attr::AlwaysInline:
1531 break;
1532
1533 case Attr::AnalyzerNoReturn:
1534 break;
1535
1536 case Attr::Annotate:
1537 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1538 break;
1539
1540 case Attr::AsmLabel:
1541 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1542 break;
1543
1544 case Attr::Blocks:
1545 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1546 break;
1547
1548 case Attr::Cleanup:
1549 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1550 break;
1551
1552 case Attr::Const:
1553 break;
1554
1555 case Attr::Constructor:
1556 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1557 break;
1558
1559 case Attr::DLLExport:
1560 case Attr::DLLImport:
1561 case Attr::Deprecated:
1562 break;
1563
1564 case Attr::Destructor:
1565 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1566 break;
1567
1568 case Attr::FastCall:
1569 break;
1570
1571 case Attr::Format: {
1572 const FormatAttr *Format = cast<FormatAttr>(Attr);
1573 AddString(Format->getType(), Record);
1574 Record.push_back(Format->getFormatIdx());
1575 Record.push_back(Format->getFirstArg());
1576 break;
1577 }
1578
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001579 case Attr::FormatArg: {
1580 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1581 Record.push_back(Format->getFormatIdx());
1582 break;
1583 }
1584
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001585 case Attr::Sentinel : {
1586 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1587 Record.push_back(Sentinel->getSentinel());
1588 Record.push_back(Sentinel->getNullPos());
1589 break;
1590 }
1591
Chris Lattnercf2a7212009-04-20 19:12:28 +00001592 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001593 case Attr::IBOutletKind:
1594 case Attr::NoReturn:
1595 case Attr::NoThrow:
1596 case Attr::Nodebug:
1597 case Attr::Noinline:
1598 break;
1599
1600 case Attr::NonNull: {
1601 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1602 Record.push_back(NonNull->size());
1603 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1604 break;
1605 }
1606
1607 case Attr::ObjCException:
1608 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001609 case Attr::CFReturnsRetained:
1610 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001611 case Attr::Overloadable:
1612 break;
1613
1614 case Attr::Packed:
1615 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1616 break;
1617
1618 case Attr::Pure:
1619 break;
1620
1621 case Attr::Regparm:
1622 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1623 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001624
1625 case Attr::ReqdWorkGroupSize:
1626 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1627 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1628 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1629 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001630
1631 case Attr::Section:
1632 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1633 break;
1634
1635 case Attr::StdCall:
1636 case Attr::TransparentUnion:
1637 case Attr::Unavailable:
1638 case Attr::Unused:
1639 case Attr::Used:
1640 break;
1641
1642 case Attr::Visibility:
1643 // FIXME: stable encoding
1644 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1645 break;
1646
1647 case Attr::WarnUnusedResult:
1648 case Attr::Weak:
1649 case Attr::WeakImport:
1650 break;
1651 }
1652 }
1653
Douglas Gregorc9490c02009-04-16 22:23:12 +00001654 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001655}
1656
1657void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1658 Record.push_back(Str.size());
1659 Record.insert(Record.end(), Str.begin(), Str.end());
1660}
1661
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001662/// \brief Note that the identifier II occurs at the given offset
1663/// within the identifier table.
1664void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001665 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001666}
1667
Douglas Gregor83941df2009-04-25 17:48:32 +00001668/// \brief Note that the selector Sel occurs at the given offset
1669/// within the method pool/selector table.
1670void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1671 unsigned ID = SelectorIDs[Sel];
1672 assert(ID && "Unknown selector");
1673 SelectorOffsets[ID - 1] = Offset;
1674}
1675
Douglas Gregorc9490c02009-04-16 22:23:12 +00001676PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001677 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001678 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1679 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001680
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001681void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001682 using namespace llvm;
1683
Douglas Gregore7785042009-04-20 15:53:59 +00001684 ASTContext &Context = SemaRef.Context;
1685 Preprocessor &PP = SemaRef.PP;
1686
Douglas Gregor2cf26342009-04-09 22:27:44 +00001687 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001688 Stream.Emit((unsigned)'C', 8);
1689 Stream.Emit((unsigned)'P', 8);
1690 Stream.Emit((unsigned)'C', 8);
1691 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001692
1693 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001694
1695 // The translation unit is the first declaration we'll emit.
1696 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1697 DeclsToEmit.push(Context.getTranslationUnitDecl());
1698
Douglas Gregor2deaea32009-04-22 18:49:13 +00001699 // Make sure that we emit IdentifierInfos (and any attached
1700 // declarations) for builtins.
1701 {
1702 IdentifierTable &Table = PP.getIdentifierTable();
1703 llvm::SmallVector<const char *, 32> BuiltinNames;
1704 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1705 Context.getLangOptions().NoBuiltin);
1706 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1707 getIdentifierRef(&Table.get(BuiltinNames[I]));
1708 }
1709
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001710 // Build a record containing all of the tentative definitions in
1711 // this header file. Generally, this record will be empty.
1712 RecordData TentativeDefinitions;
1713 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1714 TD = SemaRef.TentativeDefinitions.begin(),
1715 TDEnd = SemaRef.TentativeDefinitions.end();
1716 TD != TDEnd; ++TD)
1717 AddDeclRef(TD->second, TentativeDefinitions);
1718
Douglas Gregor14c22f22009-04-22 22:18:58 +00001719 // Build a record containing all of the locally-scoped external
1720 // declarations in this header file. Generally, this record will be
1721 // empty.
1722 RecordData LocallyScopedExternalDecls;
1723 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1724 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1725 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1726 TD != TDEnd; ++TD)
1727 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1728
Douglas Gregorb81c1702009-04-27 20:06:05 +00001729 // Build a record containing all of the ext_vector declarations.
1730 RecordData ExtVectorDecls;
1731 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1732 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1733
1734 // Build a record containing all of the Objective-C category
1735 // implementations.
1736 RecordData ObjCCategoryImpls;
1737 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1738 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1739
Douglas Gregor2cf26342009-04-09 22:27:44 +00001740 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001741 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001742 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001743 WriteMetadata(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001744 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001745 if (StatCalls)
1746 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001747 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001748 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001749
1750 // Keep writing types and declarations until all types and
1751 // declarations have been written.
1752 do {
1753 if (!DeclsToEmit.empty())
1754 WriteDeclsBlock(Context);
1755 if (!TypesToEmit.empty())
1756 WriteTypesBlock(Context);
1757 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1758
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001759 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001760 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001761
1762 // Write the type offsets array
1763 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1764 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1767 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1768 Record.clear();
1769 Record.push_back(pch::TYPE_OFFSET);
1770 Record.push_back(TypeOffsets.size());
1771 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1772 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001773 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001774
1775 // Write the declaration offsets array
1776 Abbrev = new BitCodeAbbrev();
1777 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1780 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1781 Record.clear();
1782 Record.push_back(pch::DECL_OFFSET);
1783 Record.push_back(DeclOffsets.size());
1784 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1785 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001786 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001787
1788 // Write the record of special types.
1789 Record.clear();
1790 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001791 AddTypeRef(Context.getObjCIdType(), Record);
1792 AddTypeRef(Context.getObjCSelType(), Record);
1793 AddTypeRef(Context.getObjCProtoType(), Record);
1794 AddTypeRef(Context.getObjCClassType(), Record);
1795 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1796 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001797 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1798
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001799 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001800 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001801 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001802
1803 // Write the record containing tentative definitions.
1804 if (!TentativeDefinitions.empty())
1805 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001806
1807 // Write the record containing locally-scoped external definitions.
1808 if (!LocallyScopedExternalDecls.empty())
1809 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1810 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001811
1812 // Write the record containing ext_vector type names.
1813 if (!ExtVectorDecls.empty())
1814 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1815
1816 // Write the record containing Objective-C category implementations.
1817 if (!ObjCCategoryImpls.empty())
1818 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001819
1820 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001821 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001822 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001823 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001824 Record.push_back(NumLexicalDeclContexts);
1825 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001826 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001827 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001828}
1829
1830void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1831 Record.push_back(Loc.getRawEncoding());
1832}
1833
1834void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1835 Record.push_back(Value.getBitWidth());
1836 unsigned N = Value.getNumWords();
1837 const uint64_t* Words = Value.getRawData();
1838 for (unsigned I = 0; I != N; ++I)
1839 Record.push_back(Words[I]);
1840}
1841
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001842void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1843 Record.push_back(Value.isUnsigned());
1844 AddAPInt(Value, Record);
1845}
1846
Douglas Gregor17fc2232009-04-14 21:55:33 +00001847void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1848 AddAPInt(Value.bitcastToAPInt(), Record);
1849}
1850
Douglas Gregor2cf26342009-04-09 22:27:44 +00001851void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001852 Record.push_back(getIdentifierRef(II));
1853}
1854
1855pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1856 if (II == 0)
1857 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001858
1859 pch::IdentID &ID = IdentifierIDs[II];
1860 if (ID == 0)
1861 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001862 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001863}
1864
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001865void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1866 if (SelRef.getAsOpaquePtr() == 0) {
1867 Record.push_back(0);
1868 return;
1869 }
1870
1871 pch::SelectorID &SID = SelectorIDs[SelRef];
1872 if (SID == 0) {
1873 SID = SelectorIDs.size();
1874 SelVector.push_back(SelRef);
1875 }
1876 Record.push_back(SID);
1877}
1878
Douglas Gregor2cf26342009-04-09 22:27:44 +00001879void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1880 if (T.isNull()) {
1881 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1882 return;
1883 }
1884
1885 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001886 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001887 switch (BT->getKind()) {
1888 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1889 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1890 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1891 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1892 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1893 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1894 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1895 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001896 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001897 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1898 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1899 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1900 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1901 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1902 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1903 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001904 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001905 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1906 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1907 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001908 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001909 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1910 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00001911 case BuiltinType::UndeducedAuto:
1912 assert(0 && "Should not see undeduced auto here");
1913 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001914 }
1915
1916 Record.push_back((ID << 3) | T.getCVRQualifiers());
1917 return;
1918 }
1919
Douglas Gregor8038d512009-04-10 17:25:41 +00001920 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001921 if (ID == 0) {
1922 // We haven't seen this type before. Assign it a new ID and put it
1923 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001924 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001925 TypesToEmit.push(T.getTypePtr());
1926 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001927
1928 // Encode the type qualifiers in the type reference.
1929 Record.push_back((ID << 3) | T.getCVRQualifiers());
1930}
1931
1932void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1933 if (D == 0) {
1934 Record.push_back(0);
1935 return;
1936 }
1937
Douglas Gregor8038d512009-04-10 17:25:41 +00001938 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001939 if (ID == 0) {
1940 // We haven't seen this declaration before. Give it a new ID and
1941 // enqueue it in the list of declarations to emit.
1942 ID = DeclIDs.size();
1943 DeclsToEmit.push(const_cast<Decl *>(D));
1944 }
1945
1946 Record.push_back(ID);
1947}
1948
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001949pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1950 if (D == 0)
1951 return 0;
1952
1953 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1954 return DeclIDs[D];
1955}
1956
Douglas Gregor2cf26342009-04-09 22:27:44 +00001957void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001958 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001959 Record.push_back(Name.getNameKind());
1960 switch (Name.getNameKind()) {
1961 case DeclarationName::Identifier:
1962 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1963 break;
1964
1965 case DeclarationName::ObjCZeroArgSelector:
1966 case DeclarationName::ObjCOneArgSelector:
1967 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001968 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001969 break;
1970
1971 case DeclarationName::CXXConstructorName:
1972 case DeclarationName::CXXDestructorName:
1973 case DeclarationName::CXXConversionFunctionName:
1974 AddTypeRef(Name.getCXXNameType(), Record);
1975 break;
1976
1977 case DeclarationName::CXXOperatorName:
1978 Record.push_back(Name.getCXXOverloadedOperator());
1979 break;
1980
1981 case DeclarationName::CXXUsingDirective:
1982 // No extra data to emit
1983 break;
1984 }
1985}
Douglas Gregor0b748912009-04-14 21:18:50 +00001986