blob: 566df350f614d3183eede5cb50e5a02cb33b58ff [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
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000127void PCHTypeWriter
128::VisitConstantArrayWithExprType(const ConstantArrayWithExprType *T) {
129 VisitArrayType(T);
130 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
131 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
132 Writer.AddAPInt(T->getSize(), Record);
133 Writer.AddStmt(T->getSizeExpr());
134 Code = pch::TYPE_CONSTANT_ARRAY_WITH_EXPR;
135}
136
137void PCHTypeWriter
138::VisitConstantArrayWithoutExprType(const ConstantArrayWithoutExprType *T) {
139 VisitArrayType(T);
140 Writer.AddAPInt(T->getSize(), Record);
141 Code = pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR;
142}
143
Douglas Gregor2cf26342009-04-09 22:27:44 +0000144void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
145 VisitArrayType(T);
146 Code = pch::TYPE_INCOMPLETE_ARRAY;
147}
148
149void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
150 VisitArrayType(T);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000151 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
152 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000153 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000154 Code = pch::TYPE_VARIABLE_ARRAY;
155}
156
157void PCHTypeWriter::VisitVectorType(const VectorType *T) {
158 Writer.AddTypeRef(T->getElementType(), Record);
159 Record.push_back(T->getNumElements());
160 Code = pch::TYPE_VECTOR;
161}
162
163void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
164 VisitVectorType(T);
165 Code = pch::TYPE_EXT_VECTOR;
166}
167
168void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
169 Writer.AddTypeRef(T->getResultType(), Record);
170}
171
172void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
173 VisitFunctionType(T);
174 Code = pch::TYPE_FUNCTION_NO_PROTO;
175}
176
177void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
178 VisitFunctionType(T);
179 Record.push_back(T->getNumArgs());
180 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
181 Writer.AddTypeRef(T->getArgType(I), Record);
182 Record.push_back(T->isVariadic());
183 Record.push_back(T->getTypeQuals());
Sebastian Redl465226e2009-05-27 22:11:52 +0000184 Record.push_back(T->hasExceptionSpec());
185 Record.push_back(T->hasAnyExceptionSpec());
186 Record.push_back(T->getNumExceptions());
187 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
188 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000189 Code = pch::TYPE_FUNCTION_PROTO;
190}
191
192void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
193 Writer.AddDeclRef(T->getDecl(), Record);
194 Code = pch::TYPE_TYPEDEF;
195}
196
197void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000198 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000199 Code = pch::TYPE_TYPEOF_EXPR;
200}
201
202void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
203 Writer.AddTypeRef(T->getUnderlyingType(), Record);
204 Code = pch::TYPE_TYPEOF;
205}
206
Anders Carlsson395b4752009-06-24 19:06:50 +0000207void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
208 Writer.AddStmt(T->getUnderlyingExpr());
209 Code = pch::TYPE_DECLTYPE;
210}
211
Douglas Gregor2cf26342009-04-09 22:27:44 +0000212void PCHTypeWriter::VisitTagType(const TagType *T) {
213 Writer.AddDeclRef(T->getDecl(), Record);
214 assert(!T->isBeingDefined() &&
215 "Cannot serialize in the middle of a type definition");
216}
217
218void PCHTypeWriter::VisitRecordType(const RecordType *T) {
219 VisitTagType(T);
220 Code = pch::TYPE_RECORD;
221}
222
223void PCHTypeWriter::VisitEnumType(const EnumType *T) {
224 VisitTagType(T);
225 Code = pch::TYPE_ENUM;
226}
227
228void
229PCHTypeWriter::VisitTemplateSpecializationType(
230 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000231 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000232 assert(false && "Cannot serialize template specialization types");
233}
234
235void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000236 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000237 assert(false && "Cannot serialize qualified name types");
238}
239
240void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
241 Writer.AddDeclRef(T->getDecl(), Record);
242 Code = pch::TYPE_OBJC_INTERFACE;
243}
244
245void
246PCHTypeWriter::VisitObjCQualifiedInterfaceType(
247 const ObjCQualifiedInterfaceType *T) {
248 VisitObjCInterfaceType(T);
249 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000250 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
251 E = T->qual_end(); I != E; ++I)
252 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000253 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
254}
255
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000256void
257PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
258 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000259 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000260 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000261 E = T->qual_end(); I != E; ++I)
262 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000263 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000264}
265
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000266//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000267// PCHWriter Implementation
268//===----------------------------------------------------------------------===//
269
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000270static void EmitBlockID(unsigned ID, const char *Name,
271 llvm::BitstreamWriter &Stream,
272 PCHWriter::RecordData &Record) {
273 Record.clear();
274 Record.push_back(ID);
275 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
276
277 // Emit the block name if present.
278 if (Name == 0 || Name[0] == 0) return;
279 Record.clear();
280 while (*Name)
281 Record.push_back(*Name++);
282 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
283}
284
285static void EmitRecordID(unsigned ID, const char *Name,
286 llvm::BitstreamWriter &Stream,
287 PCHWriter::RecordData &Record) {
288 Record.clear();
289 Record.push_back(ID);
290 while (*Name)
291 Record.push_back(*Name++);
292 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000293}
294
295static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
296 PCHWriter::RecordData &Record) {
297#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
298 RECORD(STMT_STOP);
299 RECORD(STMT_NULL_PTR);
300 RECORD(STMT_NULL);
301 RECORD(STMT_COMPOUND);
302 RECORD(STMT_CASE);
303 RECORD(STMT_DEFAULT);
304 RECORD(STMT_LABEL);
305 RECORD(STMT_IF);
306 RECORD(STMT_SWITCH);
307 RECORD(STMT_WHILE);
308 RECORD(STMT_DO);
309 RECORD(STMT_FOR);
310 RECORD(STMT_GOTO);
311 RECORD(STMT_INDIRECT_GOTO);
312 RECORD(STMT_CONTINUE);
313 RECORD(STMT_BREAK);
314 RECORD(STMT_RETURN);
315 RECORD(STMT_DECL);
316 RECORD(STMT_ASM);
317 RECORD(EXPR_PREDEFINED);
318 RECORD(EXPR_DECL_REF);
319 RECORD(EXPR_INTEGER_LITERAL);
320 RECORD(EXPR_FLOATING_LITERAL);
321 RECORD(EXPR_IMAGINARY_LITERAL);
322 RECORD(EXPR_STRING_LITERAL);
323 RECORD(EXPR_CHARACTER_LITERAL);
324 RECORD(EXPR_PAREN);
325 RECORD(EXPR_UNARY_OPERATOR);
326 RECORD(EXPR_SIZEOF_ALIGN_OF);
327 RECORD(EXPR_ARRAY_SUBSCRIPT);
328 RECORD(EXPR_CALL);
329 RECORD(EXPR_MEMBER);
330 RECORD(EXPR_BINARY_OPERATOR);
331 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
332 RECORD(EXPR_CONDITIONAL_OPERATOR);
333 RECORD(EXPR_IMPLICIT_CAST);
334 RECORD(EXPR_CSTYLE_CAST);
335 RECORD(EXPR_COMPOUND_LITERAL);
336 RECORD(EXPR_EXT_VECTOR_ELEMENT);
337 RECORD(EXPR_INIT_LIST);
338 RECORD(EXPR_DESIGNATED_INIT);
339 RECORD(EXPR_IMPLICIT_VALUE_INIT);
340 RECORD(EXPR_VA_ARG);
341 RECORD(EXPR_ADDR_LABEL);
342 RECORD(EXPR_STMT);
343 RECORD(EXPR_TYPES_COMPATIBLE);
344 RECORD(EXPR_CHOOSE);
345 RECORD(EXPR_GNU_NULL);
346 RECORD(EXPR_SHUFFLE_VECTOR);
347 RECORD(EXPR_BLOCK);
348 RECORD(EXPR_BLOCK_DECL_REF);
349 RECORD(EXPR_OBJC_STRING_LITERAL);
350 RECORD(EXPR_OBJC_ENCODE);
351 RECORD(EXPR_OBJC_SELECTOR_EXPR);
352 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
353 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
354 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
355 RECORD(EXPR_OBJC_KVC_REF_EXPR);
356 RECORD(EXPR_OBJC_MESSAGE_EXPR);
357 RECORD(EXPR_OBJC_SUPER_EXPR);
358 RECORD(STMT_OBJC_FOR_COLLECTION);
359 RECORD(STMT_OBJC_CATCH);
360 RECORD(STMT_OBJC_FINALLY);
361 RECORD(STMT_OBJC_AT_TRY);
362 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
363 RECORD(STMT_OBJC_AT_THROW);
364#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000365}
366
367void PCHWriter::WriteBlockInfoBlock() {
368 RecordData Record;
369 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
370
Chris Lattner2f4efd12009-04-27 00:40:25 +0000371#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000372#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
373
374 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000375 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000376 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000377 RECORD(TYPE_OFFSET);
378 RECORD(DECL_OFFSET);
379 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000380 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000381 RECORD(IDENTIFIER_OFFSET);
382 RECORD(IDENTIFIER_TABLE);
383 RECORD(EXTERNAL_DEFINITIONS);
384 RECORD(SPECIAL_TYPES);
385 RECORD(STATISTICS);
386 RECORD(TENTATIVE_DEFINITIONS);
387 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
388 RECORD(SELECTOR_OFFSETS);
389 RECORD(METHOD_POOL);
390 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000391 RECORD(SOURCE_LOCATION_OFFSETS);
392 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000393 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000394 RECORD(EXT_VECTOR_DECLS);
395 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000396 RECORD(COMMENT_RANGES);
397
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000398 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000399 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000400 RECORD(SM_SLOC_FILE_ENTRY);
401 RECORD(SM_SLOC_BUFFER_ENTRY);
402 RECORD(SM_SLOC_BUFFER_BLOB);
403 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
404 RECORD(SM_LINE_TABLE);
405 RECORD(SM_HEADER_FILE_INFO);
406
407 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000408 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000409 RECORD(PP_MACRO_OBJECT_LIKE);
410 RECORD(PP_MACRO_FUNCTION_LIKE);
411 RECORD(PP_TOKEN);
412
413 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000414 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000415 RECORD(TYPE_EXT_QUAL);
416 RECORD(TYPE_FIXED_WIDTH_INT);
417 RECORD(TYPE_COMPLEX);
418 RECORD(TYPE_POINTER);
419 RECORD(TYPE_BLOCK_POINTER);
420 RECORD(TYPE_LVALUE_REFERENCE);
421 RECORD(TYPE_RVALUE_REFERENCE);
422 RECORD(TYPE_MEMBER_POINTER);
423 RECORD(TYPE_CONSTANT_ARRAY);
424 RECORD(TYPE_INCOMPLETE_ARRAY);
425 RECORD(TYPE_VARIABLE_ARRAY);
426 RECORD(TYPE_VECTOR);
427 RECORD(TYPE_EXT_VECTOR);
428 RECORD(TYPE_FUNCTION_PROTO);
429 RECORD(TYPE_FUNCTION_NO_PROTO);
430 RECORD(TYPE_TYPEDEF);
431 RECORD(TYPE_TYPEOF_EXPR);
432 RECORD(TYPE_TYPEOF);
433 RECORD(TYPE_RECORD);
434 RECORD(TYPE_ENUM);
435 RECORD(TYPE_OBJC_INTERFACE);
436 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000437 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000438 // Statements and Exprs can occur in the Types block.
439 AddStmtsExprs(Stream, Record);
440
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000441 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000442 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000443 RECORD(DECL_ATTR);
444 RECORD(DECL_TRANSLATION_UNIT);
445 RECORD(DECL_TYPEDEF);
446 RECORD(DECL_ENUM);
447 RECORD(DECL_RECORD);
448 RECORD(DECL_ENUM_CONSTANT);
449 RECORD(DECL_FUNCTION);
450 RECORD(DECL_OBJC_METHOD);
451 RECORD(DECL_OBJC_INTERFACE);
452 RECORD(DECL_OBJC_PROTOCOL);
453 RECORD(DECL_OBJC_IVAR);
454 RECORD(DECL_OBJC_AT_DEFS_FIELD);
455 RECORD(DECL_OBJC_CLASS);
456 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
457 RECORD(DECL_OBJC_CATEGORY);
458 RECORD(DECL_OBJC_CATEGORY_IMPL);
459 RECORD(DECL_OBJC_IMPLEMENTATION);
460 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
461 RECORD(DECL_OBJC_PROPERTY);
462 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000463 RECORD(DECL_FIELD);
464 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000465 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000466 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000467 RECORD(DECL_ORIGINAL_PARM_VAR);
468 RECORD(DECL_FILE_SCOPE_ASM);
469 RECORD(DECL_BLOCK);
470 RECORD(DECL_CONTEXT_LEXICAL);
471 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000472 // Statements and Exprs can occur in the Decls block.
473 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000474#undef RECORD
475#undef BLOCK
476 Stream.ExitBlock();
477}
478
Douglas Gregore650c8c2009-07-07 00:12:59 +0000479/// \brief Adjusts the given filename to only write out the portion of the
480/// filename that is not part of the system root directory.
481///
482/// \param Filename the file name to adjust.
483///
484/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
485/// the returned filename will be adjusted by this system root.
486///
487/// \returns either the original filename (if it needs no adjustment) or the
488/// adjusted filename (which points into the @p Filename parameter).
489static const char *
490adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
491 assert(Filename && "No file name to adjust?");
492
493 if (!isysroot)
494 return Filename;
495
496 // Verify that the filename and the system root have the same prefix.
497 unsigned Pos = 0;
498 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
499 if (Filename[Pos] != isysroot[Pos])
500 return Filename; // Prefixes don't match.
501
502 // We hit the end of the filename before we hit the end of the system root.
503 if (!Filename[Pos])
504 return Filename;
505
506 // If the file name has a '/' at the current position, skip over the '/'.
507 // We distinguish sysroot-based includes from absolute includes by the
508 // absence of '/' at the beginning of sysroot-based includes.
509 if (Filename[Pos] == '/')
510 ++Pos;
511
512 return Filename + Pos;
513}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000514
Douglas Gregorab41e632009-04-27 22:23:34 +0000515/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000516void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000517 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000518
Douglas Gregore650c8c2009-07-07 00:12:59 +0000519 // Metadata
520 const TargetInfo &Target = Context.Target;
521 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
522 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
523 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
524 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
525 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
526 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
527 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
528 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
529 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
530
531 RecordData Record;
532 Record.push_back(pch::METADATA);
533 Record.push_back(pch::VERSION_MAJOR);
534 Record.push_back(pch::VERSION_MINOR);
535 Record.push_back(CLANG_VERSION_MAJOR);
536 Record.push_back(CLANG_VERSION_MINOR);
537 Record.push_back(isysroot != 0);
538 const char *Triple = Target.getTargetTriple();
539 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
540
Douglas Gregorb64c1932009-05-12 01:31:05 +0000541 // Original file name
542 SourceManager &SM = Context.getSourceManager();
543 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
544 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
545 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
546 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
547 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
548
549 llvm::sys::Path MainFilePath(MainFile->getName());
550 std::string MainFileName;
551
552 if (!MainFilePath.isAbsolute()) {
553 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
554 P.appendComponent(MainFilePath.toString());
555 MainFileName = P.toString();
556 } else {
557 MainFileName = MainFilePath.toString();
558 }
559
Douglas Gregore650c8c2009-07-07 00:12:59 +0000560 const char *MainFileNameStr = MainFileName.c_str();
561 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
562 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000563 RecordData Record;
564 Record.push_back(pch::ORIGINAL_FILE_NAME);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000565 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr,
566 strlen(MainFileNameStr));
Douglas Gregorb64c1932009-05-12 01:31:05 +0000567 }
Douglas Gregor2bec0412009-04-10 21:16:55 +0000568}
569
570/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000571void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
572 RecordData Record;
573 Record.push_back(LangOpts.Trigraphs);
574 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
575 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
576 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
577 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
578 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
579 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
580 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
581 Record.push_back(LangOpts.C99); // C99 Support
582 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
583 Record.push_back(LangOpts.CPlusPlus); // C++ Support
584 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000585 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
586
587 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
588 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
589 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
590
591 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000592 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
593 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000594 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000595 Record.push_back(LangOpts.Exceptions); // Support exception handling.
596
597 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
598 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
599 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
600
Chris Lattnerea5ce472009-04-27 07:35:58 +0000601 // Whether static initializers are protected by locks.
602 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000603 Record.push_back(LangOpts.Blocks); // block extension to C
604 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
605 // they are unused.
606 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
607 // (modulo the platform support).
608
609 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
610 // signed integer arithmetic overflows.
611
612 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
613 // may be ripped out at any time.
614
615 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
616 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
617 // defined.
618 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
619 // opposed to __DYNAMIC__).
620 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
621
622 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
623 // used (instead of C99 semantics).
624 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000625 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
626 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000627 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
628 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000629 Record.push_back(LangOpts.getGCMode());
630 Record.push_back(LangOpts.getVisibilityMode());
631 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000632 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000633 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000634}
635
Douglas Gregor14f79002009-04-10 03:52:48 +0000636//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000637// stat cache Serialization
638//===----------------------------------------------------------------------===//
639
640namespace {
641// Trait used for the on-disk hash table of stat cache results.
642class VISIBILITY_HIDDEN PCHStatCacheTrait {
643public:
644 typedef const char * key_type;
645 typedef key_type key_type_ref;
646
647 typedef std::pair<int, struct stat> data_type;
648 typedef const data_type& data_type_ref;
649
650 static unsigned ComputeHash(const char *path) {
651 return BernsteinHash(path);
652 }
653
654 std::pair<unsigned,unsigned>
655 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
656 data_type_ref Data) {
657 unsigned StrLen = strlen(path);
658 clang::io::Emit16(Out, StrLen);
659 unsigned DataLen = 1; // result value
660 if (Data.first == 0)
661 DataLen += 4 + 4 + 2 + 8 + 8;
662 clang::io::Emit8(Out, DataLen);
663 return std::make_pair(StrLen + 1, DataLen);
664 }
665
666 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
667 Out.write(path, KeyLen);
668 }
669
670 void EmitData(llvm::raw_ostream& Out, key_type_ref,
671 data_type_ref Data, unsigned DataLen) {
672 using namespace clang::io;
673 uint64_t Start = Out.tell(); (void)Start;
674
675 // Result of stat()
676 Emit8(Out, Data.first? 1 : 0);
677
678 if (Data.first == 0) {
679 Emit32(Out, (uint32_t) Data.second.st_ino);
680 Emit32(Out, (uint32_t) Data.second.st_dev);
681 Emit16(Out, (uint16_t) Data.second.st_mode);
682 Emit64(Out, (uint64_t) Data.second.st_mtime);
683 Emit64(Out, (uint64_t) Data.second.st_size);
684 }
685
686 assert(Out.tell() - Start == DataLen && "Wrong data length");
687 }
688};
689} // end anonymous namespace
690
691/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000692void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
693 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000694 // Build the on-disk hash table containing information about every
695 // stat() call.
696 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
697 unsigned NumStatEntries = 0;
698 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
699 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000700 Stat != StatEnd; ++Stat, ++NumStatEntries) {
701 const char *Filename = Stat->first();
702 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
703 Generator.insert(Filename, Stat->second);
704 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000705
706 // Create the on-disk hash table in a buffer.
707 llvm::SmallVector<char, 4096> StatCacheData;
708 uint32_t BucketOffset;
709 {
710 llvm::raw_svector_ostream Out(StatCacheData);
711 // Make sure that no bucket is at offset 0
712 clang::io::Emit32(Out, 0);
713 BucketOffset = Generator.Emit(Out);
714 }
715
716 // Create a blob abbreviation
717 using namespace llvm;
718 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
719 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
723 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
724
725 // Write the stat cache
726 RecordData Record;
727 Record.push_back(pch::STAT_CACHE);
728 Record.push_back(BucketOffset);
729 Record.push_back(NumStatEntries);
730 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
731 &StatCacheData.front(),
732 StatCacheData.size());
733}
734
735//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000736// Source Manager Serialization
737//===----------------------------------------------------------------------===//
738
739/// \brief Create an abbreviation for the SLocEntry that refers to a
740/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000741static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000742 using namespace llvm;
743 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
744 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000750 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000751}
752
753/// \brief Create an abbreviation for the SLocEntry that refers to a
754/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000755static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000756 using namespace llvm;
757 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
758 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000764 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000765}
766
767/// \brief Create an abbreviation for the SLocEntry that refers to a
768/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000769static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000770 using namespace llvm;
771 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
772 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000774 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000775}
776
777/// \brief Create an abbreviation for the SLocEntry that refers to an
778/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000779static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000780 using namespace llvm;
781 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
782 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
783 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000787 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000788 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000789}
790
791/// \brief Writes the block containing the serialized form of the
792/// source manager.
793///
794/// TODO: We should probably use an on-disk hash table (stored in a
795/// blob), indexed based on the file name, so that we only create
796/// entries for files that we actually need. In the common case (no
797/// errors), we probably won't have to create file entries for any of
798/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000799void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000800 const Preprocessor &PP,
801 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000802 RecordData Record;
803
Chris Lattnerf04ad692009-04-10 17:16:57 +0000804 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000805 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000806
807 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000808 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
809 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
810 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
811 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000812
Douglas Gregorbd945002009-04-13 16:31:14 +0000813 // Write the line table.
814 if (SourceMgr.hasLineTable()) {
815 LineTableInfo &LineTable = SourceMgr.getLineTable();
816
817 // Emit the file names
818 Record.push_back(LineTable.getNumFilenames());
819 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
820 // Emit the file name
821 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000822 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000823 unsigned FilenameLen = Filename? strlen(Filename) : 0;
824 Record.push_back(FilenameLen);
825 if (FilenameLen)
826 Record.insert(Record.end(), Filename, Filename + FilenameLen);
827 }
828
829 // Emit the line entries
830 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
831 L != LEnd; ++L) {
832 // Emit the file ID
833 Record.push_back(L->first);
834
835 // Emit the line entries
836 Record.push_back(L->second.size());
837 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
838 LEEnd = L->second.end();
839 LE != LEEnd; ++LE) {
840 Record.push_back(LE->FileOffset);
841 Record.push_back(LE->LineNo);
842 Record.push_back(LE->FilenameID);
843 Record.push_back((unsigned)LE->FileKind);
844 Record.push_back(LE->IncludeOffset);
845 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000846 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000847 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000848 }
849
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000850 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000851 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000852 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000853 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
854 E = HS.header_file_end();
855 I != E; ++I) {
856 Record.push_back(I->isImport);
857 Record.push_back(I->DirInfo);
858 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000859 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000860 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
861 Record.clear();
862 }
863
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000864 // Write out the source location entry table. We skip the first
865 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000866 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000867 RecordData PreloadSLocs;
868 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
869 for (SourceManager::sloc_entry_iterator
870 SLoc = SourceMgr.sloc_entry_begin() + 1,
871 SLocEnd = SourceMgr.sloc_entry_end();
872 SLoc != SLocEnd; ++SLoc) {
873 // Record the offset of this source-location entry.
874 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
875
876 // Figure out which record code to use.
877 unsigned Code;
878 if (SLoc->isFile()) {
879 if (SLoc->getFile().getContentCache()->Entry)
880 Code = pch::SM_SLOC_FILE_ENTRY;
881 else
882 Code = pch::SM_SLOC_BUFFER_ENTRY;
883 } else
884 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
885 Record.clear();
886 Record.push_back(Code);
887
888 Record.push_back(SLoc->getOffset());
889 if (SLoc->isFile()) {
890 const SrcMgr::FileInfo &File = SLoc->getFile();
891 Record.push_back(File.getIncludeLoc().getRawEncoding());
892 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
893 Record.push_back(File.hasLineDirectives());
894
895 const SrcMgr::ContentCache *Content = File.getContentCache();
896 if (Content->Entry) {
897 // The source location entry is a file. The blob associated
898 // with this entry is the file name.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000899
900 // Turn the file name into an absolute path, if it isn't already.
901 const char *Filename = Content->Entry->getName();
902 llvm::sys::Path FilePath(Filename, strlen(Filename));
903 std::string FilenameStr;
904 if (!FilePath.isAbsolute()) {
905 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
906 P.appendComponent(FilePath.toString());
907 FilenameStr = P.toString();
908 Filename = FilenameStr.c_str();
909 }
910
911 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
912 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename,
913 strlen(Filename));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000914
915 // FIXME: For now, preload all file source locations, so that
916 // we get the appropriate File entries in the reader. This is
917 // a temporary measure.
918 PreloadSLocs.push_back(SLocEntryOffsets.size());
919 } else {
920 // The source location entry is a buffer. The blob associated
921 // with this entry contains the contents of the buffer.
922
923 // We add one to the size so that we capture the trailing NULL
924 // that is required by llvm::MemoryBuffer::getMemBuffer (on
925 // the reader side).
926 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
927 const char *Name = Buffer->getBufferIdentifier();
928 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
929 Record.clear();
930 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
931 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
932 Buffer->getBufferStart(),
933 Buffer->getBufferSize() + 1);
934
935 if (strcmp(Name, "<built-in>") == 0)
936 PreloadSLocs.push_back(SLocEntryOffsets.size());
937 }
938 } else {
939 // The source location entry is an instantiation.
940 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
941 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
942 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
943 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
944
945 // Compute the token length for this macro expansion.
946 unsigned NextOffset = SourceMgr.getNextOffset();
947 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
948 if (++NextSLoc != SLocEnd)
949 NextOffset = NextSLoc->getOffset();
950 Record.push_back(NextOffset - SLoc->getOffset() - 1);
951 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
952 }
953 }
954
Douglas Gregorc9490c02009-04-16 22:23:12 +0000955 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000956
957 if (SLocEntryOffsets.empty())
958 return;
959
960 // Write the source-location offsets table into the PCH block. This
961 // table is used for lazily loading source-location information.
962 using namespace llvm;
963 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
964 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
965 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
966 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
967 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
968 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
969
970 Record.clear();
971 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
972 Record.push_back(SLocEntryOffsets.size());
973 Record.push_back(SourceMgr.getNextOffset());
974 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
975 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000976 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000977
978 // Write the source location entry preloads array, telling the PCH
979 // reader which source locations entries it should load eagerly.
980 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000981}
982
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000983//===----------------------------------------------------------------------===//
984// Preprocessor Serialization
985//===----------------------------------------------------------------------===//
986
Chris Lattner0b1fb982009-04-10 17:15:23 +0000987/// \brief Writes the block containing the serialized form of the
988/// preprocessor.
989///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000990void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000991 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000992
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000993 // If the preprocessor __COUNTER__ value has been bumped, remember it.
994 if (PP.getCounterValue() != 0) {
995 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000996 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000997 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000998 }
999
1000 // Enter the preprocessor block.
1001 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001002
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001003 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1004 // FIXME: use diagnostics subsystem for localization etc.
1005 if (PP.SawDateOrTime())
1006 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1007
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001008 // Loop over all the macro definitions that are live at the end of the file,
1009 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001010 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1011 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001012 // FIXME: This emits macros in hash table order, we should do it in a stable
1013 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001014 MacroInfo *MI = I->second;
1015
1016 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1017 // been redefined by the header (in which case they are not isBuiltinMacro).
1018 if (MI->isBuiltinMacro())
1019 continue;
1020
Douglas Gregor37e26842009-04-21 23:56:24 +00001021 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001022 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001023 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001024 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1025 Record.push_back(MI->isUsed());
1026
1027 unsigned Code;
1028 if (MI->isObjectLike()) {
1029 Code = pch::PP_MACRO_OBJECT_LIKE;
1030 } else {
1031 Code = pch::PP_MACRO_FUNCTION_LIKE;
1032
1033 Record.push_back(MI->isC99Varargs());
1034 Record.push_back(MI->isGNUVarargs());
1035 Record.push_back(MI->getNumArgs());
1036 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1037 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001038 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001039 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001040 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001041 Record.clear();
1042
Chris Lattnerdf961c22009-04-10 18:08:30 +00001043 // Emit the tokens array.
1044 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1045 // Note that we know that the preprocessor does not have any annotation
1046 // tokens in it because they are created by the parser, and thus can't be
1047 // in a macro definition.
1048 const Token &Tok = MI->getReplacementToken(TokNo);
1049
1050 Record.push_back(Tok.getLocation().getRawEncoding());
1051 Record.push_back(Tok.getLength());
1052
Chris Lattnerdf961c22009-04-10 18:08:30 +00001053 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1054 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001055 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001056
1057 // FIXME: Should translate token kind to a stable encoding.
1058 Record.push_back(Tok.getKind());
1059 // FIXME: Should translate token flags to a stable encoding.
1060 Record.push_back(Tok.getFlags());
1061
Douglas Gregorc9490c02009-04-16 22:23:12 +00001062 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001063 Record.clear();
1064 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001065 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001066 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001067 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001068}
1069
Douglas Gregor2e222532009-07-02 17:08:52 +00001070void PCHWriter::WriteComments(ASTContext &Context) {
1071 using namespace llvm;
1072
1073 if (Context.Comments.empty())
1074 return;
1075
1076 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1077 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1078 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1079 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1080
1081 RecordData Record;
1082 Record.push_back(pch::COMMENT_RANGES);
1083 Stream.EmitRecordWithBlob(CommentCode, Record,
1084 (const char*)&Context.Comments[0],
1085 Context.Comments.size() * sizeof(SourceRange));
1086}
1087
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001088//===----------------------------------------------------------------------===//
1089// Type Serialization
1090//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001091
Douglas Gregor2cf26342009-04-09 22:27:44 +00001092/// \brief Write the representation of a type to the PCH stream.
1093void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001094 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001095 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001096 ID = NextTypeID++;
1097
1098 // Record the offset for this type.
1099 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001100 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001101 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1102 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001103 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001104 }
1105
1106 RecordData Record;
1107
1108 // Emit the type's representation.
1109 PCHTypeWriter W(*this, Record);
1110 switch (T->getTypeClass()) {
1111 // For all of the concrete, non-dependent types, call the
1112 // appropriate visitor function.
1113#define TYPE(Class, Base) \
1114 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1115#define ABSTRACT_TYPE(Class, Base)
1116#define DEPENDENT_TYPE(Class, Base)
1117#include "clang/AST/TypeNodes.def"
1118
1119 // For all of the dependent type nodes (which only occur in C++
1120 // templates), produce an error.
1121#define TYPE(Class, Base)
1122#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1123#include "clang/AST/TypeNodes.def"
1124 assert(false && "Cannot serialize dependent type nodes");
1125 break;
1126 }
1127
1128 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001129 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001130
1131 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001132 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001133}
1134
1135/// \brief Write a block containing all of the types.
1136void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001137 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001138 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001139
Douglas Gregor366809a2009-04-26 03:49:13 +00001140 // Emit all of the types that need to be emitted (so far).
1141 while (!TypesToEmit.empty()) {
1142 const Type *T = TypesToEmit.front();
1143 TypesToEmit.pop();
1144 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1145 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001146 }
1147
1148 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001149 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001150}
1151
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001152//===----------------------------------------------------------------------===//
1153// Declaration Serialization
1154//===----------------------------------------------------------------------===//
1155
Douglas Gregor2cf26342009-04-09 22:27:44 +00001156/// \brief Write the block containing all of the declaration IDs
1157/// lexically declared within the given DeclContext.
1158///
1159/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1160/// bistream, or 0 if no block was written.
1161uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1162 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001163 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001164 return 0;
1165
Douglas Gregorc9490c02009-04-16 22:23:12 +00001166 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001167 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001168 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1169 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001170 AddDeclRef(*D, Record);
1171
Douglas Gregor25123082009-04-22 22:34:57 +00001172 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001173 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001174 return Offset;
1175}
1176
1177/// \brief Write the block containing all of the declaration IDs
1178/// visible from the given DeclContext.
1179///
1180/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1181/// bistream, or 0 if no block was written.
1182uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1183 DeclContext *DC) {
1184 if (DC->getPrimaryContext() != DC)
1185 return 0;
1186
Douglas Gregoraff22df2009-04-21 22:32:33 +00001187 // Since there is no name lookup into functions or methods, and we
1188 // perform name lookup for the translation unit via the
1189 // IdentifierInfo chains, don't bother to build a
1190 // visible-declarations table for these entities.
1191 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001192 return 0;
1193
Douglas Gregor2cf26342009-04-09 22:27:44 +00001194 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001195 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001196
1197 // Serialize the contents of the mapping used for lookup. Note that,
1198 // although we have two very different code paths, the serialized
1199 // representation is the same for both cases: a declaration name,
1200 // followed by a size, followed by references to the visible
1201 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001202 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001203 RecordData Record;
1204 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001205 if (!Map)
1206 return 0;
1207
Douglas Gregor2cf26342009-04-09 22:27:44 +00001208 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1209 D != DEnd; ++D) {
1210 AddDeclarationName(D->first, Record);
1211 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1212 Record.push_back(Result.second - Result.first);
1213 for(; Result.first != Result.second; ++Result.first)
1214 AddDeclRef(*Result.first, Record);
1215 }
1216
1217 if (Record.size() == 0)
1218 return 0;
1219
Douglas Gregorc9490c02009-04-16 22:23:12 +00001220 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001221 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001222 return Offset;
1223}
1224
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001225//===----------------------------------------------------------------------===//
1226// Global Method Pool and Selector Serialization
1227//===----------------------------------------------------------------------===//
1228
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001229namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001230// Trait used for the on-disk hash table used in the method pool.
1231class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1232 PCHWriter &Writer;
1233
1234public:
1235 typedef Selector key_type;
1236 typedef key_type key_type_ref;
1237
1238 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1239 typedef const data_type& data_type_ref;
1240
1241 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1242
1243 static unsigned ComputeHash(Selector Sel) {
1244 unsigned N = Sel.getNumArgs();
1245 if (N == 0)
1246 ++N;
1247 unsigned R = 5381;
1248 for (unsigned I = 0; I != N; ++I)
1249 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1250 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1251 return R;
1252 }
1253
1254 std::pair<unsigned,unsigned>
1255 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1256 data_type_ref Methods) {
1257 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1258 clang::io::Emit16(Out, KeyLen);
1259 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1260 for (const ObjCMethodList *Method = &Methods.first; Method;
1261 Method = Method->Next)
1262 if (Method->Method)
1263 DataLen += 4;
1264 for (const ObjCMethodList *Method = &Methods.second; Method;
1265 Method = Method->Next)
1266 if (Method->Method)
1267 DataLen += 4;
1268 clang::io::Emit16(Out, DataLen);
1269 return std::make_pair(KeyLen, DataLen);
1270 }
1271
Douglas Gregor83941df2009-04-25 17:48:32 +00001272 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1273 uint64_t Start = Out.tell();
1274 assert((Start >> 32) == 0 && "Selector key offset too large");
1275 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001276 unsigned N = Sel.getNumArgs();
1277 clang::io::Emit16(Out, N);
1278 if (N == 0)
1279 N = 1;
1280 for (unsigned I = 0; I != N; ++I)
1281 clang::io::Emit32(Out,
1282 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1283 }
1284
1285 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001286 data_type_ref Methods, unsigned DataLen) {
1287 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001288 unsigned NumInstanceMethods = 0;
1289 for (const ObjCMethodList *Method = &Methods.first; Method;
1290 Method = Method->Next)
1291 if (Method->Method)
1292 ++NumInstanceMethods;
1293
1294 unsigned NumFactoryMethods = 0;
1295 for (const ObjCMethodList *Method = &Methods.second; Method;
1296 Method = Method->Next)
1297 if (Method->Method)
1298 ++NumFactoryMethods;
1299
1300 clang::io::Emit16(Out, NumInstanceMethods);
1301 clang::io::Emit16(Out, NumFactoryMethods);
1302 for (const ObjCMethodList *Method = &Methods.first; Method;
1303 Method = Method->Next)
1304 if (Method->Method)
1305 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001306 for (const ObjCMethodList *Method = &Methods.second; Method;
1307 Method = Method->Next)
1308 if (Method->Method)
1309 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001310
1311 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001312 }
1313};
1314} // end anonymous namespace
1315
1316/// \brief Write the method pool into the PCH file.
1317///
1318/// The method pool contains both instance and factory methods, stored
1319/// in an on-disk hash table indexed by the selector.
1320void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1321 using namespace llvm;
1322
1323 // Create and write out the blob that contains the instance and
1324 // factor method pools.
1325 bool Empty = true;
1326 {
1327 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1328
1329 // Create the on-disk hash table representation. Start by
1330 // iterating through the instance method pool.
1331 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001332 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001333 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1334 Instance = SemaRef.InstanceMethodPool.begin(),
1335 InstanceEnd = SemaRef.InstanceMethodPool.end();
1336 Instance != InstanceEnd; ++Instance) {
1337 // Check whether there is a factory method with the same
1338 // selector.
1339 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1340 = SemaRef.FactoryMethodPool.find(Instance->first);
1341
1342 if (Factory == SemaRef.FactoryMethodPool.end())
1343 Generator.insert(Instance->first,
1344 std::make_pair(Instance->second,
1345 ObjCMethodList()));
1346 else
1347 Generator.insert(Instance->first,
1348 std::make_pair(Instance->second, Factory->second));
1349
Douglas Gregor83941df2009-04-25 17:48:32 +00001350 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001351 Empty = false;
1352 }
1353
1354 // Now iterate through the factory method pool, to pick up any
1355 // selectors that weren't already in the instance method pool.
1356 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1357 Factory = SemaRef.FactoryMethodPool.begin(),
1358 FactoryEnd = SemaRef.FactoryMethodPool.end();
1359 Factory != FactoryEnd; ++Factory) {
1360 // Check whether there is an instance method with the same
1361 // selector. If so, there is no work to do here.
1362 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1363 = SemaRef.InstanceMethodPool.find(Factory->first);
1364
Douglas Gregor83941df2009-04-25 17:48:32 +00001365 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001366 Generator.insert(Factory->first,
1367 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001368 ++NumSelectorsInMethodPool;
1369 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001370
1371 Empty = false;
1372 }
1373
Douglas Gregor83941df2009-04-25 17:48:32 +00001374 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001375 return;
1376
1377 // Create the on-disk hash table in a buffer.
1378 llvm::SmallVector<char, 4096> MethodPool;
1379 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001380 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001381 {
1382 PCHMethodPoolTrait Trait(*this);
1383 llvm::raw_svector_ostream Out(MethodPool);
1384 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001385 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001386 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001387
1388 // For every selector that we have seen but which was not
1389 // written into the hash table, write the selector itself and
1390 // record it's offset.
1391 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1392 if (SelectorOffsets[I] == 0)
1393 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001394 }
1395
1396 // Create a blob abbreviation
1397 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1398 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001400 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1402 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1403
Douglas Gregor83941df2009-04-25 17:48:32 +00001404 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001405 RecordData Record;
1406 Record.push_back(pch::METHOD_POOL);
1407 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001408 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001409 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1410 &MethodPool.front(),
1411 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001412
1413 // Create a blob abbreviation for the selector table offsets.
1414 Abbrev = new BitCodeAbbrev();
1415 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1416 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1417 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1418 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1419
1420 // Write the selector offsets table.
1421 Record.clear();
1422 Record.push_back(pch::SELECTOR_OFFSETS);
1423 Record.push_back(SelectorOffsets.size());
1424 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1425 (const char *)&SelectorOffsets.front(),
1426 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001427 }
1428}
1429
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001430//===----------------------------------------------------------------------===//
1431// Identifier Table Serialization
1432//===----------------------------------------------------------------------===//
1433
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001434namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001435class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1436 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001437 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001438
Douglas Gregora92193e2009-04-28 21:18:29 +00001439 /// \brief Determines whether this is an "interesting" identifier
1440 /// that needs a full IdentifierInfo structure written into the hash
1441 /// table.
1442 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1443 return II->isPoisoned() ||
1444 II->isExtensionToken() ||
1445 II->hasMacroDefinition() ||
1446 II->getObjCOrBuiltinID() ||
1447 II->getFETokenInfo<void>();
1448 }
1449
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001450public:
1451 typedef const IdentifierInfo* key_type;
1452 typedef key_type key_type_ref;
1453
1454 typedef pch::IdentID data_type;
1455 typedef data_type data_type_ref;
1456
Douglas Gregor37e26842009-04-21 23:56:24 +00001457 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1458 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001459
1460 static unsigned ComputeHash(const IdentifierInfo* II) {
1461 return clang::BernsteinHash(II->getName());
1462 }
1463
Douglas Gregor37e26842009-04-21 23:56:24 +00001464 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001465 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1466 pch::IdentID ID) {
1467 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001468 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1469 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001470 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001471 if (II->hasMacroDefinition() &&
1472 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001473 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001474 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1475 DEnd = IdentifierResolver::end();
1476 D != DEnd; ++D)
1477 DataLen += sizeof(pch::DeclID);
1478 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001479 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001480 // We emit the key length after the data length so that every
1481 // string is preceded by a 16-bit length. This matches the PTH
1482 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001483 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001484 return std::make_pair(KeyLen, DataLen);
1485 }
1486
1487 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1488 unsigned KeyLen) {
1489 // Record the location of the key data. This is used when generating
1490 // the mapping from persistent IDs to strings.
1491 Writer.SetIdentifierOffset(II, Out.tell());
1492 Out.write(II->getName(), KeyLen);
1493 }
1494
1495 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1496 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001497 if (!isInterestingIdentifier(II)) {
1498 clang::io::Emit32(Out, ID << 1);
1499 return;
1500 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001501
Douglas Gregora92193e2009-04-28 21:18:29 +00001502 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001503 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001504 bool hasMacroDefinition =
1505 II->hasMacroDefinition() &&
1506 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001507 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001508 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001509 Bits = (Bits << 1) | II->isExtensionToken();
1510 Bits = (Bits << 1) | II->isPoisoned();
1511 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001512 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001513
Douglas Gregor37e26842009-04-21 23:56:24 +00001514 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001515 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001516
Douglas Gregor668c1a42009-04-21 22:25:48 +00001517 // Emit the declaration IDs in reverse order, because the
1518 // IdentifierResolver provides the declarations as they would be
1519 // visible (e.g., the function "stat" would come before the struct
1520 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1521 // adds declarations to the end of the list (so we need to see the
1522 // struct "status" before the function "status").
1523 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1524 IdentifierResolver::end());
1525 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1526 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001527 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001528 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001529 }
1530};
1531} // end anonymous namespace
1532
Douglas Gregorafaf3082009-04-11 00:14:32 +00001533/// \brief Write the identifier table into the PCH file.
1534///
1535/// The identifier table consists of a blob containing string data
1536/// (the actual identifiers themselves) and a separate "offsets" index
1537/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001538void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001539 using namespace llvm;
1540
1541 // Create and write out the blob that contains the identifier
1542 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001543 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001544 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1545
Douglas Gregor92b059e2009-04-28 20:33:11 +00001546 // Look for any identifiers that were named while processing the
1547 // headers, but are otherwise not needed. We add these to the hash
1548 // table to enable checking of the predefines buffer in the case
1549 // where the user adds new macro definitions when building the PCH
1550 // file.
1551 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1552 IDEnd = PP.getIdentifierTable().end();
1553 ID != IDEnd; ++ID)
1554 getIdentifierRef(ID->second);
1555
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001556 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001557 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001558 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1559 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1560 ID != IDEnd; ++ID) {
1561 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001562 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001563 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001564
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001565 // Create the on-disk hash table in a buffer.
1566 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001567 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001568 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001569 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001570 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001571 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001572 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001573 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001574 }
1575
1576 // Create a blob abbreviation
1577 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1578 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001579 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001580 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001581 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001582
1583 // Write the identifier table
1584 RecordData Record;
1585 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001586 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001587 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1588 &IdentifierTable.front(),
1589 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001590 }
1591
1592 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001593 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1594 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1595 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1596 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1597 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1598
1599 RecordData Record;
1600 Record.push_back(pch::IDENTIFIER_OFFSET);
1601 Record.push_back(IdentifierOffsets.size());
1602 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1603 (const char *)&IdentifierOffsets.front(),
1604 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001605}
1606
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001607//===----------------------------------------------------------------------===//
1608// General Serialization Routines
1609//===----------------------------------------------------------------------===//
1610
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001611/// \brief Write a record containing the given attributes.
1612void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1613 RecordData Record;
1614 for (; Attr; Attr = Attr->getNext()) {
1615 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1616 Record.push_back(Attr->isInherited());
1617 switch (Attr->getKind()) {
1618 case Attr::Alias:
1619 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1620 break;
1621
1622 case Attr::Aligned:
1623 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1624 break;
1625
1626 case Attr::AlwaysInline:
1627 break;
1628
1629 case Attr::AnalyzerNoReturn:
1630 break;
1631
1632 case Attr::Annotate:
1633 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1634 break;
1635
1636 case Attr::AsmLabel:
1637 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1638 break;
1639
1640 case Attr::Blocks:
1641 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1642 break;
1643
1644 case Attr::Cleanup:
1645 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1646 break;
1647
1648 case Attr::Const:
1649 break;
1650
1651 case Attr::Constructor:
1652 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1653 break;
1654
1655 case Attr::DLLExport:
1656 case Attr::DLLImport:
1657 case Attr::Deprecated:
1658 break;
1659
1660 case Attr::Destructor:
1661 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1662 break;
1663
1664 case Attr::FastCall:
1665 break;
1666
1667 case Attr::Format: {
1668 const FormatAttr *Format = cast<FormatAttr>(Attr);
1669 AddString(Format->getType(), Record);
1670 Record.push_back(Format->getFormatIdx());
1671 Record.push_back(Format->getFirstArg());
1672 break;
1673 }
1674
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001675 case Attr::FormatArg: {
1676 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1677 Record.push_back(Format->getFormatIdx());
1678 break;
1679 }
1680
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001681 case Attr::Sentinel : {
1682 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1683 Record.push_back(Sentinel->getSentinel());
1684 Record.push_back(Sentinel->getNullPos());
1685 break;
1686 }
1687
Chris Lattnercf2a7212009-04-20 19:12:28 +00001688 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001689 case Attr::IBOutletKind:
1690 case Attr::NoReturn:
1691 case Attr::NoThrow:
1692 case Attr::Nodebug:
1693 case Attr::Noinline:
1694 break;
1695
1696 case Attr::NonNull: {
1697 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1698 Record.push_back(NonNull->size());
1699 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1700 break;
1701 }
1702
1703 case Attr::ObjCException:
1704 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001705 case Attr::CFReturnsRetained:
1706 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001707 case Attr::Overloadable:
1708 break;
1709
1710 case Attr::Packed:
1711 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1712 break;
1713
1714 case Attr::Pure:
1715 break;
1716
1717 case Attr::Regparm:
1718 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1719 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001720
1721 case Attr::ReqdWorkGroupSize:
1722 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1723 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1724 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1725 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001726
1727 case Attr::Section:
1728 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1729 break;
1730
1731 case Attr::StdCall:
1732 case Attr::TransparentUnion:
1733 case Attr::Unavailable:
1734 case Attr::Unused:
1735 case Attr::Used:
1736 break;
1737
1738 case Attr::Visibility:
1739 // FIXME: stable encoding
1740 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1741 break;
1742
1743 case Attr::WarnUnusedResult:
1744 case Attr::Weak:
1745 case Attr::WeakImport:
1746 break;
1747 }
1748 }
1749
Douglas Gregorc9490c02009-04-16 22:23:12 +00001750 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001751}
1752
1753void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1754 Record.push_back(Str.size());
1755 Record.insert(Record.end(), Str.begin(), Str.end());
1756}
1757
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001758/// \brief Note that the identifier II occurs at the given offset
1759/// within the identifier table.
1760void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001761 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001762}
1763
Douglas Gregor83941df2009-04-25 17:48:32 +00001764/// \brief Note that the selector Sel occurs at the given offset
1765/// within the method pool/selector table.
1766void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1767 unsigned ID = SelectorIDs[Sel];
1768 assert(ID && "Unknown selector");
1769 SelectorOffsets[ID - 1] = Offset;
1770}
1771
Douglas Gregorc9490c02009-04-16 22:23:12 +00001772PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001773 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001774 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1775 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001776
Douglas Gregore650c8c2009-07-07 00:12:59 +00001777void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1778 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001779 using namespace llvm;
1780
Douglas Gregore7785042009-04-20 15:53:59 +00001781 ASTContext &Context = SemaRef.Context;
1782 Preprocessor &PP = SemaRef.PP;
1783
Douglas Gregor2cf26342009-04-09 22:27:44 +00001784 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001785 Stream.Emit((unsigned)'C', 8);
1786 Stream.Emit((unsigned)'P', 8);
1787 Stream.Emit((unsigned)'C', 8);
1788 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001789
1790 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791
1792 // The translation unit is the first declaration we'll emit.
1793 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1794 DeclsToEmit.push(Context.getTranslationUnitDecl());
1795
Douglas Gregor2deaea32009-04-22 18:49:13 +00001796 // Make sure that we emit IdentifierInfos (and any attached
1797 // declarations) for builtins.
1798 {
1799 IdentifierTable &Table = PP.getIdentifierTable();
1800 llvm::SmallVector<const char *, 32> BuiltinNames;
1801 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1802 Context.getLangOptions().NoBuiltin);
1803 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1804 getIdentifierRef(&Table.get(BuiltinNames[I]));
1805 }
1806
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001807 // Build a record containing all of the tentative definitions in
1808 // this header file. Generally, this record will be empty.
1809 RecordData TentativeDefinitions;
1810 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1811 TD = SemaRef.TentativeDefinitions.begin(),
1812 TDEnd = SemaRef.TentativeDefinitions.end();
1813 TD != TDEnd; ++TD)
1814 AddDeclRef(TD->second, TentativeDefinitions);
1815
Douglas Gregor14c22f22009-04-22 22:18:58 +00001816 // Build a record containing all of the locally-scoped external
1817 // declarations in this header file. Generally, this record will be
1818 // empty.
1819 RecordData LocallyScopedExternalDecls;
1820 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1821 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1822 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1823 TD != TDEnd; ++TD)
1824 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1825
Douglas Gregorb81c1702009-04-27 20:06:05 +00001826 // Build a record containing all of the ext_vector declarations.
1827 RecordData ExtVectorDecls;
1828 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1829 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1830
1831 // Build a record containing all of the Objective-C category
1832 // implementations.
1833 RecordData ObjCCategoryImpls;
1834 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1835 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1836
Douglas Gregor2cf26342009-04-09 22:27:44 +00001837 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001838 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001839 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001840 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001841 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001842 if (StatCalls && !isysroot)
1843 WriteStatCache(*StatCalls, isysroot);
1844 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001845 WritePreprocessor(PP);
Douglas Gregor2e222532009-07-02 17:08:52 +00001846 WriteComments(Context);
1847
Douglas Gregor366809a2009-04-26 03:49:13 +00001848 // Keep writing types and declarations until all types and
1849 // declarations have been written.
1850 do {
1851 if (!DeclsToEmit.empty())
1852 WriteDeclsBlock(Context);
1853 if (!TypesToEmit.empty())
1854 WriteTypesBlock(Context);
1855 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1856
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001857 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001858 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001859
1860 // Write the type offsets array
1861 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1862 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1864 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1865 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1866 Record.clear();
1867 Record.push_back(pch::TYPE_OFFSET);
1868 Record.push_back(TypeOffsets.size());
1869 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1870 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001871 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001872
1873 // Write the declaration offsets array
1874 Abbrev = new BitCodeAbbrev();
1875 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1878 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1879 Record.clear();
1880 Record.push_back(pch::DECL_OFFSET);
1881 Record.push_back(DeclOffsets.size());
1882 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1883 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001884 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001885
1886 // Write the record of special types.
1887 Record.clear();
1888 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001889 AddTypeRef(Context.getObjCIdType(), Record);
1890 AddTypeRef(Context.getObjCSelType(), Record);
1891 AddTypeRef(Context.getObjCProtoType(), Record);
1892 AddTypeRef(Context.getObjCClassType(), Record);
1893 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1894 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001895 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1896
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001897 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001898 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001899 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001900
1901 // Write the record containing tentative definitions.
1902 if (!TentativeDefinitions.empty())
1903 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001904
1905 // Write the record containing locally-scoped external definitions.
1906 if (!LocallyScopedExternalDecls.empty())
1907 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1908 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001909
1910 // Write the record containing ext_vector type names.
1911 if (!ExtVectorDecls.empty())
1912 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1913
1914 // Write the record containing Objective-C category implementations.
1915 if (!ObjCCategoryImpls.empty())
1916 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001917
1918 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001919 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001920 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001921 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001922 Record.push_back(NumLexicalDeclContexts);
1923 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001924 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001925 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001926}
1927
1928void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1929 Record.push_back(Loc.getRawEncoding());
1930}
1931
1932void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1933 Record.push_back(Value.getBitWidth());
1934 unsigned N = Value.getNumWords();
1935 const uint64_t* Words = Value.getRawData();
1936 for (unsigned I = 0; I != N; ++I)
1937 Record.push_back(Words[I]);
1938}
1939
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001940void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1941 Record.push_back(Value.isUnsigned());
1942 AddAPInt(Value, Record);
1943}
1944
Douglas Gregor17fc2232009-04-14 21:55:33 +00001945void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1946 AddAPInt(Value.bitcastToAPInt(), Record);
1947}
1948
Douglas Gregor2cf26342009-04-09 22:27:44 +00001949void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001950 Record.push_back(getIdentifierRef(II));
1951}
1952
1953pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1954 if (II == 0)
1955 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001956
1957 pch::IdentID &ID = IdentifierIDs[II];
1958 if (ID == 0)
1959 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001960 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961}
1962
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001963void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1964 if (SelRef.getAsOpaquePtr() == 0) {
1965 Record.push_back(0);
1966 return;
1967 }
1968
1969 pch::SelectorID &SID = SelectorIDs[SelRef];
1970 if (SID == 0) {
1971 SID = SelectorIDs.size();
1972 SelVector.push_back(SelRef);
1973 }
1974 Record.push_back(SID);
1975}
1976
Douglas Gregor2cf26342009-04-09 22:27:44 +00001977void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1978 if (T.isNull()) {
1979 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1980 return;
1981 }
1982
1983 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001984 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001985 switch (BT->getKind()) {
1986 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1987 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1988 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1989 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1990 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1991 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1992 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1993 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001994 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001995 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1996 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1997 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1998 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1999 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2000 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2001 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002002 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002003 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2004 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2005 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002006 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002007 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2008 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002009 case BuiltinType::UndeducedAuto:
2010 assert(0 && "Should not see undeduced auto here");
2011 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002012 }
2013
2014 Record.push_back((ID << 3) | T.getCVRQualifiers());
2015 return;
2016 }
2017
Douglas Gregor8038d512009-04-10 17:25:41 +00002018 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00002019 if (ID == 0) {
2020 // We haven't seen this type before. Assign it a new ID and put it
2021 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00002023 TypesToEmit.push(T.getTypePtr());
2024 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002025
2026 // Encode the type qualifiers in the type reference.
2027 Record.push_back((ID << 3) | T.getCVRQualifiers());
2028}
2029
2030void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2031 if (D == 0) {
2032 Record.push_back(0);
2033 return;
2034 }
2035
Douglas Gregor8038d512009-04-10 17:25:41 +00002036 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002037 if (ID == 0) {
2038 // We haven't seen this declaration before. Give it a new ID and
2039 // enqueue it in the list of declarations to emit.
2040 ID = DeclIDs.size();
2041 DeclsToEmit.push(const_cast<Decl *>(D));
2042 }
2043
2044 Record.push_back(ID);
2045}
2046
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002047pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2048 if (D == 0)
2049 return 0;
2050
2051 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2052 return DeclIDs[D];
2053}
2054
Douglas Gregor2cf26342009-04-09 22:27:44 +00002055void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002056 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002057 Record.push_back(Name.getNameKind());
2058 switch (Name.getNameKind()) {
2059 case DeclarationName::Identifier:
2060 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2061 break;
2062
2063 case DeclarationName::ObjCZeroArgSelector:
2064 case DeclarationName::ObjCOneArgSelector:
2065 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002066 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002067 break;
2068
2069 case DeclarationName::CXXConstructorName:
2070 case DeclarationName::CXXDestructorName:
2071 case DeclarationName::CXXConversionFunctionName:
2072 AddTypeRef(Name.getCXXNameType(), Record);
2073 break;
2074
2075 case DeclarationName::CXXOperatorName:
2076 Record.push_back(Name.getCXXOverloadedOperator());
2077 break;
2078
2079 case DeclarationName::CXXUsingDirective:
2080 // No extra data to emit
2081 break;
2082 }
2083}
Douglas Gregor0b748912009-04-14 21:18:50 +00002084