blob: dc0ee3575c7c44b35762d807e1c7e03e64c670c0 [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();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000545 P.appendComponent(MainFilePath.str());
546 MainFileName = P.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000547 } else {
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000548 MainFileName = MainFilePath.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000549 }
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);
Anders Carlsson92f58222009-08-22 22:30:33 +0000624 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000625 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000626}
627
Douglas Gregor14f79002009-04-10 03:52:48 +0000628//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000629// stat cache Serialization
630//===----------------------------------------------------------------------===//
631
632namespace {
633// Trait used for the on-disk hash table of stat cache results.
634class VISIBILITY_HIDDEN PCHStatCacheTrait {
635public:
636 typedef const char * key_type;
637 typedef key_type key_type_ref;
638
639 typedef std::pair<int, struct stat> data_type;
640 typedef const data_type& data_type_ref;
641
642 static unsigned ComputeHash(const char *path) {
643 return BernsteinHash(path);
644 }
645
646 std::pair<unsigned,unsigned>
647 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
648 data_type_ref Data) {
649 unsigned StrLen = strlen(path);
650 clang::io::Emit16(Out, StrLen);
651 unsigned DataLen = 1; // result value
652 if (Data.first == 0)
653 DataLen += 4 + 4 + 2 + 8 + 8;
654 clang::io::Emit8(Out, DataLen);
655 return std::make_pair(StrLen + 1, DataLen);
656 }
657
658 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
659 Out.write(path, KeyLen);
660 }
661
662 void EmitData(llvm::raw_ostream& Out, key_type_ref,
663 data_type_ref Data, unsigned DataLen) {
664 using namespace clang::io;
665 uint64_t Start = Out.tell(); (void)Start;
666
667 // Result of stat()
668 Emit8(Out, Data.first? 1 : 0);
669
670 if (Data.first == 0) {
671 Emit32(Out, (uint32_t) Data.second.st_ino);
672 Emit32(Out, (uint32_t) Data.second.st_dev);
673 Emit16(Out, (uint16_t) Data.second.st_mode);
674 Emit64(Out, (uint64_t) Data.second.st_mtime);
675 Emit64(Out, (uint64_t) Data.second.st_size);
676 }
677
678 assert(Out.tell() - Start == DataLen && "Wrong data length");
679 }
680};
681} // end anonymous namespace
682
683/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000684void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
685 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000686 // Build the on-disk hash table containing information about every
687 // stat() call.
688 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
689 unsigned NumStatEntries = 0;
690 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
691 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000692 Stat != StatEnd; ++Stat, ++NumStatEntries) {
693 const char *Filename = Stat->first();
694 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
695 Generator.insert(Filename, Stat->second);
696 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000697
698 // Create the on-disk hash table in a buffer.
699 llvm::SmallVector<char, 4096> StatCacheData;
700 uint32_t BucketOffset;
701 {
702 llvm::raw_svector_ostream Out(StatCacheData);
703 // Make sure that no bucket is at offset 0
704 clang::io::Emit32(Out, 0);
705 BucketOffset = Generator.Emit(Out);
706 }
707
708 // Create a blob abbreviation
709 using namespace llvm;
710 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
711 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
715 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
716
717 // Write the stat cache
718 RecordData Record;
719 Record.push_back(pch::STAT_CACHE);
720 Record.push_back(BucketOffset);
721 Record.push_back(NumStatEntries);
722 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
723 &StatCacheData.front(),
724 StatCacheData.size());
725}
726
727//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000728// Source Manager Serialization
729//===----------------------------------------------------------------------===//
730
731/// \brief Create an abbreviation for the SLocEntry that refers to a
732/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000733static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000734 using namespace llvm;
735 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
736 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
737 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
739 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
740 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000742 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000743}
744
745/// \brief Create an abbreviation for the SLocEntry that refers to a
746/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000747static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000748 using namespace llvm;
749 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
750 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000756 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000757}
758
759/// \brief Create an abbreviation for the SLocEntry that refers to a
760/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000761static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000762 using namespace llvm;
763 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
764 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000766 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000767}
768
769/// \brief Create an abbreviation for the SLocEntry that refers to an
770/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000771static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000772 using namespace llvm;
773 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
774 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
776 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000780 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000781}
782
783/// \brief Writes the block containing the serialized form of the
784/// source manager.
785///
786/// TODO: We should probably use an on-disk hash table (stored in a
787/// blob), indexed based on the file name, so that we only create
788/// entries for files that we actually need. In the common case (no
789/// errors), we probably won't have to create file entries for any of
790/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000791void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000792 const Preprocessor &PP,
793 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000794 RecordData Record;
795
Chris Lattnerf04ad692009-04-10 17:16:57 +0000796 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000797 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000798
799 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000800 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
801 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
802 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
803 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000804
Douglas Gregorbd945002009-04-13 16:31:14 +0000805 // Write the line table.
806 if (SourceMgr.hasLineTable()) {
807 LineTableInfo &LineTable = SourceMgr.getLineTable();
808
809 // Emit the file names
810 Record.push_back(LineTable.getNumFilenames());
811 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
812 // Emit the file name
813 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000814 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000815 unsigned FilenameLen = Filename? strlen(Filename) : 0;
816 Record.push_back(FilenameLen);
817 if (FilenameLen)
818 Record.insert(Record.end(), Filename, Filename + FilenameLen);
819 }
820
821 // Emit the line entries
822 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
823 L != LEnd; ++L) {
824 // Emit the file ID
825 Record.push_back(L->first);
826
827 // Emit the line entries
828 Record.push_back(L->second.size());
829 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
830 LEEnd = L->second.end();
831 LE != LEEnd; ++LE) {
832 Record.push_back(LE->FileOffset);
833 Record.push_back(LE->LineNo);
834 Record.push_back(LE->FilenameID);
835 Record.push_back((unsigned)LE->FileKind);
836 Record.push_back(LE->IncludeOffset);
837 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000838 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000839 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000840 }
841
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000842 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000843 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000844 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000845 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
846 E = HS.header_file_end();
847 I != E; ++I) {
848 Record.push_back(I->isImport);
849 Record.push_back(I->DirInfo);
850 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000851 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000852 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
853 Record.clear();
854 }
855
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000856 // Write out the source location entry table. We skip the first
857 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000858 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000859 RecordData PreloadSLocs;
860 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
861 for (SourceManager::sloc_entry_iterator
862 SLoc = SourceMgr.sloc_entry_begin() + 1,
863 SLocEnd = SourceMgr.sloc_entry_end();
864 SLoc != SLocEnd; ++SLoc) {
865 // Record the offset of this source-location entry.
866 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
867
868 // Figure out which record code to use.
869 unsigned Code;
870 if (SLoc->isFile()) {
871 if (SLoc->getFile().getContentCache()->Entry)
872 Code = pch::SM_SLOC_FILE_ENTRY;
873 else
874 Code = pch::SM_SLOC_BUFFER_ENTRY;
875 } else
876 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
877 Record.clear();
878 Record.push_back(Code);
879
880 Record.push_back(SLoc->getOffset());
881 if (SLoc->isFile()) {
882 const SrcMgr::FileInfo &File = SLoc->getFile();
883 Record.push_back(File.getIncludeLoc().getRawEncoding());
884 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
885 Record.push_back(File.hasLineDirectives());
886
887 const SrcMgr::ContentCache *Content = File.getContentCache();
888 if (Content->Entry) {
889 // The source location entry is a file. The blob associated
890 // with this entry is the file name.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000891
892 // Turn the file name into an absolute path, if it isn't already.
893 const char *Filename = Content->Entry->getName();
894 llvm::sys::Path FilePath(Filename, strlen(Filename));
895 std::string FilenameStr;
896 if (!FilePath.isAbsolute()) {
897 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000898 P.appendComponent(FilePath.str());
899 FilenameStr = P.str();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000900 Filename = FilenameStr.c_str();
901 }
902
903 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
904 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename,
905 strlen(Filename));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000906
907 // FIXME: For now, preload all file source locations, so that
908 // we get the appropriate File entries in the reader. This is
909 // a temporary measure.
910 PreloadSLocs.push_back(SLocEntryOffsets.size());
911 } else {
912 // The source location entry is a buffer. The blob associated
913 // with this entry contains the contents of the buffer.
914
915 // We add one to the size so that we capture the trailing NULL
916 // that is required by llvm::MemoryBuffer::getMemBuffer (on
917 // the reader side).
918 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
919 const char *Name = Buffer->getBufferIdentifier();
920 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
921 Record.clear();
922 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
923 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
924 Buffer->getBufferStart(),
925 Buffer->getBufferSize() + 1);
926
927 if (strcmp(Name, "<built-in>") == 0)
928 PreloadSLocs.push_back(SLocEntryOffsets.size());
929 }
930 } else {
931 // The source location entry is an instantiation.
932 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
933 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
934 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
935 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
936
937 // Compute the token length for this macro expansion.
938 unsigned NextOffset = SourceMgr.getNextOffset();
939 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
940 if (++NextSLoc != SLocEnd)
941 NextOffset = NextSLoc->getOffset();
942 Record.push_back(NextOffset - SLoc->getOffset() - 1);
943 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
944 }
945 }
946
Douglas Gregorc9490c02009-04-16 22:23:12 +0000947 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000948
949 if (SLocEntryOffsets.empty())
950 return;
951
952 // Write the source-location offsets table into the PCH block. This
953 // table is used for lazily loading source-location information.
954 using namespace llvm;
955 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
956 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
957 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
958 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
959 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
960 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
961
962 Record.clear();
963 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
964 Record.push_back(SLocEntryOffsets.size());
965 Record.push_back(SourceMgr.getNextOffset());
966 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
967 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000968 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000969
970 // Write the source location entry preloads array, telling the PCH
971 // reader which source locations entries it should load eagerly.
972 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000973}
974
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000975//===----------------------------------------------------------------------===//
976// Preprocessor Serialization
977//===----------------------------------------------------------------------===//
978
Chris Lattner0b1fb982009-04-10 17:15:23 +0000979/// \brief Writes the block containing the serialized form of the
980/// preprocessor.
981///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000982void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000983 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000984
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000985 // If the preprocessor __COUNTER__ value has been bumped, remember it.
986 if (PP.getCounterValue() != 0) {
987 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000988 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000989 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000990 }
991
992 // Enter the preprocessor block.
993 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000994
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000995 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
996 // FIXME: use diagnostics subsystem for localization etc.
997 if (PP.SawDateOrTime())
998 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
999
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001000 // Loop over all the macro definitions that are live at the end of the file,
1001 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001002 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1003 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001004 // FIXME: This emits macros in hash table order, we should do it in a stable
1005 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001006 MacroInfo *MI = I->second;
1007
1008 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1009 // been redefined by the header (in which case they are not isBuiltinMacro).
1010 if (MI->isBuiltinMacro())
1011 continue;
1012
Douglas Gregor37e26842009-04-21 23:56:24 +00001013 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001014 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001015 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001016 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1017 Record.push_back(MI->isUsed());
1018
1019 unsigned Code;
1020 if (MI->isObjectLike()) {
1021 Code = pch::PP_MACRO_OBJECT_LIKE;
1022 } else {
1023 Code = pch::PP_MACRO_FUNCTION_LIKE;
1024
1025 Record.push_back(MI->isC99Varargs());
1026 Record.push_back(MI->isGNUVarargs());
1027 Record.push_back(MI->getNumArgs());
1028 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1029 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001030 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001031 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001032 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001033 Record.clear();
1034
Chris Lattnerdf961c22009-04-10 18:08:30 +00001035 // Emit the tokens array.
1036 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1037 // Note that we know that the preprocessor does not have any annotation
1038 // tokens in it because they are created by the parser, and thus can't be
1039 // in a macro definition.
1040 const Token &Tok = MI->getReplacementToken(TokNo);
1041
1042 Record.push_back(Tok.getLocation().getRawEncoding());
1043 Record.push_back(Tok.getLength());
1044
Chris Lattnerdf961c22009-04-10 18:08:30 +00001045 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1046 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001047 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001048
1049 // FIXME: Should translate token kind to a stable encoding.
1050 Record.push_back(Tok.getKind());
1051 // FIXME: Should translate token flags to a stable encoding.
1052 Record.push_back(Tok.getFlags());
1053
Douglas Gregorc9490c02009-04-16 22:23:12 +00001054 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001055 Record.clear();
1056 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001057 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001058 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001059 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001060}
1061
Douglas Gregor2e222532009-07-02 17:08:52 +00001062void PCHWriter::WriteComments(ASTContext &Context) {
1063 using namespace llvm;
1064
1065 if (Context.Comments.empty())
1066 return;
1067
1068 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1069 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1070 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1071 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1072
1073 RecordData Record;
1074 Record.push_back(pch::COMMENT_RANGES);
1075 Stream.EmitRecordWithBlob(CommentCode, Record,
1076 (const char*)&Context.Comments[0],
1077 Context.Comments.size() * sizeof(SourceRange));
1078}
1079
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001080//===----------------------------------------------------------------------===//
1081// Type Serialization
1082//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001083
Douglas Gregor2cf26342009-04-09 22:27:44 +00001084/// \brief Write the representation of a type to the PCH stream.
1085void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001086 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001087 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001088 ID = NextTypeID++;
1089
1090 // Record the offset for this type.
1091 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001092 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001093 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1094 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001095 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001096 }
1097
1098 RecordData Record;
1099
1100 // Emit the type's representation.
1101 PCHTypeWriter W(*this, Record);
1102 switch (T->getTypeClass()) {
1103 // For all of the concrete, non-dependent types, call the
1104 // appropriate visitor function.
1105#define TYPE(Class, Base) \
1106 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1107#define ABSTRACT_TYPE(Class, Base)
1108#define DEPENDENT_TYPE(Class, Base)
1109#include "clang/AST/TypeNodes.def"
1110
1111 // For all of the dependent type nodes (which only occur in C++
1112 // templates), produce an error.
1113#define TYPE(Class, Base)
1114#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1115#include "clang/AST/TypeNodes.def"
1116 assert(false && "Cannot serialize dependent type nodes");
1117 break;
1118 }
1119
1120 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001121 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001122
1123 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001124 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001125}
1126
1127/// \brief Write a block containing all of the types.
1128void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001129 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001130 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001131
Douglas Gregor366809a2009-04-26 03:49:13 +00001132 // Emit all of the types that need to be emitted (so far).
1133 while (!TypesToEmit.empty()) {
1134 const Type *T = TypesToEmit.front();
1135 TypesToEmit.pop();
1136 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1137 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001138 }
1139
1140 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001141 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001142}
1143
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001144//===----------------------------------------------------------------------===//
1145// Declaration Serialization
1146//===----------------------------------------------------------------------===//
1147
Douglas Gregor2cf26342009-04-09 22:27:44 +00001148/// \brief Write the block containing all of the declaration IDs
1149/// lexically declared within the given DeclContext.
1150///
1151/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1152/// bistream, or 0 if no block was written.
1153uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1154 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001155 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001156 return 0;
1157
Douglas Gregorc9490c02009-04-16 22:23:12 +00001158 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001160 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1161 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001162 AddDeclRef(*D, Record);
1163
Douglas Gregor25123082009-04-22 22:34:57 +00001164 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001165 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001166 return Offset;
1167}
1168
1169/// \brief Write the block containing all of the declaration IDs
1170/// visible from the given DeclContext.
1171///
1172/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1173/// bistream, or 0 if no block was written.
1174uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1175 DeclContext *DC) {
1176 if (DC->getPrimaryContext() != DC)
1177 return 0;
1178
Douglas Gregoraff22df2009-04-21 22:32:33 +00001179 // Since there is no name lookup into functions or methods, and we
1180 // perform name lookup for the translation unit via the
1181 // IdentifierInfo chains, don't bother to build a
1182 // visible-declarations table for these entities.
1183 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001184 return 0;
1185
Douglas Gregor2cf26342009-04-09 22:27:44 +00001186 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001187 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001188
1189 // Serialize the contents of the mapping used for lookup. Note that,
1190 // although we have two very different code paths, the serialized
1191 // representation is the same for both cases: a declaration name,
1192 // followed by a size, followed by references to the visible
1193 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001194 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001195 RecordData Record;
1196 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001197 if (!Map)
1198 return 0;
1199
Douglas Gregor2cf26342009-04-09 22:27:44 +00001200 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1201 D != DEnd; ++D) {
1202 AddDeclarationName(D->first, Record);
1203 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1204 Record.push_back(Result.second - Result.first);
1205 for(; Result.first != Result.second; ++Result.first)
1206 AddDeclRef(*Result.first, Record);
1207 }
1208
1209 if (Record.size() == 0)
1210 return 0;
1211
Douglas Gregorc9490c02009-04-16 22:23:12 +00001212 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001213 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001214 return Offset;
1215}
1216
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001217//===----------------------------------------------------------------------===//
1218// Global Method Pool and Selector Serialization
1219//===----------------------------------------------------------------------===//
1220
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001221namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001222// Trait used for the on-disk hash table used in the method pool.
1223class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1224 PCHWriter &Writer;
1225
1226public:
1227 typedef Selector key_type;
1228 typedef key_type key_type_ref;
1229
1230 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1231 typedef const data_type& data_type_ref;
1232
1233 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1234
1235 static unsigned ComputeHash(Selector Sel) {
1236 unsigned N = Sel.getNumArgs();
1237 if (N == 0)
1238 ++N;
1239 unsigned R = 5381;
1240 for (unsigned I = 0; I != N; ++I)
1241 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1242 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1243 return R;
1244 }
1245
1246 std::pair<unsigned,unsigned>
1247 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1248 data_type_ref Methods) {
1249 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1250 clang::io::Emit16(Out, KeyLen);
1251 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1252 for (const ObjCMethodList *Method = &Methods.first; Method;
1253 Method = Method->Next)
1254 if (Method->Method)
1255 DataLen += 4;
1256 for (const ObjCMethodList *Method = &Methods.second; Method;
1257 Method = Method->Next)
1258 if (Method->Method)
1259 DataLen += 4;
1260 clang::io::Emit16(Out, DataLen);
1261 return std::make_pair(KeyLen, DataLen);
1262 }
1263
Douglas Gregor83941df2009-04-25 17:48:32 +00001264 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1265 uint64_t Start = Out.tell();
1266 assert((Start >> 32) == 0 && "Selector key offset too large");
1267 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001268 unsigned N = Sel.getNumArgs();
1269 clang::io::Emit16(Out, N);
1270 if (N == 0)
1271 N = 1;
1272 for (unsigned I = 0; I != N; ++I)
1273 clang::io::Emit32(Out,
1274 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1275 }
1276
1277 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001278 data_type_ref Methods, unsigned DataLen) {
1279 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001280 unsigned NumInstanceMethods = 0;
1281 for (const ObjCMethodList *Method = &Methods.first; Method;
1282 Method = Method->Next)
1283 if (Method->Method)
1284 ++NumInstanceMethods;
1285
1286 unsigned NumFactoryMethods = 0;
1287 for (const ObjCMethodList *Method = &Methods.second; Method;
1288 Method = Method->Next)
1289 if (Method->Method)
1290 ++NumFactoryMethods;
1291
1292 clang::io::Emit16(Out, NumInstanceMethods);
1293 clang::io::Emit16(Out, NumFactoryMethods);
1294 for (const ObjCMethodList *Method = &Methods.first; Method;
1295 Method = Method->Next)
1296 if (Method->Method)
1297 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001298 for (const ObjCMethodList *Method = &Methods.second; Method;
1299 Method = Method->Next)
1300 if (Method->Method)
1301 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001302
1303 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001304 }
1305};
1306} // end anonymous namespace
1307
1308/// \brief Write the method pool into the PCH file.
1309///
1310/// The method pool contains both instance and factory methods, stored
1311/// in an on-disk hash table indexed by the selector.
1312void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1313 using namespace llvm;
1314
1315 // Create and write out the blob that contains the instance and
1316 // factor method pools.
1317 bool Empty = true;
1318 {
1319 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1320
1321 // Create the on-disk hash table representation. Start by
1322 // iterating through the instance method pool.
1323 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001324 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001325 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1326 Instance = SemaRef.InstanceMethodPool.begin(),
1327 InstanceEnd = SemaRef.InstanceMethodPool.end();
1328 Instance != InstanceEnd; ++Instance) {
1329 // Check whether there is a factory method with the same
1330 // selector.
1331 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1332 = SemaRef.FactoryMethodPool.find(Instance->first);
1333
1334 if (Factory == SemaRef.FactoryMethodPool.end())
1335 Generator.insert(Instance->first,
1336 std::make_pair(Instance->second,
1337 ObjCMethodList()));
1338 else
1339 Generator.insert(Instance->first,
1340 std::make_pair(Instance->second, Factory->second));
1341
Douglas Gregor83941df2009-04-25 17:48:32 +00001342 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001343 Empty = false;
1344 }
1345
1346 // Now iterate through the factory method pool, to pick up any
1347 // selectors that weren't already in the instance method pool.
1348 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1349 Factory = SemaRef.FactoryMethodPool.begin(),
1350 FactoryEnd = SemaRef.FactoryMethodPool.end();
1351 Factory != FactoryEnd; ++Factory) {
1352 // Check whether there is an instance method with the same
1353 // selector. If so, there is no work to do here.
1354 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1355 = SemaRef.InstanceMethodPool.find(Factory->first);
1356
Douglas Gregor83941df2009-04-25 17:48:32 +00001357 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001358 Generator.insert(Factory->first,
1359 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001360 ++NumSelectorsInMethodPool;
1361 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001362
1363 Empty = false;
1364 }
1365
Douglas Gregor83941df2009-04-25 17:48:32 +00001366 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001367 return;
1368
1369 // Create the on-disk hash table in a buffer.
1370 llvm::SmallVector<char, 4096> MethodPool;
1371 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001372 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001373 {
1374 PCHMethodPoolTrait Trait(*this);
1375 llvm::raw_svector_ostream Out(MethodPool);
1376 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001377 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001378 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001379
1380 // For every selector that we have seen but which was not
1381 // written into the hash table, write the selector itself and
1382 // record it's offset.
1383 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1384 if (SelectorOffsets[I] == 0)
1385 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001386 }
1387
1388 // Create a blob abbreviation
1389 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1390 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1391 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001392 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1394 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1395
Douglas Gregor83941df2009-04-25 17:48:32 +00001396 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001397 RecordData Record;
1398 Record.push_back(pch::METHOD_POOL);
1399 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001400 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001401 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1402 &MethodPool.front(),
1403 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001404
1405 // Create a blob abbreviation for the selector table offsets.
1406 Abbrev = new BitCodeAbbrev();
1407 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1409 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1410 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1411
1412 // Write the selector offsets table.
1413 Record.clear();
1414 Record.push_back(pch::SELECTOR_OFFSETS);
1415 Record.push_back(SelectorOffsets.size());
1416 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1417 (const char *)&SelectorOffsets.front(),
1418 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001419 }
1420}
1421
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001422//===----------------------------------------------------------------------===//
1423// Identifier Table Serialization
1424//===----------------------------------------------------------------------===//
1425
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001426namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001427class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1428 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001429 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001430
Douglas Gregora92193e2009-04-28 21:18:29 +00001431 /// \brief Determines whether this is an "interesting" identifier
1432 /// that needs a full IdentifierInfo structure written into the hash
1433 /// table.
1434 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1435 return II->isPoisoned() ||
1436 II->isExtensionToken() ||
1437 II->hasMacroDefinition() ||
1438 II->getObjCOrBuiltinID() ||
1439 II->getFETokenInfo<void>();
1440 }
1441
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001442public:
1443 typedef const IdentifierInfo* key_type;
1444 typedef key_type key_type_ref;
1445
1446 typedef pch::IdentID data_type;
1447 typedef data_type data_type_ref;
1448
Douglas Gregor37e26842009-04-21 23:56:24 +00001449 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1450 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001451
1452 static unsigned ComputeHash(const IdentifierInfo* II) {
1453 return clang::BernsteinHash(II->getName());
1454 }
1455
Douglas Gregor37e26842009-04-21 23:56:24 +00001456 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001457 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1458 pch::IdentID ID) {
1459 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001460 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1461 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001462 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001463 if (II->hasMacroDefinition() &&
1464 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001465 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001466 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1467 DEnd = IdentifierResolver::end();
1468 D != DEnd; ++D)
1469 DataLen += sizeof(pch::DeclID);
1470 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001471 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001472 // We emit the key length after the data length so that every
1473 // string is preceded by a 16-bit length. This matches the PTH
1474 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001475 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001476 return std::make_pair(KeyLen, DataLen);
1477 }
1478
1479 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1480 unsigned KeyLen) {
1481 // Record the location of the key data. This is used when generating
1482 // the mapping from persistent IDs to strings.
1483 Writer.SetIdentifierOffset(II, Out.tell());
1484 Out.write(II->getName(), KeyLen);
1485 }
1486
1487 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1488 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001489 if (!isInterestingIdentifier(II)) {
1490 clang::io::Emit32(Out, ID << 1);
1491 return;
1492 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001493
Douglas Gregora92193e2009-04-28 21:18:29 +00001494 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001495 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001496 bool hasMacroDefinition =
1497 II->hasMacroDefinition() &&
1498 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001499 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001500 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001501 Bits = (Bits << 1) | II->isExtensionToken();
1502 Bits = (Bits << 1) | II->isPoisoned();
1503 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001504 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001505
Douglas Gregor37e26842009-04-21 23:56:24 +00001506 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001507 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001508
Douglas Gregor668c1a42009-04-21 22:25:48 +00001509 // Emit the declaration IDs in reverse order, because the
1510 // IdentifierResolver provides the declarations as they would be
1511 // visible (e.g., the function "stat" would come before the struct
1512 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1513 // adds declarations to the end of the list (so we need to see the
1514 // struct "status" before the function "status").
1515 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1516 IdentifierResolver::end());
1517 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1518 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001519 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001520 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001521 }
1522};
1523} // end anonymous namespace
1524
Douglas Gregorafaf3082009-04-11 00:14:32 +00001525/// \brief Write the identifier table into the PCH file.
1526///
1527/// The identifier table consists of a blob containing string data
1528/// (the actual identifiers themselves) and a separate "offsets" index
1529/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001530void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001531 using namespace llvm;
1532
1533 // Create and write out the blob that contains the identifier
1534 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001535 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001536 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1537
Douglas Gregor92b059e2009-04-28 20:33:11 +00001538 // Look for any identifiers that were named while processing the
1539 // headers, but are otherwise not needed. We add these to the hash
1540 // table to enable checking of the predefines buffer in the case
1541 // where the user adds new macro definitions when building the PCH
1542 // file.
1543 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1544 IDEnd = PP.getIdentifierTable().end();
1545 ID != IDEnd; ++ID)
1546 getIdentifierRef(ID->second);
1547
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001548 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001549 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001550 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1551 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1552 ID != IDEnd; ++ID) {
1553 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001554 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001555 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001556
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001557 // Create the on-disk hash table in a buffer.
1558 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001559 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001560 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001561 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001562 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001563 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001564 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001565 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001566 }
1567
1568 // Create a blob abbreviation
1569 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1570 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001572 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001573 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001574
1575 // Write the identifier table
1576 RecordData Record;
1577 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001578 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001579 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1580 &IdentifierTable.front(),
1581 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001582 }
1583
1584 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001585 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1586 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1587 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1588 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1589 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1590
1591 RecordData Record;
1592 Record.push_back(pch::IDENTIFIER_OFFSET);
1593 Record.push_back(IdentifierOffsets.size());
1594 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1595 (const char *)&IdentifierOffsets.front(),
1596 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001597}
1598
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001599//===----------------------------------------------------------------------===//
1600// General Serialization Routines
1601//===----------------------------------------------------------------------===//
1602
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001603/// \brief Write a record containing the given attributes.
1604void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1605 RecordData Record;
1606 for (; Attr; Attr = Attr->getNext()) {
1607 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1608 Record.push_back(Attr->isInherited());
1609 switch (Attr->getKind()) {
1610 case Attr::Alias:
1611 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1612 break;
1613
1614 case Attr::Aligned:
1615 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1616 break;
1617
1618 case Attr::AlwaysInline:
1619 break;
1620
1621 case Attr::AnalyzerNoReturn:
1622 break;
1623
1624 case Attr::Annotate:
1625 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1626 break;
1627
1628 case Attr::AsmLabel:
1629 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1630 break;
1631
1632 case Attr::Blocks:
1633 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1634 break;
1635
1636 case Attr::Cleanup:
1637 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1638 break;
1639
1640 case Attr::Const:
1641 break;
1642
1643 case Attr::Constructor:
1644 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1645 break;
1646
1647 case Attr::DLLExport:
1648 case Attr::DLLImport:
1649 case Attr::Deprecated:
1650 break;
1651
1652 case Attr::Destructor:
1653 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1654 break;
1655
1656 case Attr::FastCall:
1657 break;
1658
1659 case Attr::Format: {
1660 const FormatAttr *Format = cast<FormatAttr>(Attr);
1661 AddString(Format->getType(), Record);
1662 Record.push_back(Format->getFormatIdx());
1663 Record.push_back(Format->getFirstArg());
1664 break;
1665 }
1666
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001667 case Attr::FormatArg: {
1668 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1669 Record.push_back(Format->getFormatIdx());
1670 break;
1671 }
1672
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001673 case Attr::Sentinel : {
1674 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1675 Record.push_back(Sentinel->getSentinel());
1676 Record.push_back(Sentinel->getNullPos());
1677 break;
1678 }
1679
Chris Lattnercf2a7212009-04-20 19:12:28 +00001680 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001681 case Attr::IBOutletKind:
Ryan Flynn76168e22009-08-09 20:07:29 +00001682 case Attr::Malloc:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001683 case Attr::NoReturn:
1684 case Attr::NoThrow:
1685 case Attr::Nodebug:
1686 case Attr::Noinline:
1687 break;
1688
1689 case Attr::NonNull: {
1690 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1691 Record.push_back(NonNull->size());
1692 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1693 break;
1694 }
1695
1696 case Attr::ObjCException:
1697 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001698 case Attr::CFReturnsRetained:
1699 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001700 case Attr::Overloadable:
1701 break;
1702
Anders Carlssona860e752009-08-08 18:23:56 +00001703 case Attr::PragmaPack:
1704 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001705 break;
1706
Anders Carlssona860e752009-08-08 18:23:56 +00001707 case Attr::Packed:
1708 break;
1709
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001710 case Attr::Pure:
1711 break;
1712
1713 case Attr::Regparm:
1714 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1715 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001716
1717 case Attr::ReqdWorkGroupSize:
1718 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1719 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1720 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1721 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001722
1723 case Attr::Section:
1724 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1725 break;
1726
1727 case Attr::StdCall:
1728 case Attr::TransparentUnion:
1729 case Attr::Unavailable:
1730 case Attr::Unused:
1731 case Attr::Used:
1732 break;
1733
1734 case Attr::Visibility:
1735 // FIXME: stable encoding
1736 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1737 break;
1738
1739 case Attr::WarnUnusedResult:
1740 case Attr::Weak:
1741 case Attr::WeakImport:
1742 break;
1743 }
1744 }
1745
Douglas Gregorc9490c02009-04-16 22:23:12 +00001746 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001747}
1748
1749void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1750 Record.push_back(Str.size());
1751 Record.insert(Record.end(), Str.begin(), Str.end());
1752}
1753
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001754/// \brief Note that the identifier II occurs at the given offset
1755/// within the identifier table.
1756void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001757 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001758}
1759
Douglas Gregor83941df2009-04-25 17:48:32 +00001760/// \brief Note that the selector Sel occurs at the given offset
1761/// within the method pool/selector table.
1762void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1763 unsigned ID = SelectorIDs[Sel];
1764 assert(ID && "Unknown selector");
1765 SelectorOffsets[ID - 1] = Offset;
1766}
1767
Douglas Gregorc9490c02009-04-16 22:23:12 +00001768PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001769 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001770 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1771 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001772
Douglas Gregore650c8c2009-07-07 00:12:59 +00001773void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1774 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001775 using namespace llvm;
1776
Douglas Gregore7785042009-04-20 15:53:59 +00001777 ASTContext &Context = SemaRef.Context;
1778 Preprocessor &PP = SemaRef.PP;
1779
Douglas Gregor2cf26342009-04-09 22:27:44 +00001780 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001781 Stream.Emit((unsigned)'C', 8);
1782 Stream.Emit((unsigned)'P', 8);
1783 Stream.Emit((unsigned)'C', 8);
1784 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001785
1786 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001787
1788 // The translation unit is the first declaration we'll emit.
1789 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1790 DeclsToEmit.push(Context.getTranslationUnitDecl());
1791
Douglas Gregor2deaea32009-04-22 18:49:13 +00001792 // Make sure that we emit IdentifierInfos (and any attached
1793 // declarations) for builtins.
1794 {
1795 IdentifierTable &Table = PP.getIdentifierTable();
1796 llvm::SmallVector<const char *, 32> BuiltinNames;
1797 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1798 Context.getLangOptions().NoBuiltin);
1799 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1800 getIdentifierRef(&Table.get(BuiltinNames[I]));
1801 }
1802
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001803 // Build a record containing all of the tentative definitions in
1804 // this header file. Generally, this record will be empty.
1805 RecordData TentativeDefinitions;
1806 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1807 TD = SemaRef.TentativeDefinitions.begin(),
1808 TDEnd = SemaRef.TentativeDefinitions.end();
1809 TD != TDEnd; ++TD)
1810 AddDeclRef(TD->second, TentativeDefinitions);
1811
Douglas Gregor14c22f22009-04-22 22:18:58 +00001812 // Build a record containing all of the locally-scoped external
1813 // declarations in this header file. Generally, this record will be
1814 // empty.
1815 RecordData LocallyScopedExternalDecls;
1816 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1817 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1818 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1819 TD != TDEnd; ++TD)
1820 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1821
Douglas Gregorb81c1702009-04-27 20:06:05 +00001822 // Build a record containing all of the ext_vector declarations.
1823 RecordData ExtVectorDecls;
1824 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1825 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1826
Douglas Gregor2cf26342009-04-09 22:27:44 +00001827 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001828 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001829 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001830 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001831 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001832 if (StatCalls && !isysroot)
1833 WriteStatCache(*StatCalls, isysroot);
1834 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001835 WritePreprocessor(PP);
Douglas Gregor2e222532009-07-02 17:08:52 +00001836 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001837 // Write the record of special types.
1838 Record.clear();
1839
1840 AddTypeRef(Context.getBuiltinVaListType(), Record);
1841 AddTypeRef(Context.getObjCIdType(), Record);
1842 AddTypeRef(Context.getObjCSelType(), Record);
1843 AddTypeRef(Context.getObjCProtoType(), Record);
1844 AddTypeRef(Context.getObjCClassType(), Record);
1845 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1846 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1847 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001848 AddTypeRef(Context.getjmp_bufType(), Record);
1849 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregord1571ac2009-08-21 00:27:50 +00001850 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1851 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001852 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Douglas Gregor2e222532009-07-02 17:08:52 +00001853
Douglas Gregor366809a2009-04-26 03:49:13 +00001854 // Keep writing types and declarations until all types and
1855 // declarations have been written.
1856 do {
1857 if (!DeclsToEmit.empty())
1858 WriteDeclsBlock(Context);
1859 if (!TypesToEmit.empty())
1860 WriteTypesBlock(Context);
1861 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1862
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001863 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001864 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001865
1866 // Write the type offsets array
1867 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1868 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1871 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1872 Record.clear();
1873 Record.push_back(pch::TYPE_OFFSET);
1874 Record.push_back(TypeOffsets.size());
1875 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1876 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001877 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001878
1879 // Write the declaration offsets array
1880 Abbrev = new BitCodeAbbrev();
1881 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1882 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1884 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1885 Record.clear();
1886 Record.push_back(pch::DECL_OFFSET);
1887 Record.push_back(DeclOffsets.size());
1888 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1889 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001890 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001891
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001892 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001893 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001894 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001895
1896 // Write the record containing tentative definitions.
1897 if (!TentativeDefinitions.empty())
1898 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001899
1900 // Write the record containing locally-scoped external definitions.
1901 if (!LocallyScopedExternalDecls.empty())
1902 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1903 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001904
1905 // Write the record containing ext_vector type names.
1906 if (!ExtVectorDecls.empty())
1907 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001908
1909 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001910 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001911 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001912 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001913 Record.push_back(NumLexicalDeclContexts);
1914 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001915 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001916 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001917}
1918
1919void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1920 Record.push_back(Loc.getRawEncoding());
1921}
1922
1923void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1924 Record.push_back(Value.getBitWidth());
1925 unsigned N = Value.getNumWords();
1926 const uint64_t* Words = Value.getRawData();
1927 for (unsigned I = 0; I != N; ++I)
1928 Record.push_back(Words[I]);
1929}
1930
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001931void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1932 Record.push_back(Value.isUnsigned());
1933 AddAPInt(Value, Record);
1934}
1935
Douglas Gregor17fc2232009-04-14 21:55:33 +00001936void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1937 AddAPInt(Value.bitcastToAPInt(), Record);
1938}
1939
Douglas Gregor2cf26342009-04-09 22:27:44 +00001940void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001941 Record.push_back(getIdentifierRef(II));
1942}
1943
1944pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1945 if (II == 0)
1946 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001947
1948 pch::IdentID &ID = IdentifierIDs[II];
1949 if (ID == 0)
1950 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001951 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001952}
1953
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001954void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1955 if (SelRef.getAsOpaquePtr() == 0) {
1956 Record.push_back(0);
1957 return;
1958 }
1959
1960 pch::SelectorID &SID = SelectorIDs[SelRef];
1961 if (SID == 0) {
1962 SID = SelectorIDs.size();
1963 SelVector.push_back(SelRef);
1964 }
1965 Record.push_back(SID);
1966}
1967
Douglas Gregor2cf26342009-04-09 22:27:44 +00001968void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1969 if (T.isNull()) {
1970 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1971 return;
1972 }
1973
1974 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001975 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001976 switch (BT->getKind()) {
1977 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1978 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1979 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1980 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1981 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1982 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1983 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1984 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001985 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001986 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1987 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1988 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1989 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1990 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1991 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1992 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001993 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001994 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1995 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1996 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001997 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001998 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
1999 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2001 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002002 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2003 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002004 case BuiltinType::UndeducedAuto:
2005 assert(0 && "Should not see undeduced auto here");
2006 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002007 }
2008
2009 Record.push_back((ID << 3) | T.getCVRQualifiers());
2010 return;
2011 }
2012
Douglas Gregor8038d512009-04-10 17:25:41 +00002013 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00002014 if (ID == 0) {
2015 // We haven't seen this type before. Assign it a new ID and put it
2016 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002017 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00002018 TypesToEmit.push(T.getTypePtr());
2019 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020
2021 // Encode the type qualifiers in the type reference.
2022 Record.push_back((ID << 3) | T.getCVRQualifiers());
2023}
2024
2025void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2026 if (D == 0) {
2027 Record.push_back(0);
2028 return;
2029 }
2030
Douglas Gregor8038d512009-04-10 17:25:41 +00002031 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002032 if (ID == 0) {
2033 // We haven't seen this declaration before. Give it a new ID and
2034 // enqueue it in the list of declarations to emit.
2035 ID = DeclIDs.size();
2036 DeclsToEmit.push(const_cast<Decl *>(D));
2037 }
2038
2039 Record.push_back(ID);
2040}
2041
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002042pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2043 if (D == 0)
2044 return 0;
2045
2046 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2047 return DeclIDs[D];
2048}
2049
Douglas Gregor2cf26342009-04-09 22:27:44 +00002050void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002051 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002052 Record.push_back(Name.getNameKind());
2053 switch (Name.getNameKind()) {
2054 case DeclarationName::Identifier:
2055 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2056 break;
2057
2058 case DeclarationName::ObjCZeroArgSelector:
2059 case DeclarationName::ObjCOneArgSelector:
2060 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002061 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002062 break;
2063
2064 case DeclarationName::CXXConstructorName:
2065 case DeclarationName::CXXDestructorName:
2066 case DeclarationName::CXXConversionFunctionName:
2067 AddTypeRef(Name.getCXXNameType(), Record);
2068 break;
2069
2070 case DeclarationName::CXXOperatorName:
2071 Record.push_back(Name.getCXXOverloadedOperator());
2072 break;
2073
2074 case DeclarationName::CXXUsingDirective:
2075 // No extra data to emit
2076 break;
2077 }
2078}
Douglas Gregor0b748912009-04-14 21:18:50 +00002079