blob: 69247d3e859e39ce9921d780e2c6c484f7211cf1 [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);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000242 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000243 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
244 E = T->qual_end(); I != E; ++I)
245 Writer.AddDeclRef(*I, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +0000246 Code = pch::TYPE_OBJC_INTERFACE;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000247}
248
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000249void
250PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Steve Naroff14108da2009-07-10 23:34:53 +0000251 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000252 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000253 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000254 E = T->qual_end(); I != E; ++I)
255 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000256 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000257}
258
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000259//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000260// PCHWriter Implementation
261//===----------------------------------------------------------------------===//
262
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000263static void EmitBlockID(unsigned ID, const char *Name,
264 llvm::BitstreamWriter &Stream,
265 PCHWriter::RecordData &Record) {
266 Record.clear();
267 Record.push_back(ID);
268 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
269
270 // Emit the block name if present.
271 if (Name == 0 || Name[0] == 0) return;
272 Record.clear();
273 while (*Name)
274 Record.push_back(*Name++);
275 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
276}
277
278static void EmitRecordID(unsigned ID, const char *Name,
279 llvm::BitstreamWriter &Stream,
280 PCHWriter::RecordData &Record) {
281 Record.clear();
282 Record.push_back(ID);
283 while (*Name)
284 Record.push_back(*Name++);
285 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000286}
287
288static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
289 PCHWriter::RecordData &Record) {
290#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
291 RECORD(STMT_STOP);
292 RECORD(STMT_NULL_PTR);
293 RECORD(STMT_NULL);
294 RECORD(STMT_COMPOUND);
295 RECORD(STMT_CASE);
296 RECORD(STMT_DEFAULT);
297 RECORD(STMT_LABEL);
298 RECORD(STMT_IF);
299 RECORD(STMT_SWITCH);
300 RECORD(STMT_WHILE);
301 RECORD(STMT_DO);
302 RECORD(STMT_FOR);
303 RECORD(STMT_GOTO);
304 RECORD(STMT_INDIRECT_GOTO);
305 RECORD(STMT_CONTINUE);
306 RECORD(STMT_BREAK);
307 RECORD(STMT_RETURN);
308 RECORD(STMT_DECL);
309 RECORD(STMT_ASM);
310 RECORD(EXPR_PREDEFINED);
311 RECORD(EXPR_DECL_REF);
312 RECORD(EXPR_INTEGER_LITERAL);
313 RECORD(EXPR_FLOATING_LITERAL);
314 RECORD(EXPR_IMAGINARY_LITERAL);
315 RECORD(EXPR_STRING_LITERAL);
316 RECORD(EXPR_CHARACTER_LITERAL);
317 RECORD(EXPR_PAREN);
318 RECORD(EXPR_UNARY_OPERATOR);
319 RECORD(EXPR_SIZEOF_ALIGN_OF);
320 RECORD(EXPR_ARRAY_SUBSCRIPT);
321 RECORD(EXPR_CALL);
322 RECORD(EXPR_MEMBER);
323 RECORD(EXPR_BINARY_OPERATOR);
324 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
325 RECORD(EXPR_CONDITIONAL_OPERATOR);
326 RECORD(EXPR_IMPLICIT_CAST);
327 RECORD(EXPR_CSTYLE_CAST);
328 RECORD(EXPR_COMPOUND_LITERAL);
329 RECORD(EXPR_EXT_VECTOR_ELEMENT);
330 RECORD(EXPR_INIT_LIST);
331 RECORD(EXPR_DESIGNATED_INIT);
332 RECORD(EXPR_IMPLICIT_VALUE_INIT);
333 RECORD(EXPR_VA_ARG);
334 RECORD(EXPR_ADDR_LABEL);
335 RECORD(EXPR_STMT);
336 RECORD(EXPR_TYPES_COMPATIBLE);
337 RECORD(EXPR_CHOOSE);
338 RECORD(EXPR_GNU_NULL);
339 RECORD(EXPR_SHUFFLE_VECTOR);
340 RECORD(EXPR_BLOCK);
341 RECORD(EXPR_BLOCK_DECL_REF);
342 RECORD(EXPR_OBJC_STRING_LITERAL);
343 RECORD(EXPR_OBJC_ENCODE);
344 RECORD(EXPR_OBJC_SELECTOR_EXPR);
345 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
346 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
347 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
348 RECORD(EXPR_OBJC_KVC_REF_EXPR);
349 RECORD(EXPR_OBJC_MESSAGE_EXPR);
350 RECORD(EXPR_OBJC_SUPER_EXPR);
351 RECORD(STMT_OBJC_FOR_COLLECTION);
352 RECORD(STMT_OBJC_CATCH);
353 RECORD(STMT_OBJC_FINALLY);
354 RECORD(STMT_OBJC_AT_TRY);
355 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
356 RECORD(STMT_OBJC_AT_THROW);
357#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000358}
359
360void PCHWriter::WriteBlockInfoBlock() {
361 RecordData Record;
362 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
363
Chris Lattner2f4efd12009-04-27 00:40:25 +0000364#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000365#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
366
367 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000368 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000369 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000370 RECORD(TYPE_OFFSET);
371 RECORD(DECL_OFFSET);
372 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000373 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000374 RECORD(IDENTIFIER_OFFSET);
375 RECORD(IDENTIFIER_TABLE);
376 RECORD(EXTERNAL_DEFINITIONS);
377 RECORD(SPECIAL_TYPES);
378 RECORD(STATISTICS);
379 RECORD(TENTATIVE_DEFINITIONS);
380 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
381 RECORD(SELECTOR_OFFSETS);
382 RECORD(METHOD_POOL);
383 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000384 RECORD(SOURCE_LOCATION_OFFSETS);
385 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000386 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000387 RECORD(EXT_VECTOR_DECLS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 RECORD(COMMENT_RANGES);
389
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000390 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000391 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000392 RECORD(SM_SLOC_FILE_ENTRY);
393 RECORD(SM_SLOC_BUFFER_ENTRY);
394 RECORD(SM_SLOC_BUFFER_BLOB);
395 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
396 RECORD(SM_LINE_TABLE);
397 RECORD(SM_HEADER_FILE_INFO);
398
399 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000400 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000401 RECORD(PP_MACRO_OBJECT_LIKE);
402 RECORD(PP_MACRO_FUNCTION_LIKE);
403 RECORD(PP_TOKEN);
404
405 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000406 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000407 RECORD(TYPE_EXT_QUAL);
408 RECORD(TYPE_FIXED_WIDTH_INT);
409 RECORD(TYPE_COMPLEX);
410 RECORD(TYPE_POINTER);
411 RECORD(TYPE_BLOCK_POINTER);
412 RECORD(TYPE_LVALUE_REFERENCE);
413 RECORD(TYPE_RVALUE_REFERENCE);
414 RECORD(TYPE_MEMBER_POINTER);
415 RECORD(TYPE_CONSTANT_ARRAY);
416 RECORD(TYPE_INCOMPLETE_ARRAY);
417 RECORD(TYPE_VARIABLE_ARRAY);
418 RECORD(TYPE_VECTOR);
419 RECORD(TYPE_EXT_VECTOR);
420 RECORD(TYPE_FUNCTION_PROTO);
421 RECORD(TYPE_FUNCTION_NO_PROTO);
422 RECORD(TYPE_TYPEDEF);
423 RECORD(TYPE_TYPEOF_EXPR);
424 RECORD(TYPE_TYPEOF);
425 RECORD(TYPE_RECORD);
426 RECORD(TYPE_ENUM);
427 RECORD(TYPE_OBJC_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000428 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000429 // Statements and Exprs can occur in the Types block.
430 AddStmtsExprs(Stream, Record);
431
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000432 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000433 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000434 RECORD(DECL_ATTR);
435 RECORD(DECL_TRANSLATION_UNIT);
436 RECORD(DECL_TYPEDEF);
437 RECORD(DECL_ENUM);
438 RECORD(DECL_RECORD);
439 RECORD(DECL_ENUM_CONSTANT);
440 RECORD(DECL_FUNCTION);
441 RECORD(DECL_OBJC_METHOD);
442 RECORD(DECL_OBJC_INTERFACE);
443 RECORD(DECL_OBJC_PROTOCOL);
444 RECORD(DECL_OBJC_IVAR);
445 RECORD(DECL_OBJC_AT_DEFS_FIELD);
446 RECORD(DECL_OBJC_CLASS);
447 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
448 RECORD(DECL_OBJC_CATEGORY);
449 RECORD(DECL_OBJC_CATEGORY_IMPL);
450 RECORD(DECL_OBJC_IMPLEMENTATION);
451 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
452 RECORD(DECL_OBJC_PROPERTY);
453 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000454 RECORD(DECL_FIELD);
455 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000456 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000457 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000458 RECORD(DECL_ORIGINAL_PARM_VAR);
459 RECORD(DECL_FILE_SCOPE_ASM);
460 RECORD(DECL_BLOCK);
461 RECORD(DECL_CONTEXT_LEXICAL);
462 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000463 // Statements and Exprs can occur in the Decls block.
464 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000465#undef RECORD
466#undef BLOCK
467 Stream.ExitBlock();
468}
469
Douglas Gregore650c8c2009-07-07 00:12:59 +0000470/// \brief Adjusts the given filename to only write out the portion of the
471/// filename that is not part of the system root directory.
472///
473/// \param Filename the file name to adjust.
474///
475/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
476/// the returned filename will be adjusted by this system root.
477///
478/// \returns either the original filename (if it needs no adjustment) or the
479/// adjusted filename (which points into the @p Filename parameter).
480static const char *
481adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
482 assert(Filename && "No file name to adjust?");
483
484 if (!isysroot)
485 return Filename;
486
487 // Verify that the filename and the system root have the same prefix.
488 unsigned Pos = 0;
489 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
490 if (Filename[Pos] != isysroot[Pos])
491 return Filename; // Prefixes don't match.
492
493 // We hit the end of the filename before we hit the end of the system root.
494 if (!Filename[Pos])
495 return Filename;
496
497 // If the file name has a '/' at the current position, skip over the '/'.
498 // We distinguish sysroot-based includes from absolute includes by the
499 // absence of '/' at the beginning of sysroot-based includes.
500 if (Filename[Pos] == '/')
501 ++Pos;
502
503 return Filename + Pos;
504}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000505
Douglas Gregorab41e632009-04-27 22:23:34 +0000506/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000507void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000508 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000509
Douglas Gregore650c8c2009-07-07 00:12:59 +0000510 // Metadata
511 const TargetInfo &Target = Context.Target;
512 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
513 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
514 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
515 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
516 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
517 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
518 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
519 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
520 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
521
522 RecordData Record;
523 Record.push_back(pch::METADATA);
524 Record.push_back(pch::VERSION_MAJOR);
525 Record.push_back(pch::VERSION_MINOR);
526 Record.push_back(CLANG_VERSION_MAJOR);
527 Record.push_back(CLANG_VERSION_MINOR);
528 Record.push_back(isysroot != 0);
529 const char *Triple = Target.getTargetTriple();
530 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
531
Douglas Gregorb64c1932009-05-12 01:31:05 +0000532 // Original file name
533 SourceManager &SM = Context.getSourceManager();
534 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
535 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
536 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
537 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
538 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
539
540 llvm::sys::Path MainFilePath(MainFile->getName());
541 std::string MainFileName;
542
543 if (!MainFilePath.isAbsolute()) {
544 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
545 P.appendComponent(MainFilePath.toString());
546 MainFileName = P.toString();
547 } else {
548 MainFileName = MainFilePath.toString();
549 }
550
Douglas Gregore650c8c2009-07-07 00:12:59 +0000551 const char *MainFileNameStr = MainFileName.c_str();
552 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
553 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000554 RecordData Record;
555 Record.push_back(pch::ORIGINAL_FILE_NAME);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000556 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr,
557 strlen(MainFileNameStr));
Douglas Gregorb64c1932009-05-12 01:31:05 +0000558 }
Douglas Gregor2bec0412009-04-10 21:16:55 +0000559}
560
561/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000562void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
563 RecordData Record;
564 Record.push_back(LangOpts.Trigraphs);
565 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
566 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
567 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
568 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
569 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
570 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
571 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
572 Record.push_back(LangOpts.C99); // C99 Support
573 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
574 Record.push_back(LangOpts.CPlusPlus); // C++ Support
575 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000576 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
577
578 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
579 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
580 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
581
582 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000583 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
584 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000585 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000586 Record.push_back(LangOpts.Exceptions); // Support exception handling.
587
588 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
589 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
590 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
591
Chris Lattnerea5ce472009-04-27 07:35:58 +0000592 // Whether static initializers are protected by locks.
593 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000594 Record.push_back(LangOpts.Blocks); // block extension to C
595 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
596 // they are unused.
597 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
598 // (modulo the platform support).
599
600 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
601 // signed integer arithmetic overflows.
602
603 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
604 // may be ripped out at any time.
605
606 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
607 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
608 // defined.
609 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
610 // opposed to __DYNAMIC__).
611 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
612
613 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
614 // used (instead of C99 semantics).
615 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000616 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
617 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000618 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
619 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000620 Record.push_back(LangOpts.getGCMode());
621 Record.push_back(LangOpts.getVisibilityMode());
622 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000623 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000624 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000625}
626
Douglas Gregor14f79002009-04-10 03:52:48 +0000627//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000628// stat cache Serialization
629//===----------------------------------------------------------------------===//
630
631namespace {
632// Trait used for the on-disk hash table of stat cache results.
633class VISIBILITY_HIDDEN PCHStatCacheTrait {
634public:
635 typedef const char * key_type;
636 typedef key_type key_type_ref;
637
638 typedef std::pair<int, struct stat> data_type;
639 typedef const data_type& data_type_ref;
640
641 static unsigned ComputeHash(const char *path) {
642 return BernsteinHash(path);
643 }
644
645 std::pair<unsigned,unsigned>
646 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
647 data_type_ref Data) {
648 unsigned StrLen = strlen(path);
649 clang::io::Emit16(Out, StrLen);
650 unsigned DataLen = 1; // result value
651 if (Data.first == 0)
652 DataLen += 4 + 4 + 2 + 8 + 8;
653 clang::io::Emit8(Out, DataLen);
654 return std::make_pair(StrLen + 1, DataLen);
655 }
656
657 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
658 Out.write(path, KeyLen);
659 }
660
661 void EmitData(llvm::raw_ostream& Out, key_type_ref,
662 data_type_ref Data, unsigned DataLen) {
663 using namespace clang::io;
664 uint64_t Start = Out.tell(); (void)Start;
665
666 // Result of stat()
667 Emit8(Out, Data.first? 1 : 0);
668
669 if (Data.first == 0) {
670 Emit32(Out, (uint32_t) Data.second.st_ino);
671 Emit32(Out, (uint32_t) Data.second.st_dev);
672 Emit16(Out, (uint16_t) Data.second.st_mode);
673 Emit64(Out, (uint64_t) Data.second.st_mtime);
674 Emit64(Out, (uint64_t) Data.second.st_size);
675 }
676
677 assert(Out.tell() - Start == DataLen && "Wrong data length");
678 }
679};
680} // end anonymous namespace
681
682/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000683void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
684 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000685 // Build the on-disk hash table containing information about every
686 // stat() call.
687 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
688 unsigned NumStatEntries = 0;
689 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
690 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000691 Stat != StatEnd; ++Stat, ++NumStatEntries) {
692 const char *Filename = Stat->first();
693 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
694 Generator.insert(Filename, Stat->second);
695 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000696
697 // Create the on-disk hash table in a buffer.
698 llvm::SmallVector<char, 4096> StatCacheData;
699 uint32_t BucketOffset;
700 {
701 llvm::raw_svector_ostream Out(StatCacheData);
702 // Make sure that no bucket is at offset 0
703 clang::io::Emit32(Out, 0);
704 BucketOffset = Generator.Emit(Out);
705 }
706
707 // Create a blob abbreviation
708 using namespace llvm;
709 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
710 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
714 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
715
716 // Write the stat cache
717 RecordData Record;
718 Record.push_back(pch::STAT_CACHE);
719 Record.push_back(BucketOffset);
720 Record.push_back(NumStatEntries);
721 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
722 &StatCacheData.front(),
723 StatCacheData.size());
724}
725
726//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000727// Source Manager Serialization
728//===----------------------------------------------------------------------===//
729
730/// \brief Create an abbreviation for the SLocEntry that refers to a
731/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000732static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000733 using namespace llvm;
734 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
735 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
737 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
739 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000740 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000741 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000742}
743
744/// \brief Create an abbreviation for the SLocEntry that refers to a
745/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000746static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000747 using namespace llvm;
748 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
749 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000755 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000756}
757
758/// \brief Create an abbreviation for the SLocEntry that refers to a
759/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000760static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000761 using namespace llvm;
762 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
763 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000765 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000766}
767
768/// \brief Create an abbreviation for the SLocEntry that refers to an
769/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000770static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000771 using namespace llvm;
772 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
773 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
774 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
776 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000779 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000780}
781
782/// \brief Writes the block containing the serialized form of the
783/// source manager.
784///
785/// TODO: We should probably use an on-disk hash table (stored in a
786/// blob), indexed based on the file name, so that we only create
787/// entries for files that we actually need. In the common case (no
788/// errors), we probably won't have to create file entries for any of
789/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000790void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000791 const Preprocessor &PP,
792 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000793 RecordData Record;
794
Chris Lattnerf04ad692009-04-10 17:16:57 +0000795 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000796 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000797
798 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000799 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
800 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
801 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
802 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000803
Douglas Gregorbd945002009-04-13 16:31:14 +0000804 // Write the line table.
805 if (SourceMgr.hasLineTable()) {
806 LineTableInfo &LineTable = SourceMgr.getLineTable();
807
808 // Emit the file names
809 Record.push_back(LineTable.getNumFilenames());
810 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
811 // Emit the file name
812 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000813 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000814 unsigned FilenameLen = Filename? strlen(Filename) : 0;
815 Record.push_back(FilenameLen);
816 if (FilenameLen)
817 Record.insert(Record.end(), Filename, Filename + FilenameLen);
818 }
819
820 // Emit the line entries
821 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
822 L != LEnd; ++L) {
823 // Emit the file ID
824 Record.push_back(L->first);
825
826 // Emit the line entries
827 Record.push_back(L->second.size());
828 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
829 LEEnd = L->second.end();
830 LE != LEEnd; ++LE) {
831 Record.push_back(LE->FileOffset);
832 Record.push_back(LE->LineNo);
833 Record.push_back(LE->FilenameID);
834 Record.push_back((unsigned)LE->FileKind);
835 Record.push_back(LE->IncludeOffset);
836 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000837 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000838 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000839 }
840
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000842 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000843 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000844 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
845 E = HS.header_file_end();
846 I != E; ++I) {
847 Record.push_back(I->isImport);
848 Record.push_back(I->DirInfo);
849 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000850 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000851 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
852 Record.clear();
853 }
854
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000855 // Write out the source location entry table. We skip the first
856 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000857 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000858 RecordData PreloadSLocs;
859 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
860 for (SourceManager::sloc_entry_iterator
861 SLoc = SourceMgr.sloc_entry_begin() + 1,
862 SLocEnd = SourceMgr.sloc_entry_end();
863 SLoc != SLocEnd; ++SLoc) {
864 // Record the offset of this source-location entry.
865 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
866
867 // Figure out which record code to use.
868 unsigned Code;
869 if (SLoc->isFile()) {
870 if (SLoc->getFile().getContentCache()->Entry)
871 Code = pch::SM_SLOC_FILE_ENTRY;
872 else
873 Code = pch::SM_SLOC_BUFFER_ENTRY;
874 } else
875 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
876 Record.clear();
877 Record.push_back(Code);
878
879 Record.push_back(SLoc->getOffset());
880 if (SLoc->isFile()) {
881 const SrcMgr::FileInfo &File = SLoc->getFile();
882 Record.push_back(File.getIncludeLoc().getRawEncoding());
883 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
884 Record.push_back(File.hasLineDirectives());
885
886 const SrcMgr::ContentCache *Content = File.getContentCache();
887 if (Content->Entry) {
888 // The source location entry is a file. The blob associated
889 // with this entry is the file name.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000890
891 // Turn the file name into an absolute path, if it isn't already.
892 const char *Filename = Content->Entry->getName();
893 llvm::sys::Path FilePath(Filename, strlen(Filename));
894 std::string FilenameStr;
895 if (!FilePath.isAbsolute()) {
896 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
897 P.appendComponent(FilePath.toString());
898 FilenameStr = P.toString();
899 Filename = FilenameStr.c_str();
900 }
901
902 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
903 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename,
904 strlen(Filename));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000905
906 // FIXME: For now, preload all file source locations, so that
907 // we get the appropriate File entries in the reader. This is
908 // a temporary measure.
909 PreloadSLocs.push_back(SLocEntryOffsets.size());
910 } else {
911 // The source location entry is a buffer. The blob associated
912 // with this entry contains the contents of the buffer.
913
914 // We add one to the size so that we capture the trailing NULL
915 // that is required by llvm::MemoryBuffer::getMemBuffer (on
916 // the reader side).
917 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
918 const char *Name = Buffer->getBufferIdentifier();
919 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
920 Record.clear();
921 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
922 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
923 Buffer->getBufferStart(),
924 Buffer->getBufferSize() + 1);
925
926 if (strcmp(Name, "<built-in>") == 0)
927 PreloadSLocs.push_back(SLocEntryOffsets.size());
928 }
929 } else {
930 // The source location entry is an instantiation.
931 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
932 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
933 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
934 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
935
936 // Compute the token length for this macro expansion.
937 unsigned NextOffset = SourceMgr.getNextOffset();
938 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
939 if (++NextSLoc != SLocEnd)
940 NextOffset = NextSLoc->getOffset();
941 Record.push_back(NextOffset - SLoc->getOffset() - 1);
942 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
943 }
944 }
945
Douglas Gregorc9490c02009-04-16 22:23:12 +0000946 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000947
948 if (SLocEntryOffsets.empty())
949 return;
950
951 // Write the source-location offsets table into the PCH block. This
952 // table is used for lazily loading source-location information.
953 using namespace llvm;
954 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
955 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
956 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
957 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
958 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
959 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
960
961 Record.clear();
962 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
963 Record.push_back(SLocEntryOffsets.size());
964 Record.push_back(SourceMgr.getNextOffset());
965 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
966 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000967 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000968
969 // Write the source location entry preloads array, telling the PCH
970 // reader which source locations entries it should load eagerly.
971 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000972}
973
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000974//===----------------------------------------------------------------------===//
975// Preprocessor Serialization
976//===----------------------------------------------------------------------===//
977
Chris Lattner0b1fb982009-04-10 17:15:23 +0000978/// \brief Writes the block containing the serialized form of the
979/// preprocessor.
980///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000981void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000982 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000983
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000984 // If the preprocessor __COUNTER__ value has been bumped, remember it.
985 if (PP.getCounterValue() != 0) {
986 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000987 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000988 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000989 }
990
991 // Enter the preprocessor block.
992 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000993
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000994 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
995 // FIXME: use diagnostics subsystem for localization etc.
996 if (PP.SawDateOrTime())
997 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
998
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000999 // Loop over all the macro definitions that are live at the end of the file,
1000 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001001 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1002 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001003 // FIXME: This emits macros in hash table order, we should do it in a stable
1004 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001005 MacroInfo *MI = I->second;
1006
1007 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1008 // been redefined by the header (in which case they are not isBuiltinMacro).
1009 if (MI->isBuiltinMacro())
1010 continue;
1011
Douglas Gregor37e26842009-04-21 23:56:24 +00001012 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001013 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001014 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001015 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1016 Record.push_back(MI->isUsed());
1017
1018 unsigned Code;
1019 if (MI->isObjectLike()) {
1020 Code = pch::PP_MACRO_OBJECT_LIKE;
1021 } else {
1022 Code = pch::PP_MACRO_FUNCTION_LIKE;
1023
1024 Record.push_back(MI->isC99Varargs());
1025 Record.push_back(MI->isGNUVarargs());
1026 Record.push_back(MI->getNumArgs());
1027 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1028 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001029 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001030 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001031 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001032 Record.clear();
1033
Chris Lattnerdf961c22009-04-10 18:08:30 +00001034 // Emit the tokens array.
1035 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1036 // Note that we know that the preprocessor does not have any annotation
1037 // tokens in it because they are created by the parser, and thus can't be
1038 // in a macro definition.
1039 const Token &Tok = MI->getReplacementToken(TokNo);
1040
1041 Record.push_back(Tok.getLocation().getRawEncoding());
1042 Record.push_back(Tok.getLength());
1043
Chris Lattnerdf961c22009-04-10 18:08:30 +00001044 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1045 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001046 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001047
1048 // FIXME: Should translate token kind to a stable encoding.
1049 Record.push_back(Tok.getKind());
1050 // FIXME: Should translate token flags to a stable encoding.
1051 Record.push_back(Tok.getFlags());
1052
Douglas Gregorc9490c02009-04-16 22:23:12 +00001053 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001054 Record.clear();
1055 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001056 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001057 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001058 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001059}
1060
Douglas Gregor2e222532009-07-02 17:08:52 +00001061void PCHWriter::WriteComments(ASTContext &Context) {
1062 using namespace llvm;
1063
1064 if (Context.Comments.empty())
1065 return;
1066
1067 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1068 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1069 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1070 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1071
1072 RecordData Record;
1073 Record.push_back(pch::COMMENT_RANGES);
1074 Stream.EmitRecordWithBlob(CommentCode, Record,
1075 (const char*)&Context.Comments[0],
1076 Context.Comments.size() * sizeof(SourceRange));
1077}
1078
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001079//===----------------------------------------------------------------------===//
1080// Type Serialization
1081//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001082
Douglas Gregor2cf26342009-04-09 22:27:44 +00001083/// \brief Write the representation of a type to the PCH stream.
1084void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001085 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001086 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001087 ID = NextTypeID++;
1088
1089 // Record the offset for this type.
1090 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001091 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001092 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1093 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001094 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001095 }
1096
1097 RecordData Record;
1098
1099 // Emit the type's representation.
1100 PCHTypeWriter W(*this, Record);
1101 switch (T->getTypeClass()) {
1102 // For all of the concrete, non-dependent types, call the
1103 // appropriate visitor function.
1104#define TYPE(Class, Base) \
1105 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1106#define ABSTRACT_TYPE(Class, Base)
1107#define DEPENDENT_TYPE(Class, Base)
1108#include "clang/AST/TypeNodes.def"
1109
1110 // For all of the dependent type nodes (which only occur in C++
1111 // templates), produce an error.
1112#define TYPE(Class, Base)
1113#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1114#include "clang/AST/TypeNodes.def"
1115 assert(false && "Cannot serialize dependent type nodes");
1116 break;
1117 }
1118
1119 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001120 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001121
1122 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001123 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001124}
1125
1126/// \brief Write a block containing all of the types.
1127void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001128 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001129 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001130
Douglas Gregor366809a2009-04-26 03:49:13 +00001131 // Emit all of the types that need to be emitted (so far).
1132 while (!TypesToEmit.empty()) {
1133 const Type *T = TypesToEmit.front();
1134 TypesToEmit.pop();
1135 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1136 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001137 }
1138
1139 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001140 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001141}
1142
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001143//===----------------------------------------------------------------------===//
1144// Declaration Serialization
1145//===----------------------------------------------------------------------===//
1146
Douglas Gregor2cf26342009-04-09 22:27:44 +00001147/// \brief Write the block containing all of the declaration IDs
1148/// lexically declared within the given DeclContext.
1149///
1150/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1151/// bistream, or 0 if no block was written.
1152uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1153 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001154 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001155 return 0;
1156
Douglas Gregorc9490c02009-04-16 22:23:12 +00001157 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001158 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001159 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1160 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001161 AddDeclRef(*D, Record);
1162
Douglas Gregor25123082009-04-22 22:34:57 +00001163 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001164 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001165 return Offset;
1166}
1167
1168/// \brief Write the block containing all of the declaration IDs
1169/// visible from the given DeclContext.
1170///
1171/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1172/// bistream, or 0 if no block was written.
1173uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1174 DeclContext *DC) {
1175 if (DC->getPrimaryContext() != DC)
1176 return 0;
1177
Douglas Gregoraff22df2009-04-21 22:32:33 +00001178 // Since there is no name lookup into functions or methods, and we
1179 // perform name lookup for the translation unit via the
1180 // IdentifierInfo chains, don't bother to build a
1181 // visible-declarations table for these entities.
1182 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001183 return 0;
1184
Douglas Gregor2cf26342009-04-09 22:27:44 +00001185 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001186 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001187
1188 // Serialize the contents of the mapping used for lookup. Note that,
1189 // although we have two very different code paths, the serialized
1190 // representation is the same for both cases: a declaration name,
1191 // followed by a size, followed by references to the visible
1192 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001193 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001194 RecordData Record;
1195 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001196 if (!Map)
1197 return 0;
1198
Douglas Gregor2cf26342009-04-09 22:27:44 +00001199 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1200 D != DEnd; ++D) {
1201 AddDeclarationName(D->first, Record);
1202 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1203 Record.push_back(Result.second - Result.first);
1204 for(; Result.first != Result.second; ++Result.first)
1205 AddDeclRef(*Result.first, Record);
1206 }
1207
1208 if (Record.size() == 0)
1209 return 0;
1210
Douglas Gregorc9490c02009-04-16 22:23:12 +00001211 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001212 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001213 return Offset;
1214}
1215
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001216//===----------------------------------------------------------------------===//
1217// Global Method Pool and Selector Serialization
1218//===----------------------------------------------------------------------===//
1219
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001220namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001221// Trait used for the on-disk hash table used in the method pool.
1222class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1223 PCHWriter &Writer;
1224
1225public:
1226 typedef Selector key_type;
1227 typedef key_type key_type_ref;
1228
1229 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1230 typedef const data_type& data_type_ref;
1231
1232 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1233
1234 static unsigned ComputeHash(Selector Sel) {
1235 unsigned N = Sel.getNumArgs();
1236 if (N == 0)
1237 ++N;
1238 unsigned R = 5381;
1239 for (unsigned I = 0; I != N; ++I)
1240 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1241 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1242 return R;
1243 }
1244
1245 std::pair<unsigned,unsigned>
1246 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1247 data_type_ref Methods) {
1248 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1249 clang::io::Emit16(Out, KeyLen);
1250 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1251 for (const ObjCMethodList *Method = &Methods.first; Method;
1252 Method = Method->Next)
1253 if (Method->Method)
1254 DataLen += 4;
1255 for (const ObjCMethodList *Method = &Methods.second; Method;
1256 Method = Method->Next)
1257 if (Method->Method)
1258 DataLen += 4;
1259 clang::io::Emit16(Out, DataLen);
1260 return std::make_pair(KeyLen, DataLen);
1261 }
1262
Douglas Gregor83941df2009-04-25 17:48:32 +00001263 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1264 uint64_t Start = Out.tell();
1265 assert((Start >> 32) == 0 && "Selector key offset too large");
1266 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001267 unsigned N = Sel.getNumArgs();
1268 clang::io::Emit16(Out, N);
1269 if (N == 0)
1270 N = 1;
1271 for (unsigned I = 0; I != N; ++I)
1272 clang::io::Emit32(Out,
1273 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1274 }
1275
1276 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001277 data_type_ref Methods, unsigned DataLen) {
1278 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001279 unsigned NumInstanceMethods = 0;
1280 for (const ObjCMethodList *Method = &Methods.first; Method;
1281 Method = Method->Next)
1282 if (Method->Method)
1283 ++NumInstanceMethods;
1284
1285 unsigned NumFactoryMethods = 0;
1286 for (const ObjCMethodList *Method = &Methods.second; Method;
1287 Method = Method->Next)
1288 if (Method->Method)
1289 ++NumFactoryMethods;
1290
1291 clang::io::Emit16(Out, NumInstanceMethods);
1292 clang::io::Emit16(Out, NumFactoryMethods);
1293 for (const ObjCMethodList *Method = &Methods.first; Method;
1294 Method = Method->Next)
1295 if (Method->Method)
1296 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001297 for (const ObjCMethodList *Method = &Methods.second; Method;
1298 Method = Method->Next)
1299 if (Method->Method)
1300 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001301
1302 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001303 }
1304};
1305} // end anonymous namespace
1306
1307/// \brief Write the method pool into the PCH file.
1308///
1309/// The method pool contains both instance and factory methods, stored
1310/// in an on-disk hash table indexed by the selector.
1311void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1312 using namespace llvm;
1313
1314 // Create and write out the blob that contains the instance and
1315 // factor method pools.
1316 bool Empty = true;
1317 {
1318 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1319
1320 // Create the on-disk hash table representation. Start by
1321 // iterating through the instance method pool.
1322 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001323 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001324 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1325 Instance = SemaRef.InstanceMethodPool.begin(),
1326 InstanceEnd = SemaRef.InstanceMethodPool.end();
1327 Instance != InstanceEnd; ++Instance) {
1328 // Check whether there is a factory method with the same
1329 // selector.
1330 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1331 = SemaRef.FactoryMethodPool.find(Instance->first);
1332
1333 if (Factory == SemaRef.FactoryMethodPool.end())
1334 Generator.insert(Instance->first,
1335 std::make_pair(Instance->second,
1336 ObjCMethodList()));
1337 else
1338 Generator.insert(Instance->first,
1339 std::make_pair(Instance->second, Factory->second));
1340
Douglas Gregor83941df2009-04-25 17:48:32 +00001341 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001342 Empty = false;
1343 }
1344
1345 // Now iterate through the factory method pool, to pick up any
1346 // selectors that weren't already in the instance method pool.
1347 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1348 Factory = SemaRef.FactoryMethodPool.begin(),
1349 FactoryEnd = SemaRef.FactoryMethodPool.end();
1350 Factory != FactoryEnd; ++Factory) {
1351 // Check whether there is an instance method with the same
1352 // selector. If so, there is no work to do here.
1353 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1354 = SemaRef.InstanceMethodPool.find(Factory->first);
1355
Douglas Gregor83941df2009-04-25 17:48:32 +00001356 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001357 Generator.insert(Factory->first,
1358 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001359 ++NumSelectorsInMethodPool;
1360 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001361
1362 Empty = false;
1363 }
1364
Douglas Gregor83941df2009-04-25 17:48:32 +00001365 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001366 return;
1367
1368 // Create the on-disk hash table in a buffer.
1369 llvm::SmallVector<char, 4096> MethodPool;
1370 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001371 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001372 {
1373 PCHMethodPoolTrait Trait(*this);
1374 llvm::raw_svector_ostream Out(MethodPool);
1375 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001376 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001377 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001378
1379 // For every selector that we have seen but which was not
1380 // written into the hash table, write the selector itself and
1381 // record it's offset.
1382 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1383 if (SelectorOffsets[I] == 0)
1384 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001385 }
1386
1387 // Create a blob abbreviation
1388 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1389 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1390 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001391 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001392 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1393 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1394
Douglas Gregor83941df2009-04-25 17:48:32 +00001395 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001396 RecordData Record;
1397 Record.push_back(pch::METHOD_POOL);
1398 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001399 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001400 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1401 &MethodPool.front(),
1402 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001403
1404 // Create a blob abbreviation for the selector table offsets.
1405 Abbrev = new BitCodeAbbrev();
1406 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1407 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1409 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1410
1411 // Write the selector offsets table.
1412 Record.clear();
1413 Record.push_back(pch::SELECTOR_OFFSETS);
1414 Record.push_back(SelectorOffsets.size());
1415 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1416 (const char *)&SelectorOffsets.front(),
1417 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001418 }
1419}
1420
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001421//===----------------------------------------------------------------------===//
1422// Identifier Table Serialization
1423//===----------------------------------------------------------------------===//
1424
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001425namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001426class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1427 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001428 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001429
Douglas Gregora92193e2009-04-28 21:18:29 +00001430 /// \brief Determines whether this is an "interesting" identifier
1431 /// that needs a full IdentifierInfo structure written into the hash
1432 /// table.
1433 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1434 return II->isPoisoned() ||
1435 II->isExtensionToken() ||
1436 II->hasMacroDefinition() ||
1437 II->getObjCOrBuiltinID() ||
1438 II->getFETokenInfo<void>();
1439 }
1440
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001441public:
1442 typedef const IdentifierInfo* key_type;
1443 typedef key_type key_type_ref;
1444
1445 typedef pch::IdentID data_type;
1446 typedef data_type data_type_ref;
1447
Douglas Gregor37e26842009-04-21 23:56:24 +00001448 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1449 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001450
1451 static unsigned ComputeHash(const IdentifierInfo* II) {
1452 return clang::BernsteinHash(II->getName());
1453 }
1454
Douglas Gregor37e26842009-04-21 23:56:24 +00001455 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001456 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1457 pch::IdentID ID) {
1458 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001459 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1460 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001461 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001462 if (II->hasMacroDefinition() &&
1463 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001464 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001465 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1466 DEnd = IdentifierResolver::end();
1467 D != DEnd; ++D)
1468 DataLen += sizeof(pch::DeclID);
1469 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001470 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001471 // We emit the key length after the data length so that every
1472 // string is preceded by a 16-bit length. This matches the PTH
1473 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001474 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001475 return std::make_pair(KeyLen, DataLen);
1476 }
1477
1478 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1479 unsigned KeyLen) {
1480 // Record the location of the key data. This is used when generating
1481 // the mapping from persistent IDs to strings.
1482 Writer.SetIdentifierOffset(II, Out.tell());
1483 Out.write(II->getName(), KeyLen);
1484 }
1485
1486 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1487 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001488 if (!isInterestingIdentifier(II)) {
1489 clang::io::Emit32(Out, ID << 1);
1490 return;
1491 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001492
Douglas Gregora92193e2009-04-28 21:18:29 +00001493 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001494 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001495 bool hasMacroDefinition =
1496 II->hasMacroDefinition() &&
1497 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001498 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001499 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001500 Bits = (Bits << 1) | II->isExtensionToken();
1501 Bits = (Bits << 1) | II->isPoisoned();
1502 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001503 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001504
Douglas Gregor37e26842009-04-21 23:56:24 +00001505 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001506 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001507
Douglas Gregor668c1a42009-04-21 22:25:48 +00001508 // Emit the declaration IDs in reverse order, because the
1509 // IdentifierResolver provides the declarations as they would be
1510 // visible (e.g., the function "stat" would come before the struct
1511 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1512 // adds declarations to the end of the list (so we need to see the
1513 // struct "status" before the function "status").
1514 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1515 IdentifierResolver::end());
1516 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1517 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001518 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001519 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001520 }
1521};
1522} // end anonymous namespace
1523
Douglas Gregorafaf3082009-04-11 00:14:32 +00001524/// \brief Write the identifier table into the PCH file.
1525///
1526/// The identifier table consists of a blob containing string data
1527/// (the actual identifiers themselves) and a separate "offsets" index
1528/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001529void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001530 using namespace llvm;
1531
1532 // Create and write out the blob that contains the identifier
1533 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001534 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001535 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1536
Douglas Gregor92b059e2009-04-28 20:33:11 +00001537 // Look for any identifiers that were named while processing the
1538 // headers, but are otherwise not needed. We add these to the hash
1539 // table to enable checking of the predefines buffer in the case
1540 // where the user adds new macro definitions when building the PCH
1541 // file.
1542 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1543 IDEnd = PP.getIdentifierTable().end();
1544 ID != IDEnd; ++ID)
1545 getIdentifierRef(ID->second);
1546
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001547 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001548 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001549 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1550 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1551 ID != IDEnd; ++ID) {
1552 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001553 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001554 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001555
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001556 // Create the on-disk hash table in a buffer.
1557 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001558 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001559 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001560 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001561 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001562 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001563 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001564 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001565 }
1566
1567 // Create a blob abbreviation
1568 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1569 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001572 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001573
1574 // Write the identifier table
1575 RecordData Record;
1576 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001577 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001578 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1579 &IdentifierTable.front(),
1580 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001581 }
1582
1583 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001584 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1585 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1586 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1587 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1588 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1589
1590 RecordData Record;
1591 Record.push_back(pch::IDENTIFIER_OFFSET);
1592 Record.push_back(IdentifierOffsets.size());
1593 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1594 (const char *)&IdentifierOffsets.front(),
1595 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001596}
1597
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001598//===----------------------------------------------------------------------===//
1599// General Serialization Routines
1600//===----------------------------------------------------------------------===//
1601
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001602/// \brief Write a record containing the given attributes.
1603void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1604 RecordData Record;
1605 for (; Attr; Attr = Attr->getNext()) {
1606 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1607 Record.push_back(Attr->isInherited());
1608 switch (Attr->getKind()) {
1609 case Attr::Alias:
1610 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1611 break;
1612
1613 case Attr::Aligned:
1614 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1615 break;
1616
1617 case Attr::AlwaysInline:
1618 break;
1619
1620 case Attr::AnalyzerNoReturn:
1621 break;
1622
1623 case Attr::Annotate:
1624 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1625 break;
1626
1627 case Attr::AsmLabel:
1628 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1629 break;
1630
1631 case Attr::Blocks:
1632 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1633 break;
1634
1635 case Attr::Cleanup:
1636 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1637 break;
1638
1639 case Attr::Const:
1640 break;
1641
1642 case Attr::Constructor:
1643 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1644 break;
1645
1646 case Attr::DLLExport:
1647 case Attr::DLLImport:
1648 case Attr::Deprecated:
1649 break;
1650
1651 case Attr::Destructor:
1652 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1653 break;
1654
1655 case Attr::FastCall:
1656 break;
1657
1658 case Attr::Format: {
1659 const FormatAttr *Format = cast<FormatAttr>(Attr);
1660 AddString(Format->getType(), Record);
1661 Record.push_back(Format->getFormatIdx());
1662 Record.push_back(Format->getFirstArg());
1663 break;
1664 }
1665
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001666 case Attr::FormatArg: {
1667 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1668 Record.push_back(Format->getFormatIdx());
1669 break;
1670 }
1671
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001672 case Attr::Sentinel : {
1673 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1674 Record.push_back(Sentinel->getSentinel());
1675 Record.push_back(Sentinel->getNullPos());
1676 break;
1677 }
1678
Chris Lattnercf2a7212009-04-20 19:12:28 +00001679 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001680 case Attr::IBOutletKind:
1681 case Attr::NoReturn:
1682 case Attr::NoThrow:
1683 case Attr::Nodebug:
1684 case Attr::Noinline:
1685 break;
1686
1687 case Attr::NonNull: {
1688 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1689 Record.push_back(NonNull->size());
1690 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1691 break;
1692 }
1693
1694 case Attr::ObjCException:
1695 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001696 case Attr::CFReturnsRetained:
1697 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001698 case Attr::Overloadable:
1699 break;
1700
1701 case Attr::Packed:
1702 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1703 break;
1704
1705 case Attr::Pure:
1706 break;
1707
1708 case Attr::Regparm:
1709 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1710 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001711
1712 case Attr::ReqdWorkGroupSize:
1713 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1714 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1715 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1716 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001717
1718 case Attr::Section:
1719 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1720 break;
1721
1722 case Attr::StdCall:
1723 case Attr::TransparentUnion:
1724 case Attr::Unavailable:
1725 case Attr::Unused:
1726 case Attr::Used:
1727 break;
1728
1729 case Attr::Visibility:
1730 // FIXME: stable encoding
1731 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1732 break;
1733
1734 case Attr::WarnUnusedResult:
1735 case Attr::Weak:
1736 case Attr::WeakImport:
1737 break;
1738 }
1739 }
1740
Douglas Gregorc9490c02009-04-16 22:23:12 +00001741 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001742}
1743
1744void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1745 Record.push_back(Str.size());
1746 Record.insert(Record.end(), Str.begin(), Str.end());
1747}
1748
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001749/// \brief Note that the identifier II occurs at the given offset
1750/// within the identifier table.
1751void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001752 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001753}
1754
Douglas Gregor83941df2009-04-25 17:48:32 +00001755/// \brief Note that the selector Sel occurs at the given offset
1756/// within the method pool/selector table.
1757void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1758 unsigned ID = SelectorIDs[Sel];
1759 assert(ID && "Unknown selector");
1760 SelectorOffsets[ID - 1] = Offset;
1761}
1762
Douglas Gregorc9490c02009-04-16 22:23:12 +00001763PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001764 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001765 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1766 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767
Douglas Gregore650c8c2009-07-07 00:12:59 +00001768void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1769 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001770 using namespace llvm;
1771
Douglas Gregore7785042009-04-20 15:53:59 +00001772 ASTContext &Context = SemaRef.Context;
1773 Preprocessor &PP = SemaRef.PP;
1774
Douglas Gregor2cf26342009-04-09 22:27:44 +00001775 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001776 Stream.Emit((unsigned)'C', 8);
1777 Stream.Emit((unsigned)'P', 8);
1778 Stream.Emit((unsigned)'C', 8);
1779 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001780
1781 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001782
1783 // The translation unit is the first declaration we'll emit.
1784 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1785 DeclsToEmit.push(Context.getTranslationUnitDecl());
1786
Douglas Gregor2deaea32009-04-22 18:49:13 +00001787 // Make sure that we emit IdentifierInfos (and any attached
1788 // declarations) for builtins.
1789 {
1790 IdentifierTable &Table = PP.getIdentifierTable();
1791 llvm::SmallVector<const char *, 32> BuiltinNames;
1792 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1793 Context.getLangOptions().NoBuiltin);
1794 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1795 getIdentifierRef(&Table.get(BuiltinNames[I]));
1796 }
1797
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001798 // Build a record containing all of the tentative definitions in
1799 // this header file. Generally, this record will be empty.
1800 RecordData TentativeDefinitions;
1801 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1802 TD = SemaRef.TentativeDefinitions.begin(),
1803 TDEnd = SemaRef.TentativeDefinitions.end();
1804 TD != TDEnd; ++TD)
1805 AddDeclRef(TD->second, TentativeDefinitions);
1806
Douglas Gregor14c22f22009-04-22 22:18:58 +00001807 // Build a record containing all of the locally-scoped external
1808 // declarations in this header file. Generally, this record will be
1809 // empty.
1810 RecordData LocallyScopedExternalDecls;
1811 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1812 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1813 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1814 TD != TDEnd; ++TD)
1815 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1816
Douglas Gregorb81c1702009-04-27 20:06:05 +00001817 // Build a record containing all of the ext_vector declarations.
1818 RecordData ExtVectorDecls;
1819 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1820 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1821
Douglas Gregor2cf26342009-04-09 22:27:44 +00001822 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001823 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001824 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001825 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001826 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001827 if (StatCalls && !isysroot)
1828 WriteStatCache(*StatCalls, isysroot);
1829 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001830 WritePreprocessor(PP);
Douglas Gregor2e222532009-07-02 17:08:52 +00001831 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001832 // Write the record of special types.
1833 Record.clear();
1834
1835 AddTypeRef(Context.getBuiltinVaListType(), Record);
1836 AddTypeRef(Context.getObjCIdType(), Record);
1837 AddTypeRef(Context.getObjCSelType(), Record);
1838 AddTypeRef(Context.getObjCProtoType(), Record);
1839 AddTypeRef(Context.getObjCClassType(), Record);
1840 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1841 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1842 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001843 AddTypeRef(Context.getjmp_bufType(), Record);
1844 AddTypeRef(Context.getsigjmp_bufType(), Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001845 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Douglas Gregor2e222532009-07-02 17:08:52 +00001846
Douglas Gregor366809a2009-04-26 03:49:13 +00001847 // Keep writing types and declarations until all types and
1848 // declarations have been written.
1849 do {
1850 if (!DeclsToEmit.empty())
1851 WriteDeclsBlock(Context);
1852 if (!TypesToEmit.empty())
1853 WriteTypesBlock(Context);
1854 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1855
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001856 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001857 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001858
1859 // Write the type offsets array
1860 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1861 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1862 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1864 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1865 Record.clear();
1866 Record.push_back(pch::TYPE_OFFSET);
1867 Record.push_back(TypeOffsets.size());
1868 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1869 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001870 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001871
1872 // Write the declaration offsets array
1873 Abbrev = new BitCodeAbbrev();
1874 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1877 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1878 Record.clear();
1879 Record.push_back(pch::DECL_OFFSET);
1880 Record.push_back(DeclOffsets.size());
1881 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1882 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001883 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001884
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001885 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001886 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001887 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001888
1889 // Write the record containing tentative definitions.
1890 if (!TentativeDefinitions.empty())
1891 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001892
1893 // Write the record containing locally-scoped external definitions.
1894 if (!LocallyScopedExternalDecls.empty())
1895 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1896 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001897
1898 // Write the record containing ext_vector type names.
1899 if (!ExtVectorDecls.empty())
1900 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001901
1902 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001903 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001904 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001905 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001906 Record.push_back(NumLexicalDeclContexts);
1907 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001908 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001909 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001910}
1911
1912void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1913 Record.push_back(Loc.getRawEncoding());
1914}
1915
1916void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1917 Record.push_back(Value.getBitWidth());
1918 unsigned N = Value.getNumWords();
1919 const uint64_t* Words = Value.getRawData();
1920 for (unsigned I = 0; I != N; ++I)
1921 Record.push_back(Words[I]);
1922}
1923
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001924void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1925 Record.push_back(Value.isUnsigned());
1926 AddAPInt(Value, Record);
1927}
1928
Douglas Gregor17fc2232009-04-14 21:55:33 +00001929void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1930 AddAPInt(Value.bitcastToAPInt(), Record);
1931}
1932
Douglas Gregor2cf26342009-04-09 22:27:44 +00001933void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001934 Record.push_back(getIdentifierRef(II));
1935}
1936
1937pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1938 if (II == 0)
1939 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001940
1941 pch::IdentID &ID = IdentifierIDs[II];
1942 if (ID == 0)
1943 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001944 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001945}
1946
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001947void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1948 if (SelRef.getAsOpaquePtr() == 0) {
1949 Record.push_back(0);
1950 return;
1951 }
1952
1953 pch::SelectorID &SID = SelectorIDs[SelRef];
1954 if (SID == 0) {
1955 SID = SelectorIDs.size();
1956 SelVector.push_back(SelRef);
1957 }
1958 Record.push_back(SID);
1959}
1960
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1962 if (T.isNull()) {
1963 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1964 return;
1965 }
1966
1967 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001968 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001969 switch (BT->getKind()) {
1970 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1971 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1972 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1973 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1974 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1975 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1976 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1977 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001978 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001979 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1980 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1981 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1982 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1983 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1984 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1985 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001986 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001987 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1988 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1989 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001990 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001991 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
1992 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001993 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1994 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00001995 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
1996 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00001997 case BuiltinType::UndeducedAuto:
1998 assert(0 && "Should not see undeduced auto here");
1999 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 }
2001
2002 Record.push_back((ID << 3) | T.getCVRQualifiers());
2003 return;
2004 }
2005
Douglas Gregor8038d512009-04-10 17:25:41 +00002006 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00002007 if (ID == 0) {
2008 // We haven't seen this type before. Assign it a new ID and put it
2009 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002010 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00002011 TypesToEmit.push(T.getTypePtr());
2012 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002013
2014 // Encode the type qualifiers in the type reference.
2015 Record.push_back((ID << 3) | T.getCVRQualifiers());
2016}
2017
2018void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2019 if (D == 0) {
2020 Record.push_back(0);
2021 return;
2022 }
2023
Douglas Gregor8038d512009-04-10 17:25:41 +00002024 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002025 if (ID == 0) {
2026 // We haven't seen this declaration before. Give it a new ID and
2027 // enqueue it in the list of declarations to emit.
2028 ID = DeclIDs.size();
2029 DeclsToEmit.push(const_cast<Decl *>(D));
2030 }
2031
2032 Record.push_back(ID);
2033}
2034
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002035pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2036 if (D == 0)
2037 return 0;
2038
2039 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2040 return DeclIDs[D];
2041}
2042
Douglas Gregor2cf26342009-04-09 22:27:44 +00002043void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002044 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002045 Record.push_back(Name.getNameKind());
2046 switch (Name.getNameKind()) {
2047 case DeclarationName::Identifier:
2048 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2049 break;
2050
2051 case DeclarationName::ObjCZeroArgSelector:
2052 case DeclarationName::ObjCOneArgSelector:
2053 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002054 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002055 break;
2056
2057 case DeclarationName::CXXConstructorName:
2058 case DeclarationName::CXXDestructorName:
2059 case DeclarationName::CXXConversionFunctionName:
2060 AddTypeRef(Name.getCXXNameType(), Record);
2061 break;
2062
2063 case DeclarationName::CXXOperatorName:
2064 Record.push_back(Name.getCXXOverloadedOperator());
2065 break;
2066
2067 case DeclarationName::CXXUsingDirective:
2068 // No extra data to emit
2069 break;
2070 }
2071}
Douglas Gregor0b748912009-04-14 21:18:50 +00002072