blob: 8ff688e6e3678b055763deda170a205834c17349 [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 Gregor17fc2232009-04-14 21:55:33 +000030#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamWriter.h"
33#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000034#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000035#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
39// Type serialization
40//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000041
Douglas Gregor2cf26342009-04-09 22:27:44 +000042namespace {
43 class VISIBILITY_HIDDEN PCHTypeWriter {
44 PCHWriter &Writer;
45 PCHWriter::RecordData &Record;
46
47 public:
48 /// \brief Type code that corresponds to the record generated.
49 pch::TypeCode Code;
50
51 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor4fed3f42009-04-27 18:38:38 +000052 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000053
54 void VisitArrayType(const ArrayType *T);
55 void VisitFunctionType(const FunctionType *T);
56 void VisitTagType(const TagType *T);
57
58#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
59#define ABSTRACT_TYPE(Class, Base)
60#define DEPENDENT_TYPE(Class, Base)
61#include "clang/AST/TypeNodes.def"
62 };
63}
64
65void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
66 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
67 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
68 Record.push_back(T->getAddressSpace());
69 Code = pch::TYPE_EXT_QUAL;
70}
71
72void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
73 assert(false && "Built-in types are never serialized");
74}
75
76void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
77 Record.push_back(T->getWidth());
78 Record.push_back(T->isSigned());
79 Code = pch::TYPE_FIXED_WIDTH_INT;
80}
81
82void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
83 Writer.AddTypeRef(T->getElementType(), Record);
84 Code = pch::TYPE_COMPLEX;
85}
86
87void PCHTypeWriter::VisitPointerType(const PointerType *T) {
88 Writer.AddTypeRef(T->getPointeeType(), Record);
89 Code = pch::TYPE_POINTER;
90}
91
92void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_BLOCK_POINTER;
95}
96
97void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Code = pch::TYPE_LVALUE_REFERENCE;
100}
101
102void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Code = pch::TYPE_RVALUE_REFERENCE;
105}
106
107void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
108 Writer.AddTypeRef(T->getPointeeType(), Record);
109 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
110 Code = pch::TYPE_MEMBER_POINTER;
111}
112
113void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
114 Writer.AddTypeRef(T->getElementType(), Record);
115 Record.push_back(T->getSizeModifier()); // FIXME: stable values
116 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
117}
118
119void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
120 VisitArrayType(T);
121 Writer.AddAPInt(T->getSize(), Record);
122 Code = pch::TYPE_CONSTANT_ARRAY;
123}
124
125void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
126 VisitArrayType(T);
127 Code = pch::TYPE_INCOMPLETE_ARRAY;
128}
129
130void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
131 VisitArrayType(T);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000132 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133 Code = pch::TYPE_VARIABLE_ARRAY;
134}
135
136void PCHTypeWriter::VisitVectorType(const VectorType *T) {
137 Writer.AddTypeRef(T->getElementType(), Record);
138 Record.push_back(T->getNumElements());
139 Code = pch::TYPE_VECTOR;
140}
141
142void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
143 VisitVectorType(T);
144 Code = pch::TYPE_EXT_VECTOR;
145}
146
147void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
148 Writer.AddTypeRef(T->getResultType(), Record);
149}
150
151void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
152 VisitFunctionType(T);
153 Code = pch::TYPE_FUNCTION_NO_PROTO;
154}
155
156void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
157 VisitFunctionType(T);
158 Record.push_back(T->getNumArgs());
159 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
160 Writer.AddTypeRef(T->getArgType(I), Record);
161 Record.push_back(T->isVariadic());
162 Record.push_back(T->getTypeQuals());
163 Code = pch::TYPE_FUNCTION_PROTO;
164}
165
166void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
167 Writer.AddDeclRef(T->getDecl(), Record);
168 Code = pch::TYPE_TYPEDEF;
169}
170
171void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000172 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000173 Code = pch::TYPE_TYPEOF_EXPR;
174}
175
176void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
177 Writer.AddTypeRef(T->getUnderlyingType(), Record);
178 Code = pch::TYPE_TYPEOF;
179}
180
181void PCHTypeWriter::VisitTagType(const TagType *T) {
182 Writer.AddDeclRef(T->getDecl(), Record);
183 assert(!T->isBeingDefined() &&
184 "Cannot serialize in the middle of a type definition");
185}
186
187void PCHTypeWriter::VisitRecordType(const RecordType *T) {
188 VisitTagType(T);
189 Code = pch::TYPE_RECORD;
190}
191
192void PCHTypeWriter::VisitEnumType(const EnumType *T) {
193 VisitTagType(T);
194 Code = pch::TYPE_ENUM;
195}
196
197void
198PCHTypeWriter::VisitTemplateSpecializationType(
199 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000200 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000201 assert(false && "Cannot serialize template specialization types");
202}
203
204void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000205 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000206 assert(false && "Cannot serialize qualified name types");
207}
208
209void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
210 Writer.AddDeclRef(T->getDecl(), Record);
211 Code = pch::TYPE_OBJC_INTERFACE;
212}
213
214void
215PCHTypeWriter::VisitObjCQualifiedInterfaceType(
216 const ObjCQualifiedInterfaceType *T) {
217 VisitObjCInterfaceType(T);
218 Record.push_back(T->getNumProtocols());
219 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
220 Writer.AddDeclRef(T->getProtocol(I), Record);
221 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
222}
223
224void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
225 Record.push_back(T->getNumProtocols());
226 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
227 Writer.AddDeclRef(T->getProtocols(I), Record);
228 Code = pch::TYPE_OBJC_QUALIFIED_ID;
229}
230
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000231//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000232// PCHWriter Implementation
233//===----------------------------------------------------------------------===//
234
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000235static void EmitBlockID(unsigned ID, const char *Name,
236 llvm::BitstreamWriter &Stream,
237 PCHWriter::RecordData &Record) {
238 Record.clear();
239 Record.push_back(ID);
240 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
241
242 // Emit the block name if present.
243 if (Name == 0 || Name[0] == 0) return;
244 Record.clear();
245 while (*Name)
246 Record.push_back(*Name++);
247 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
248}
249
250static void EmitRecordID(unsigned ID, const char *Name,
251 llvm::BitstreamWriter &Stream,
252 PCHWriter::RecordData &Record) {
253 Record.clear();
254 Record.push_back(ID);
255 while (*Name)
256 Record.push_back(*Name++);
257 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000258}
259
260static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
261 PCHWriter::RecordData &Record) {
262#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
263 RECORD(STMT_STOP);
264 RECORD(STMT_NULL_PTR);
265 RECORD(STMT_NULL);
266 RECORD(STMT_COMPOUND);
267 RECORD(STMT_CASE);
268 RECORD(STMT_DEFAULT);
269 RECORD(STMT_LABEL);
270 RECORD(STMT_IF);
271 RECORD(STMT_SWITCH);
272 RECORD(STMT_WHILE);
273 RECORD(STMT_DO);
274 RECORD(STMT_FOR);
275 RECORD(STMT_GOTO);
276 RECORD(STMT_INDIRECT_GOTO);
277 RECORD(STMT_CONTINUE);
278 RECORD(STMT_BREAK);
279 RECORD(STMT_RETURN);
280 RECORD(STMT_DECL);
281 RECORD(STMT_ASM);
282 RECORD(EXPR_PREDEFINED);
283 RECORD(EXPR_DECL_REF);
284 RECORD(EXPR_INTEGER_LITERAL);
285 RECORD(EXPR_FLOATING_LITERAL);
286 RECORD(EXPR_IMAGINARY_LITERAL);
287 RECORD(EXPR_STRING_LITERAL);
288 RECORD(EXPR_CHARACTER_LITERAL);
289 RECORD(EXPR_PAREN);
290 RECORD(EXPR_UNARY_OPERATOR);
291 RECORD(EXPR_SIZEOF_ALIGN_OF);
292 RECORD(EXPR_ARRAY_SUBSCRIPT);
293 RECORD(EXPR_CALL);
294 RECORD(EXPR_MEMBER);
295 RECORD(EXPR_BINARY_OPERATOR);
296 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
297 RECORD(EXPR_CONDITIONAL_OPERATOR);
298 RECORD(EXPR_IMPLICIT_CAST);
299 RECORD(EXPR_CSTYLE_CAST);
300 RECORD(EXPR_COMPOUND_LITERAL);
301 RECORD(EXPR_EXT_VECTOR_ELEMENT);
302 RECORD(EXPR_INIT_LIST);
303 RECORD(EXPR_DESIGNATED_INIT);
304 RECORD(EXPR_IMPLICIT_VALUE_INIT);
305 RECORD(EXPR_VA_ARG);
306 RECORD(EXPR_ADDR_LABEL);
307 RECORD(EXPR_STMT);
308 RECORD(EXPR_TYPES_COMPATIBLE);
309 RECORD(EXPR_CHOOSE);
310 RECORD(EXPR_GNU_NULL);
311 RECORD(EXPR_SHUFFLE_VECTOR);
312 RECORD(EXPR_BLOCK);
313 RECORD(EXPR_BLOCK_DECL_REF);
314 RECORD(EXPR_OBJC_STRING_LITERAL);
315 RECORD(EXPR_OBJC_ENCODE);
316 RECORD(EXPR_OBJC_SELECTOR_EXPR);
317 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
318 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
319 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
320 RECORD(EXPR_OBJC_KVC_REF_EXPR);
321 RECORD(EXPR_OBJC_MESSAGE_EXPR);
322 RECORD(EXPR_OBJC_SUPER_EXPR);
323 RECORD(STMT_OBJC_FOR_COLLECTION);
324 RECORD(STMT_OBJC_CATCH);
325 RECORD(STMT_OBJC_FINALLY);
326 RECORD(STMT_OBJC_AT_TRY);
327 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
328 RECORD(STMT_OBJC_AT_THROW);
329#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000330}
331
332void PCHWriter::WriteBlockInfoBlock() {
333 RecordData Record;
334 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
335
Chris Lattner2f4efd12009-04-27 00:40:25 +0000336#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000337#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
338
339 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000340 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000341 RECORD(TYPE_OFFSET);
342 RECORD(DECL_OFFSET);
343 RECORD(LANGUAGE_OPTIONS);
344 RECORD(TARGET_TRIPLE);
345 RECORD(IDENTIFIER_OFFSET);
346 RECORD(IDENTIFIER_TABLE);
347 RECORD(EXTERNAL_DEFINITIONS);
348 RECORD(SPECIAL_TYPES);
349 RECORD(STATISTICS);
350 RECORD(TENTATIVE_DEFINITIONS);
351 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
352 RECORD(SELECTOR_OFFSETS);
353 RECORD(METHOD_POOL);
354 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000355 RECORD(SOURCE_LOCATION_OFFSETS);
356 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000357 RECORD(STAT_CACHE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000358
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000359 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000360 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000361 RECORD(SM_SLOC_FILE_ENTRY);
362 RECORD(SM_SLOC_BUFFER_ENTRY);
363 RECORD(SM_SLOC_BUFFER_BLOB);
364 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
365 RECORD(SM_LINE_TABLE);
366 RECORD(SM_HEADER_FILE_INFO);
367
368 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000369 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000370 RECORD(PP_MACRO_OBJECT_LIKE);
371 RECORD(PP_MACRO_FUNCTION_LIKE);
372 RECORD(PP_TOKEN);
373
374 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000375 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000376 RECORD(TYPE_EXT_QUAL);
377 RECORD(TYPE_FIXED_WIDTH_INT);
378 RECORD(TYPE_COMPLEX);
379 RECORD(TYPE_POINTER);
380 RECORD(TYPE_BLOCK_POINTER);
381 RECORD(TYPE_LVALUE_REFERENCE);
382 RECORD(TYPE_RVALUE_REFERENCE);
383 RECORD(TYPE_MEMBER_POINTER);
384 RECORD(TYPE_CONSTANT_ARRAY);
385 RECORD(TYPE_INCOMPLETE_ARRAY);
386 RECORD(TYPE_VARIABLE_ARRAY);
387 RECORD(TYPE_VECTOR);
388 RECORD(TYPE_EXT_VECTOR);
389 RECORD(TYPE_FUNCTION_PROTO);
390 RECORD(TYPE_FUNCTION_NO_PROTO);
391 RECORD(TYPE_TYPEDEF);
392 RECORD(TYPE_TYPEOF_EXPR);
393 RECORD(TYPE_TYPEOF);
394 RECORD(TYPE_RECORD);
395 RECORD(TYPE_ENUM);
396 RECORD(TYPE_OBJC_INTERFACE);
397 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
398 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000399 // Statements and Exprs can occur in the Types block.
400 AddStmtsExprs(Stream, Record);
401
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000402 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000403 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000404 RECORD(DECL_ATTR);
405 RECORD(DECL_TRANSLATION_UNIT);
406 RECORD(DECL_TYPEDEF);
407 RECORD(DECL_ENUM);
408 RECORD(DECL_RECORD);
409 RECORD(DECL_ENUM_CONSTANT);
410 RECORD(DECL_FUNCTION);
411 RECORD(DECL_OBJC_METHOD);
412 RECORD(DECL_OBJC_INTERFACE);
413 RECORD(DECL_OBJC_PROTOCOL);
414 RECORD(DECL_OBJC_IVAR);
415 RECORD(DECL_OBJC_AT_DEFS_FIELD);
416 RECORD(DECL_OBJC_CLASS);
417 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
418 RECORD(DECL_OBJC_CATEGORY);
419 RECORD(DECL_OBJC_CATEGORY_IMPL);
420 RECORD(DECL_OBJC_IMPLEMENTATION);
421 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
422 RECORD(DECL_OBJC_PROPERTY);
423 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000424 RECORD(DECL_FIELD);
425 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000426 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000427 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000428 RECORD(DECL_ORIGINAL_PARM_VAR);
429 RECORD(DECL_FILE_SCOPE_ASM);
430 RECORD(DECL_BLOCK);
431 RECORD(DECL_CONTEXT_LEXICAL);
432 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000433 // Statements and Exprs can occur in the Decls block.
434 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000435#undef RECORD
436#undef BLOCK
437 Stream.ExitBlock();
438}
439
440
Douglas Gregor2bec0412009-04-10 21:16:55 +0000441/// \brief Write the target triple (e.g., i686-apple-darwin9).
442void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
443 using namespace llvm;
444 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
445 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
446 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000447 unsigned TripleAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000448
449 RecordData Record;
450 Record.push_back(pch::TARGET_TRIPLE);
451 const char *Triple = Target.getTargetTriple();
Douglas Gregorc9490c02009-04-16 22:23:12 +0000452 Stream.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000453}
454
455/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000456void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
457 RecordData Record;
458 Record.push_back(LangOpts.Trigraphs);
459 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
460 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
461 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
462 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
463 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
464 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
465 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
466 Record.push_back(LangOpts.C99); // C99 Support
467 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
468 Record.push_back(LangOpts.CPlusPlus); // C++ Support
469 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
470 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
471 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
472
473 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
474 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
475 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
476
477 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
478 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
479 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
480 Record.push_back(LangOpts.LaxVectorConversions);
481 Record.push_back(LangOpts.Exceptions); // Support exception handling.
482
483 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
484 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
485 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
486
Chris Lattnerea5ce472009-04-27 07:35:58 +0000487 // Whether static initializers are protected by locks.
488 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000489 Record.push_back(LangOpts.Blocks); // block extension to C
490 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
491 // they are unused.
492 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
493 // (modulo the platform support).
494
495 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
496 // signed integer arithmetic overflows.
497
498 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
499 // may be ripped out at any time.
500
501 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
502 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
503 // defined.
504 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
505 // opposed to __DYNAMIC__).
506 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
507
508 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
509 // used (instead of C99 semantics).
510 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
511 Record.push_back(LangOpts.getGCMode());
512 Record.push_back(LangOpts.getVisibilityMode());
513 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000514 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000515}
516
Douglas Gregor14f79002009-04-10 03:52:48 +0000517//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000518// stat cache Serialization
519//===----------------------------------------------------------------------===//
520
521namespace {
522// Trait used for the on-disk hash table of stat cache results.
523class VISIBILITY_HIDDEN PCHStatCacheTrait {
524public:
525 typedef const char * key_type;
526 typedef key_type key_type_ref;
527
528 typedef std::pair<int, struct stat> data_type;
529 typedef const data_type& data_type_ref;
530
531 static unsigned ComputeHash(const char *path) {
532 return BernsteinHash(path);
533 }
534
535 std::pair<unsigned,unsigned>
536 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
537 data_type_ref Data) {
538 unsigned StrLen = strlen(path);
539 clang::io::Emit16(Out, StrLen);
540 unsigned DataLen = 1; // result value
541 if (Data.first == 0)
542 DataLen += 4 + 4 + 2 + 8 + 8;
543 clang::io::Emit8(Out, DataLen);
544 return std::make_pair(StrLen + 1, DataLen);
545 }
546
547 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
548 Out.write(path, KeyLen);
549 }
550
551 void EmitData(llvm::raw_ostream& Out, key_type_ref,
552 data_type_ref Data, unsigned DataLen) {
553 using namespace clang::io;
554 uint64_t Start = Out.tell(); (void)Start;
555
556 // Result of stat()
557 Emit8(Out, Data.first? 1 : 0);
558
559 if (Data.first == 0) {
560 Emit32(Out, (uint32_t) Data.second.st_ino);
561 Emit32(Out, (uint32_t) Data.second.st_dev);
562 Emit16(Out, (uint16_t) Data.second.st_mode);
563 Emit64(Out, (uint64_t) Data.second.st_mtime);
564 Emit64(Out, (uint64_t) Data.second.st_size);
565 }
566
567 assert(Out.tell() - Start == DataLen && "Wrong data length");
568 }
569};
570} // end anonymous namespace
571
572/// \brief Write the stat() system call cache to the PCH file.
573void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
574 // Build the on-disk hash table containing information about every
575 // stat() call.
576 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
577 unsigned NumStatEntries = 0;
578 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
579 StatEnd = StatCalls.end();
580 Stat != StatEnd; ++Stat, ++NumStatEntries)
581 Generator.insert(Stat->first(), Stat->second);
582
583 // Create the on-disk hash table in a buffer.
584 llvm::SmallVector<char, 4096> StatCacheData;
585 uint32_t BucketOffset;
586 {
587 llvm::raw_svector_ostream Out(StatCacheData);
588 // Make sure that no bucket is at offset 0
589 clang::io::Emit32(Out, 0);
590 BucketOffset = Generator.Emit(Out);
591 }
592
593 // Create a blob abbreviation
594 using namespace llvm;
595 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
596 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
600 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
601
602 // Write the stat cache
603 RecordData Record;
604 Record.push_back(pch::STAT_CACHE);
605 Record.push_back(BucketOffset);
606 Record.push_back(NumStatEntries);
607 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
608 &StatCacheData.front(),
609 StatCacheData.size());
610}
611
612//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000613// Source Manager Serialization
614//===----------------------------------------------------------------------===//
615
616/// \brief Create an abbreviation for the SLocEntry that refers to a
617/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000618static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000619 using namespace llvm;
620 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
621 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
622 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
623 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
624 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
625 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000627 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000628}
629
630/// \brief Create an abbreviation for the SLocEntry that refers to a
631/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000632static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000633 using namespace llvm;
634 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
635 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
638 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000641 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000642}
643
644/// \brief Create an abbreviation for the SLocEntry that refers to a
645/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000646static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000647 using namespace llvm;
648 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
649 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000651 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000652}
653
654/// \brief Create an abbreviation for the SLocEntry that refers to an
655/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000656static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000657 using namespace llvm;
658 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
659 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000665 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000666}
667
668/// \brief Writes the block containing the serialized form of the
669/// source manager.
670///
671/// TODO: We should probably use an on-disk hash table (stored in a
672/// blob), indexed based on the file name, so that we only create
673/// entries for files that we actually need. In the common case (no
674/// errors), we probably won't have to create file entries for any of
675/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000676void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
677 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000678 RecordData Record;
679
Chris Lattnerf04ad692009-04-10 17:16:57 +0000680 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000681 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000682
683 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000684 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
685 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
686 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
687 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000688
Douglas Gregorbd945002009-04-13 16:31:14 +0000689 // Write the line table.
690 if (SourceMgr.hasLineTable()) {
691 LineTableInfo &LineTable = SourceMgr.getLineTable();
692
693 // Emit the file names
694 Record.push_back(LineTable.getNumFilenames());
695 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
696 // Emit the file name
697 const char *Filename = LineTable.getFilename(I);
698 unsigned FilenameLen = Filename? strlen(Filename) : 0;
699 Record.push_back(FilenameLen);
700 if (FilenameLen)
701 Record.insert(Record.end(), Filename, Filename + FilenameLen);
702 }
703
704 // Emit the line entries
705 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
706 L != LEnd; ++L) {
707 // Emit the file ID
708 Record.push_back(L->first);
709
710 // Emit the line entries
711 Record.push_back(L->second.size());
712 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
713 LEEnd = L->second.end();
714 LE != LEEnd; ++LE) {
715 Record.push_back(LE->FileOffset);
716 Record.push_back(LE->LineNo);
717 Record.push_back(LE->FilenameID);
718 Record.push_back((unsigned)LE->FileKind);
719 Record.push_back(LE->IncludeOffset);
720 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000721 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000722 }
723 }
724
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000725 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000726 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000727 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000728 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
729 E = HS.header_file_end();
730 I != E; ++I) {
731 Record.push_back(I->isImport);
732 Record.push_back(I->DirInfo);
733 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000734 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000735 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
736 Record.clear();
737 }
738
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000739 // Write out the source location entry table. We skip the first
740 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000741 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000742 RecordData PreloadSLocs;
743 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
744 for (SourceManager::sloc_entry_iterator
745 SLoc = SourceMgr.sloc_entry_begin() + 1,
746 SLocEnd = SourceMgr.sloc_entry_end();
747 SLoc != SLocEnd; ++SLoc) {
748 // Record the offset of this source-location entry.
749 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
750
751 // Figure out which record code to use.
752 unsigned Code;
753 if (SLoc->isFile()) {
754 if (SLoc->getFile().getContentCache()->Entry)
755 Code = pch::SM_SLOC_FILE_ENTRY;
756 else
757 Code = pch::SM_SLOC_BUFFER_ENTRY;
758 } else
759 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
760 Record.clear();
761 Record.push_back(Code);
762
763 Record.push_back(SLoc->getOffset());
764 if (SLoc->isFile()) {
765 const SrcMgr::FileInfo &File = SLoc->getFile();
766 Record.push_back(File.getIncludeLoc().getRawEncoding());
767 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
768 Record.push_back(File.hasLineDirectives());
769
770 const SrcMgr::ContentCache *Content = File.getContentCache();
771 if (Content->Entry) {
772 // The source location entry is a file. The blob associated
773 // with this entry is the file name.
774 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
775 Content->Entry->getName(),
776 strlen(Content->Entry->getName()));
777
778 // FIXME: For now, preload all file source locations, so that
779 // we get the appropriate File entries in the reader. This is
780 // a temporary measure.
781 PreloadSLocs.push_back(SLocEntryOffsets.size());
782 } else {
783 // The source location entry is a buffer. The blob associated
784 // with this entry contains the contents of the buffer.
785
786 // We add one to the size so that we capture the trailing NULL
787 // that is required by llvm::MemoryBuffer::getMemBuffer (on
788 // the reader side).
789 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
790 const char *Name = Buffer->getBufferIdentifier();
791 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
792 Record.clear();
793 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
794 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
795 Buffer->getBufferStart(),
796 Buffer->getBufferSize() + 1);
797
798 if (strcmp(Name, "<built-in>") == 0)
799 PreloadSLocs.push_back(SLocEntryOffsets.size());
800 }
801 } else {
802 // The source location entry is an instantiation.
803 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
804 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
805 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
806 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
807
808 // Compute the token length for this macro expansion.
809 unsigned NextOffset = SourceMgr.getNextOffset();
810 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
811 if (++NextSLoc != SLocEnd)
812 NextOffset = NextSLoc->getOffset();
813 Record.push_back(NextOffset - SLoc->getOffset() - 1);
814 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
815 }
816 }
817
Douglas Gregorc9490c02009-04-16 22:23:12 +0000818 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000819
820 if (SLocEntryOffsets.empty())
821 return;
822
823 // Write the source-location offsets table into the PCH block. This
824 // table is used for lazily loading source-location information.
825 using namespace llvm;
826 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
827 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
828 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
829 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
831 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
832
833 Record.clear();
834 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
835 Record.push_back(SLocEntryOffsets.size());
836 Record.push_back(SourceMgr.getNextOffset());
837 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
838 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000839 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000840
841 // Write the source location entry preloads array, telling the PCH
842 // reader which source locations entries it should load eagerly.
843 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000844}
845
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000846//===----------------------------------------------------------------------===//
847// Preprocessor Serialization
848//===----------------------------------------------------------------------===//
849
Chris Lattner0b1fb982009-04-10 17:15:23 +0000850/// \brief Writes the block containing the serialized form of the
851/// preprocessor.
852///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000853void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000854 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000855
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000856 // If the preprocessor __COUNTER__ value has been bumped, remember it.
857 if (PP.getCounterValue() != 0) {
858 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000859 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000860 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000861 }
862
863 // Enter the preprocessor block.
864 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000865
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000866 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
867 // FIXME: use diagnostics subsystem for localization etc.
868 if (PP.SawDateOrTime())
869 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
870
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000871 // Loop over all the macro definitions that are live at the end of the file,
872 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000873 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
874 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000875 // FIXME: This emits macros in hash table order, we should do it in a stable
876 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000877 MacroInfo *MI = I->second;
878
879 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
880 // been redefined by the header (in which case they are not isBuiltinMacro).
881 if (MI->isBuiltinMacro())
882 continue;
883
Douglas Gregor37e26842009-04-21 23:56:24 +0000884 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000885 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000886 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000887 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
888 Record.push_back(MI->isUsed());
889
890 unsigned Code;
891 if (MI->isObjectLike()) {
892 Code = pch::PP_MACRO_OBJECT_LIKE;
893 } else {
894 Code = pch::PP_MACRO_FUNCTION_LIKE;
895
896 Record.push_back(MI->isC99Varargs());
897 Record.push_back(MI->isGNUVarargs());
898 Record.push_back(MI->getNumArgs());
899 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
900 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000901 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000902 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000903 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000904 Record.clear();
905
Chris Lattnerdf961c22009-04-10 18:08:30 +0000906 // Emit the tokens array.
907 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
908 // Note that we know that the preprocessor does not have any annotation
909 // tokens in it because they are created by the parser, and thus can't be
910 // in a macro definition.
911 const Token &Tok = MI->getReplacementToken(TokNo);
912
913 Record.push_back(Tok.getLocation().getRawEncoding());
914 Record.push_back(Tok.getLength());
915
Chris Lattnerdf961c22009-04-10 18:08:30 +0000916 // FIXME: When reading literal tokens, reconstruct the literal pointer if
917 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000918 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000919
920 // FIXME: Should translate token kind to a stable encoding.
921 Record.push_back(Tok.getKind());
922 // FIXME: Should translate token flags to a stable encoding.
923 Record.push_back(Tok.getFlags());
924
Douglas Gregorc9490c02009-04-16 22:23:12 +0000925 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000926 Record.clear();
927 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000928 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000929 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000930 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000931}
932
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000933//===----------------------------------------------------------------------===//
934// Type Serialization
935//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000936
Douglas Gregor2cf26342009-04-09 22:27:44 +0000937/// \brief Write the representation of a type to the PCH stream.
938void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000939 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000940 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000941 ID = NextTypeID++;
942
943 // Record the offset for this type.
944 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000945 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000946 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
947 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000948 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000949 }
950
951 RecordData Record;
952
953 // Emit the type's representation.
954 PCHTypeWriter W(*this, Record);
955 switch (T->getTypeClass()) {
956 // For all of the concrete, non-dependent types, call the
957 // appropriate visitor function.
958#define TYPE(Class, Base) \
959 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
960#define ABSTRACT_TYPE(Class, Base)
961#define DEPENDENT_TYPE(Class, Base)
962#include "clang/AST/TypeNodes.def"
963
964 // For all of the dependent type nodes (which only occur in C++
965 // templates), produce an error.
966#define TYPE(Class, Base)
967#define DEPENDENT_TYPE(Class, Base) case Type::Class:
968#include "clang/AST/TypeNodes.def"
969 assert(false && "Cannot serialize dependent type nodes");
970 break;
971 }
972
973 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000974 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +0000975
976 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000977 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000978}
979
980/// \brief Write a block containing all of the types.
981void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000982 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000983 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000984
Douglas Gregor366809a2009-04-26 03:49:13 +0000985 // Emit all of the types that need to be emitted (so far).
986 while (!TypesToEmit.empty()) {
987 const Type *T = TypesToEmit.front();
988 TypesToEmit.pop();
989 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
990 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000991 }
992
993 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +0000994 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000995}
996
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000997//===----------------------------------------------------------------------===//
998// Declaration Serialization
999//===----------------------------------------------------------------------===//
1000
Douglas Gregor2cf26342009-04-09 22:27:44 +00001001/// \brief Write the block containing all of the declaration IDs
1002/// lexically declared within the given DeclContext.
1003///
1004/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1005/// bistream, or 0 if no block was written.
1006uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1007 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001008 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001009 return 0;
1010
Douglas Gregorc9490c02009-04-16 22:23:12 +00001011 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001012 RecordData Record;
1013 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1014 DEnd = DC->decls_end(Context);
1015 D != DEnd; ++D)
1016 AddDeclRef(*D, Record);
1017
Douglas Gregor25123082009-04-22 22:34:57 +00001018 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001019 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001020 return Offset;
1021}
1022
1023/// \brief Write the block containing all of the declaration IDs
1024/// visible from the given DeclContext.
1025///
1026/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1027/// bistream, or 0 if no block was written.
1028uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1029 DeclContext *DC) {
1030 if (DC->getPrimaryContext() != DC)
1031 return 0;
1032
Douglas Gregoraff22df2009-04-21 22:32:33 +00001033 // Since there is no name lookup into functions or methods, and we
1034 // perform name lookup for the translation unit via the
1035 // IdentifierInfo chains, don't bother to build a
1036 // visible-declarations table for these entities.
1037 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001038 return 0;
1039
Douglas Gregor2cf26342009-04-09 22:27:44 +00001040 // Force the DeclContext to build a its name-lookup table.
1041 DC->lookup(Context, DeclarationName());
1042
1043 // Serialize the contents of the mapping used for lookup. Note that,
1044 // although we have two very different code paths, the serialized
1045 // representation is the same for both cases: a declaration name,
1046 // followed by a size, followed by references to the visible
1047 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001048 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001049 RecordData Record;
1050 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001051 if (!Map)
1052 return 0;
1053
Douglas Gregor2cf26342009-04-09 22:27:44 +00001054 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1055 D != DEnd; ++D) {
1056 AddDeclarationName(D->first, Record);
1057 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1058 Record.push_back(Result.second - Result.first);
1059 for(; Result.first != Result.second; ++Result.first)
1060 AddDeclRef(*Result.first, Record);
1061 }
1062
1063 if (Record.size() == 0)
1064 return 0;
1065
Douglas Gregorc9490c02009-04-16 22:23:12 +00001066 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001067 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001068 return Offset;
1069}
1070
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001071//===----------------------------------------------------------------------===//
1072// Global Method Pool and Selector Serialization
1073//===----------------------------------------------------------------------===//
1074
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001075namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001076// Trait used for the on-disk hash table used in the method pool.
1077class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1078 PCHWriter &Writer;
1079
1080public:
1081 typedef Selector key_type;
1082 typedef key_type key_type_ref;
1083
1084 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1085 typedef const data_type& data_type_ref;
1086
1087 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1088
1089 static unsigned ComputeHash(Selector Sel) {
1090 unsigned N = Sel.getNumArgs();
1091 if (N == 0)
1092 ++N;
1093 unsigned R = 5381;
1094 for (unsigned I = 0; I != N; ++I)
1095 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1096 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1097 return R;
1098 }
1099
1100 std::pair<unsigned,unsigned>
1101 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1102 data_type_ref Methods) {
1103 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1104 clang::io::Emit16(Out, KeyLen);
1105 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1106 for (const ObjCMethodList *Method = &Methods.first; Method;
1107 Method = Method->Next)
1108 if (Method->Method)
1109 DataLen += 4;
1110 for (const ObjCMethodList *Method = &Methods.second; Method;
1111 Method = Method->Next)
1112 if (Method->Method)
1113 DataLen += 4;
1114 clang::io::Emit16(Out, DataLen);
1115 return std::make_pair(KeyLen, DataLen);
1116 }
1117
Douglas Gregor83941df2009-04-25 17:48:32 +00001118 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1119 uint64_t Start = Out.tell();
1120 assert((Start >> 32) == 0 && "Selector key offset too large");
1121 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001122 unsigned N = Sel.getNumArgs();
1123 clang::io::Emit16(Out, N);
1124 if (N == 0)
1125 N = 1;
1126 for (unsigned I = 0; I != N; ++I)
1127 clang::io::Emit32(Out,
1128 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1129 }
1130
1131 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001132 data_type_ref Methods, unsigned DataLen) {
1133 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001134 unsigned NumInstanceMethods = 0;
1135 for (const ObjCMethodList *Method = &Methods.first; Method;
1136 Method = Method->Next)
1137 if (Method->Method)
1138 ++NumInstanceMethods;
1139
1140 unsigned NumFactoryMethods = 0;
1141 for (const ObjCMethodList *Method = &Methods.second; Method;
1142 Method = Method->Next)
1143 if (Method->Method)
1144 ++NumFactoryMethods;
1145
1146 clang::io::Emit16(Out, NumInstanceMethods);
1147 clang::io::Emit16(Out, NumFactoryMethods);
1148 for (const ObjCMethodList *Method = &Methods.first; Method;
1149 Method = Method->Next)
1150 if (Method->Method)
1151 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001152 for (const ObjCMethodList *Method = &Methods.second; Method;
1153 Method = Method->Next)
1154 if (Method->Method)
1155 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001156
1157 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001158 }
1159};
1160} // end anonymous namespace
1161
1162/// \brief Write the method pool into the PCH file.
1163///
1164/// The method pool contains both instance and factory methods, stored
1165/// in an on-disk hash table indexed by the selector.
1166void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1167 using namespace llvm;
1168
1169 // Create and write out the blob that contains the instance and
1170 // factor method pools.
1171 bool Empty = true;
1172 {
1173 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1174
1175 // Create the on-disk hash table representation. Start by
1176 // iterating through the instance method pool.
1177 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001178 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001179 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1180 Instance = SemaRef.InstanceMethodPool.begin(),
1181 InstanceEnd = SemaRef.InstanceMethodPool.end();
1182 Instance != InstanceEnd; ++Instance) {
1183 // Check whether there is a factory method with the same
1184 // selector.
1185 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1186 = SemaRef.FactoryMethodPool.find(Instance->first);
1187
1188 if (Factory == SemaRef.FactoryMethodPool.end())
1189 Generator.insert(Instance->first,
1190 std::make_pair(Instance->second,
1191 ObjCMethodList()));
1192 else
1193 Generator.insert(Instance->first,
1194 std::make_pair(Instance->second, Factory->second));
1195
Douglas Gregor83941df2009-04-25 17:48:32 +00001196 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001197 Empty = false;
1198 }
1199
1200 // Now iterate through the factory method pool, to pick up any
1201 // selectors that weren't already in the instance method pool.
1202 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1203 Factory = SemaRef.FactoryMethodPool.begin(),
1204 FactoryEnd = SemaRef.FactoryMethodPool.end();
1205 Factory != FactoryEnd; ++Factory) {
1206 // Check whether there is an instance method with the same
1207 // selector. If so, there is no work to do here.
1208 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1209 = SemaRef.InstanceMethodPool.find(Factory->first);
1210
Douglas Gregor83941df2009-04-25 17:48:32 +00001211 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001212 Generator.insert(Factory->first,
1213 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001214 ++NumSelectorsInMethodPool;
1215 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001216
1217 Empty = false;
1218 }
1219
Douglas Gregor83941df2009-04-25 17:48:32 +00001220 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001221 return;
1222
1223 // Create the on-disk hash table in a buffer.
1224 llvm::SmallVector<char, 4096> MethodPool;
1225 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001226 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001227 {
1228 PCHMethodPoolTrait Trait(*this);
1229 llvm::raw_svector_ostream Out(MethodPool);
1230 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001231 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001232 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001233
1234 // For every selector that we have seen but which was not
1235 // written into the hash table, write the selector itself and
1236 // record it's offset.
1237 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1238 if (SelectorOffsets[I] == 0)
1239 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001240 }
1241
1242 // Create a blob abbreviation
1243 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1244 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1245 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001246 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1248 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1249
Douglas Gregor83941df2009-04-25 17:48:32 +00001250 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001251 RecordData Record;
1252 Record.push_back(pch::METHOD_POOL);
1253 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001254 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001255 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1256 &MethodPool.front(),
1257 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001258
1259 // Create a blob abbreviation for the selector table offsets.
1260 Abbrev = new BitCodeAbbrev();
1261 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1262 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1264 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1265
1266 // Write the selector offsets table.
1267 Record.clear();
1268 Record.push_back(pch::SELECTOR_OFFSETS);
1269 Record.push_back(SelectorOffsets.size());
1270 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1271 (const char *)&SelectorOffsets.front(),
1272 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001273 }
1274}
1275
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001276//===----------------------------------------------------------------------===//
1277// Identifier Table Serialization
1278//===----------------------------------------------------------------------===//
1279
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001280namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001281class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1282 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001283 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001284
1285public:
1286 typedef const IdentifierInfo* key_type;
1287 typedef key_type key_type_ref;
1288
1289 typedef pch::IdentID data_type;
1290 typedef data_type data_type_ref;
1291
Douglas Gregor37e26842009-04-21 23:56:24 +00001292 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1293 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001294
1295 static unsigned ComputeHash(const IdentifierInfo* II) {
1296 return clang::BernsteinHash(II->getName());
1297 }
1298
Douglas Gregor37e26842009-04-21 23:56:24 +00001299 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001300 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1301 pch::IdentID ID) {
1302 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001303 unsigned DataLen = 4 + 4; // 4 bytes for token ID, builtin, flags
1304 // 4 bytes for the persistent ID
Douglas Gregor37e26842009-04-21 23:56:24 +00001305 if (II->hasMacroDefinition() &&
1306 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1307 DataLen += 8;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001308 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1309 DEnd = IdentifierResolver::end();
1310 D != DEnd; ++D)
1311 DataLen += sizeof(pch::DeclID);
Douglas Gregord6595a42009-04-25 21:04:17 +00001312 // We emit the key length after the data length so that the
1313 // "uninteresting" identifiers following the identifier hash table
1314 // structure will have the same (key length, key characters)
1315 // layout as the keys in the hash table. This also matches the
1316 // format for identifiers in pretokenized headers.
Douglas Gregor668c1a42009-04-21 22:25:48 +00001317 clang::io::Emit16(Out, DataLen);
Douglas Gregord6595a42009-04-25 21:04:17 +00001318 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001319 return std::make_pair(KeyLen, DataLen);
1320 }
1321
1322 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1323 unsigned KeyLen) {
1324 // Record the location of the key data. This is used when generating
1325 // the mapping from persistent IDs to strings.
1326 Writer.SetIdentifierOffset(II, Out.tell());
1327 Out.write(II->getName(), KeyLen);
1328 }
1329
1330 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1331 pch::IdentID ID, unsigned) {
1332 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001333 bool hasMacroDefinition =
1334 II->hasMacroDefinition() &&
1335 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001336 Bits = Bits | (uint32_t)II->getTokenID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001337 Bits = (Bits << 10) | (uint32_t)II->getObjCOrBuiltinID();
1338 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001339 Bits = (Bits << 1) | II->isExtensionToken();
1340 Bits = (Bits << 1) | II->isPoisoned();
1341 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
1342 clang::io::Emit32(Out, Bits);
1343 clang::io::Emit32(Out, ID);
1344
Douglas Gregor37e26842009-04-21 23:56:24 +00001345 if (hasMacroDefinition)
1346 clang::io::Emit64(Out, Writer.getMacroOffset(II));
1347
Douglas Gregor668c1a42009-04-21 22:25:48 +00001348 // Emit the declaration IDs in reverse order, because the
1349 // IdentifierResolver provides the declarations as they would be
1350 // visible (e.g., the function "stat" would come before the struct
1351 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1352 // adds declarations to the end of the list (so we need to see the
1353 // struct "status" before the function "status").
1354 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1355 IdentifierResolver::end());
1356 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1357 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001358 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001359 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001360 }
1361};
1362} // end anonymous namespace
1363
Douglas Gregorafaf3082009-04-11 00:14:32 +00001364/// \brief Write the identifier table into the PCH file.
1365///
1366/// The identifier table consists of a blob containing string data
1367/// (the actual identifiers themselves) and a separate "offsets" index
1368/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001369void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001370 using namespace llvm;
1371
1372 // Create and write out the blob that contains the identifier
1373 // strings.
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001374 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001375 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001376 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1377
Douglas Gregord6595a42009-04-25 21:04:17 +00001378 llvm::SmallVector<const IdentifierInfo *, 32> UninterestingIdentifiers;
1379
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001380 // Create the on-disk hash table representation.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001381 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1382 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1383 ID != IDEnd; ++ID) {
1384 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregord6595a42009-04-25 21:04:17 +00001385
1386 // Classify each identifier as either "interesting" or "not
1387 // interesting". Interesting identifiers are those that have
1388 // additional information that needs to be read from the PCH
1389 // file, e.g., a built-in ID, declaration chain, or macro
1390 // definition. These identifiers are placed into the hash table
1391 // so that they can be found when looked up in the user program.
1392 // All other identifiers are "uninteresting", which means that
1393 // the IdentifierInfo built by default has all of the
1394 // information we care about. Such identifiers are placed after
1395 // the hash table.
1396 const IdentifierInfo *II = ID->first;
1397 if (II->isPoisoned() ||
1398 II->isExtensionToken() ||
1399 II->hasMacroDefinition() ||
1400 II->getObjCOrBuiltinID() ||
1401 II->getFETokenInfo<void>())
1402 Generator.insert(ID->first, ID->second);
1403 else
1404 UninterestingIdentifiers.push_back(II);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001405 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001406
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001407 // Create the on-disk hash table in a buffer.
1408 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001409 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001410 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001411 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001412 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001413 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001414 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001415 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregord6595a42009-04-25 21:04:17 +00001416
1417 for (unsigned I = 0, N = UninterestingIdentifiers.size(); I != N; ++I) {
1418 const IdentifierInfo *II = UninterestingIdentifiers[I];
1419 unsigned N = II->getLength() + 1;
1420 clang::io::Emit16(Out, N);
1421 SetIdentifierOffset(II, Out.tell());
1422 Out.write(II->getName(), N);
1423 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001424 }
1425
1426 // Create a blob abbreviation
1427 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1428 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001431 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001432
1433 // Write the identifier table
1434 RecordData Record;
1435 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001436 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001437 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1438 &IdentifierTable.front(),
1439 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001440 }
1441
1442 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001443 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1444 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1446 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1447 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1448
1449 RecordData Record;
1450 Record.push_back(pch::IDENTIFIER_OFFSET);
1451 Record.push_back(IdentifierOffsets.size());
1452 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1453 (const char *)&IdentifierOffsets.front(),
1454 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001455}
1456
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001457//===----------------------------------------------------------------------===//
1458// General Serialization Routines
1459//===----------------------------------------------------------------------===//
1460
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001461/// \brief Write a record containing the given attributes.
1462void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1463 RecordData Record;
1464 for (; Attr; Attr = Attr->getNext()) {
1465 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1466 Record.push_back(Attr->isInherited());
1467 switch (Attr->getKind()) {
1468 case Attr::Alias:
1469 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1470 break;
1471
1472 case Attr::Aligned:
1473 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1474 break;
1475
1476 case Attr::AlwaysInline:
1477 break;
1478
1479 case Attr::AnalyzerNoReturn:
1480 break;
1481
1482 case Attr::Annotate:
1483 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1484 break;
1485
1486 case Attr::AsmLabel:
1487 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1488 break;
1489
1490 case Attr::Blocks:
1491 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1492 break;
1493
1494 case Attr::Cleanup:
1495 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1496 break;
1497
1498 case Attr::Const:
1499 break;
1500
1501 case Attr::Constructor:
1502 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1503 break;
1504
1505 case Attr::DLLExport:
1506 case Attr::DLLImport:
1507 case Attr::Deprecated:
1508 break;
1509
1510 case Attr::Destructor:
1511 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1512 break;
1513
1514 case Attr::FastCall:
1515 break;
1516
1517 case Attr::Format: {
1518 const FormatAttr *Format = cast<FormatAttr>(Attr);
1519 AddString(Format->getType(), Record);
1520 Record.push_back(Format->getFormatIdx());
1521 Record.push_back(Format->getFirstArg());
1522 break;
1523 }
1524
Chris Lattnercf2a7212009-04-20 19:12:28 +00001525 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001526 case Attr::IBOutletKind:
1527 case Attr::NoReturn:
1528 case Attr::NoThrow:
1529 case Attr::Nodebug:
1530 case Attr::Noinline:
1531 break;
1532
1533 case Attr::NonNull: {
1534 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1535 Record.push_back(NonNull->size());
1536 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1537 break;
1538 }
1539
1540 case Attr::ObjCException:
1541 case Attr::ObjCNSObject:
Ted Kremenekc6a59e42009-04-27 19:36:56 +00001542 case Attr::ObjCOwnershipCFRelease:
1543 case Attr::ObjCOwnershipRelease:
Ted Kremenek4064de92009-04-27 18:27:22 +00001544 case Attr::ObjCOwnershipCFRetain:
Ted Kremenekde9a81b2009-04-25 00:17:17 +00001545 case Attr::ObjCOwnershipRetain:
Ted Kremenek0fc169e2009-04-24 23:09:54 +00001546 case Attr::ObjCOwnershipReturns:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001547 case Attr::Overloadable:
1548 break;
1549
1550 case Attr::Packed:
1551 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1552 break;
1553
1554 case Attr::Pure:
1555 break;
1556
1557 case Attr::Regparm:
1558 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1559 break;
1560
1561 case Attr::Section:
1562 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1563 break;
1564
1565 case Attr::StdCall:
1566 case Attr::TransparentUnion:
1567 case Attr::Unavailable:
1568 case Attr::Unused:
1569 case Attr::Used:
1570 break;
1571
1572 case Attr::Visibility:
1573 // FIXME: stable encoding
1574 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1575 break;
1576
1577 case Attr::WarnUnusedResult:
1578 case Attr::Weak:
1579 case Attr::WeakImport:
1580 break;
1581 }
1582 }
1583
Douglas Gregorc9490c02009-04-16 22:23:12 +00001584 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001585}
1586
1587void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1588 Record.push_back(Str.size());
1589 Record.insert(Record.end(), Str.begin(), Str.end());
1590}
1591
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001592/// \brief Note that the identifier II occurs at the given offset
1593/// within the identifier table.
1594void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001595 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001596}
1597
Douglas Gregor83941df2009-04-25 17:48:32 +00001598/// \brief Note that the selector Sel occurs at the given offset
1599/// within the method pool/selector table.
1600void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1601 unsigned ID = SelectorIDs[Sel];
1602 assert(ID && "Unknown selector");
1603 SelectorOffsets[ID - 1] = Offset;
1604}
1605
Douglas Gregorc9490c02009-04-16 22:23:12 +00001606PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001607 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001608 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1609 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001610
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001611void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001612 using namespace llvm;
1613
Douglas Gregore7785042009-04-20 15:53:59 +00001614 ASTContext &Context = SemaRef.Context;
1615 Preprocessor &PP = SemaRef.PP;
1616
Douglas Gregor2cf26342009-04-09 22:27:44 +00001617 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001618 Stream.Emit((unsigned)'C', 8);
1619 Stream.Emit((unsigned)'P', 8);
1620 Stream.Emit((unsigned)'C', 8);
1621 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001622
1623 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001624
1625 // The translation unit is the first declaration we'll emit.
1626 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1627 DeclsToEmit.push(Context.getTranslationUnitDecl());
1628
Douglas Gregor2deaea32009-04-22 18:49:13 +00001629 // Make sure that we emit IdentifierInfos (and any attached
1630 // declarations) for builtins.
1631 {
1632 IdentifierTable &Table = PP.getIdentifierTable();
1633 llvm::SmallVector<const char *, 32> BuiltinNames;
1634 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1635 Context.getLangOptions().NoBuiltin);
1636 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1637 getIdentifierRef(&Table.get(BuiltinNames[I]));
1638 }
1639
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001640 // Build a record containing all of the tentative definitions in
1641 // this header file. Generally, this record will be empty.
1642 RecordData TentativeDefinitions;
1643 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1644 TD = SemaRef.TentativeDefinitions.begin(),
1645 TDEnd = SemaRef.TentativeDefinitions.end();
1646 TD != TDEnd; ++TD)
1647 AddDeclRef(TD->second, TentativeDefinitions);
1648
Douglas Gregor14c22f22009-04-22 22:18:58 +00001649 // Build a record containing all of the locally-scoped external
1650 // declarations in this header file. Generally, this record will be
1651 // empty.
1652 RecordData LocallyScopedExternalDecls;
1653 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1654 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1655 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1656 TD != TDEnd; ++TD)
1657 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1658
Douglas Gregor2cf26342009-04-09 22:27:44 +00001659 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001660 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001661 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregor2bec0412009-04-10 21:16:55 +00001662 WriteTargetTriple(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001663 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001664 if (StatCalls)
1665 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001666 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001667 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001668
1669 // Keep writing types and declarations until all types and
1670 // declarations have been written.
1671 do {
1672 if (!DeclsToEmit.empty())
1673 WriteDeclsBlock(Context);
1674 if (!TypesToEmit.empty())
1675 WriteTypesBlock(Context);
1676 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1677
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001678 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001679 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001680
1681 // Write the type offsets array
1682 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1683 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1686 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1687 Record.clear();
1688 Record.push_back(pch::TYPE_OFFSET);
1689 Record.push_back(TypeOffsets.size());
1690 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1691 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001692 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001693
1694 // Write the declaration offsets array
1695 Abbrev = new BitCodeAbbrev();
1696 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1699 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1700 Record.clear();
1701 Record.push_back(pch::DECL_OFFSET);
1702 Record.push_back(DeclOffsets.size());
1703 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1704 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001705 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001706
1707 // Write the record of special types.
1708 Record.clear();
1709 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001710 AddTypeRef(Context.getObjCIdType(), Record);
1711 AddTypeRef(Context.getObjCSelType(), Record);
1712 AddTypeRef(Context.getObjCProtoType(), Record);
1713 AddTypeRef(Context.getObjCClassType(), Record);
1714 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1715 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001716 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1717
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001718 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001719 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001720 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001721
1722 // Write the record containing tentative definitions.
1723 if (!TentativeDefinitions.empty())
1724 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001725
1726 // Write the record containing locally-scoped external definitions.
1727 if (!LocallyScopedExternalDecls.empty())
1728 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1729 LocallyScopedExternalDecls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001730
1731 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001732 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001733 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001734 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001735 Record.push_back(NumLexicalDeclContexts);
1736 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001737 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001738 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739}
1740
1741void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1742 Record.push_back(Loc.getRawEncoding());
1743}
1744
1745void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1746 Record.push_back(Value.getBitWidth());
1747 unsigned N = Value.getNumWords();
1748 const uint64_t* Words = Value.getRawData();
1749 for (unsigned I = 0; I != N; ++I)
1750 Record.push_back(Words[I]);
1751}
1752
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001753void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1754 Record.push_back(Value.isUnsigned());
1755 AddAPInt(Value, Record);
1756}
1757
Douglas Gregor17fc2232009-04-14 21:55:33 +00001758void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1759 AddAPInt(Value.bitcastToAPInt(), Record);
1760}
1761
Douglas Gregor2cf26342009-04-09 22:27:44 +00001762void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001763 Record.push_back(getIdentifierRef(II));
1764}
1765
1766pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1767 if (II == 0)
1768 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001769
1770 pch::IdentID &ID = IdentifierIDs[II];
1771 if (ID == 0)
1772 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001773 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001774}
1775
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001776void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1777 if (SelRef.getAsOpaquePtr() == 0) {
1778 Record.push_back(0);
1779 return;
1780 }
1781
1782 pch::SelectorID &SID = SelectorIDs[SelRef];
1783 if (SID == 0) {
1784 SID = SelectorIDs.size();
1785 SelVector.push_back(SelRef);
1786 }
1787 Record.push_back(SID);
1788}
1789
Douglas Gregor2cf26342009-04-09 22:27:44 +00001790void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1791 if (T.isNull()) {
1792 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1793 return;
1794 }
1795
1796 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001797 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001798 switch (BT->getKind()) {
1799 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1800 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1801 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1802 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1803 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1804 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1805 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1806 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1807 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1808 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1809 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1810 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1811 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1812 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1813 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1814 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1815 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1816 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1817 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1818 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1819 }
1820
1821 Record.push_back((ID << 3) | T.getCVRQualifiers());
1822 return;
1823 }
1824
Douglas Gregor8038d512009-04-10 17:25:41 +00001825 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001826 if (ID == 0) {
1827 // We haven't seen this type before. Assign it a new ID and put it
1828 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001829 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001830 TypesToEmit.push(T.getTypePtr());
1831 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001832
1833 // Encode the type qualifiers in the type reference.
1834 Record.push_back((ID << 3) | T.getCVRQualifiers());
1835}
1836
1837void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1838 if (D == 0) {
1839 Record.push_back(0);
1840 return;
1841 }
1842
Douglas Gregor8038d512009-04-10 17:25:41 +00001843 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001844 if (ID == 0) {
1845 // We haven't seen this declaration before. Give it a new ID and
1846 // enqueue it in the list of declarations to emit.
1847 ID = DeclIDs.size();
1848 DeclsToEmit.push(const_cast<Decl *>(D));
1849 }
1850
1851 Record.push_back(ID);
1852}
1853
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001854pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1855 if (D == 0)
1856 return 0;
1857
1858 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1859 return DeclIDs[D];
1860}
1861
Douglas Gregor2cf26342009-04-09 22:27:44 +00001862void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001863 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001864 Record.push_back(Name.getNameKind());
1865 switch (Name.getNameKind()) {
1866 case DeclarationName::Identifier:
1867 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1868 break;
1869
1870 case DeclarationName::ObjCZeroArgSelector:
1871 case DeclarationName::ObjCOneArgSelector:
1872 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001873 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001874 break;
1875
1876 case DeclarationName::CXXConstructorName:
1877 case DeclarationName::CXXDestructorName:
1878 case DeclarationName::CXXConversionFunctionName:
1879 AddTypeRef(Name.getCXXNameType(), Record);
1880 break;
1881
1882 case DeclarationName::CXXOperatorName:
1883 Record.push_back(Name.getCXXOverloadedOperator());
1884 break;
1885
1886 case DeclarationName::CXXUsingDirective:
1887 // No extra data to emit
1888 break;
1889 }
1890}
Douglas Gregor0b748912009-04-14 21:18:50 +00001891