blob: 4ca3c8d0ae6e52bd5504b8c914b2ac545d243b76 [file] [log] [blame]
Douglas Gregorc34897d2009-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"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclContextInternals.h"
18#include "clang/AST/DeclVisitor.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/StmtVisitor.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000024#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000028#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000030#include "llvm/Bitcode/BitstreamWriter.h"
31#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000032#include "llvm/Support/MemoryBuffer.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000033#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Type serialization
38//===----------------------------------------------------------------------===//
39namespace {
40 class VISIBILITY_HIDDEN PCHTypeWriter {
41 PCHWriter &Writer;
42 PCHWriter::RecordData &Record;
43
44 public:
45 /// \brief Type code that corresponds to the record generated.
46 pch::TypeCode Code;
47
48 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
49 : Writer(Writer), Record(Record) { }
50
51 void VisitArrayType(const ArrayType *T);
52 void VisitFunctionType(const FunctionType *T);
53 void VisitTagType(const TagType *T);
54
55#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
56#define ABSTRACT_TYPE(Class, Base)
57#define DEPENDENT_TYPE(Class, Base)
58#include "clang/AST/TypeNodes.def"
59 };
60}
61
62void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
63 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
64 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
65 Record.push_back(T->getAddressSpace());
66 Code = pch::TYPE_EXT_QUAL;
67}
68
69void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
70 assert(false && "Built-in types are never serialized");
71}
72
73void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
74 Record.push_back(T->getWidth());
75 Record.push_back(T->isSigned());
76 Code = pch::TYPE_FIXED_WIDTH_INT;
77}
78
79void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
80 Writer.AddTypeRef(T->getElementType(), Record);
81 Code = pch::TYPE_COMPLEX;
82}
83
84void PCHTypeWriter::VisitPointerType(const PointerType *T) {
85 Writer.AddTypeRef(T->getPointeeType(), Record);
86 Code = pch::TYPE_POINTER;
87}
88
89void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_BLOCK_POINTER;
92}
93
94void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_LVALUE_REFERENCE;
97}
98
99void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_RVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
107 Code = pch::TYPE_MEMBER_POINTER;
108}
109
110void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
111 Writer.AddTypeRef(T->getElementType(), Record);
112 Record.push_back(T->getSizeModifier()); // FIXME: stable values
113 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
114}
115
116void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
117 VisitArrayType(T);
118 Writer.AddAPInt(T->getSize(), Record);
119 Code = pch::TYPE_CONSTANT_ARRAY;
120}
121
122void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
123 VisitArrayType(T);
124 Code = pch::TYPE_INCOMPLETE_ARRAY;
125}
126
127void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
128 VisitArrayType(T);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000129 Writer.AddExpr(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000130 Code = pch::TYPE_VARIABLE_ARRAY;
131}
132
133void PCHTypeWriter::VisitVectorType(const VectorType *T) {
134 Writer.AddTypeRef(T->getElementType(), Record);
135 Record.push_back(T->getNumElements());
136 Code = pch::TYPE_VECTOR;
137}
138
139void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
140 VisitVectorType(T);
141 Code = pch::TYPE_EXT_VECTOR;
142}
143
144void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
145 Writer.AddTypeRef(T->getResultType(), Record);
146}
147
148void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
149 VisitFunctionType(T);
150 Code = pch::TYPE_FUNCTION_NO_PROTO;
151}
152
153void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
154 VisitFunctionType(T);
155 Record.push_back(T->getNumArgs());
156 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
157 Writer.AddTypeRef(T->getArgType(I), Record);
158 Record.push_back(T->isVariadic());
159 Record.push_back(T->getTypeQuals());
160 Code = pch::TYPE_FUNCTION_PROTO;
161}
162
163void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
164 Writer.AddDeclRef(T->getDecl(), Record);
165 Code = pch::TYPE_TYPEDEF;
166}
167
168void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000169 Writer.AddExpr(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_TYPEOF_EXPR;
171}
172
173void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
174 Writer.AddTypeRef(T->getUnderlyingType(), Record);
175 Code = pch::TYPE_TYPEOF;
176}
177
178void PCHTypeWriter::VisitTagType(const TagType *T) {
179 Writer.AddDeclRef(T->getDecl(), Record);
180 assert(!T->isBeingDefined() &&
181 "Cannot serialize in the middle of a type definition");
182}
183
184void PCHTypeWriter::VisitRecordType(const RecordType *T) {
185 VisitTagType(T);
186 Code = pch::TYPE_RECORD;
187}
188
189void PCHTypeWriter::VisitEnumType(const EnumType *T) {
190 VisitTagType(T);
191 Code = pch::TYPE_ENUM;
192}
193
194void
195PCHTypeWriter::VisitTemplateSpecializationType(
196 const TemplateSpecializationType *T) {
197 // FIXME: Serialize this type
198 assert(false && "Cannot serialize template specialization types");
199}
200
201void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
202 // FIXME: Serialize this type
203 assert(false && "Cannot serialize qualified name types");
204}
205
206void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
207 Writer.AddDeclRef(T->getDecl(), Record);
208 Code = pch::TYPE_OBJC_INTERFACE;
209}
210
211void
212PCHTypeWriter::VisitObjCQualifiedInterfaceType(
213 const ObjCQualifiedInterfaceType *T) {
214 VisitObjCInterfaceType(T);
215 Record.push_back(T->getNumProtocols());
216 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
217 Writer.AddDeclRef(T->getProtocol(I), Record);
218 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
219}
220
221void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
222 Record.push_back(T->getNumProtocols());
223 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
224 Writer.AddDeclRef(T->getProtocols(I), Record);
225 Code = pch::TYPE_OBJC_QUALIFIED_ID;
226}
227
228void
229PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
230 Record.push_back(T->getNumProtocols());
231 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
232 Writer.AddDeclRef(T->getProtocols(I), Record);
233 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
234}
235
236//===----------------------------------------------------------------------===//
237// Declaration serialization
238//===----------------------------------------------------------------------===//
239namespace {
240 class VISIBILITY_HIDDEN PCHDeclWriter
241 : public DeclVisitor<PCHDeclWriter, void> {
242
243 PCHWriter &Writer;
244 PCHWriter::RecordData &Record;
245
246 public:
247 pch::DeclCode Code;
248
249 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
250 : Writer(Writer), Record(Record) { }
251
252 void VisitDecl(Decl *D);
253 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 void VisitNamedDecl(NamedDecl *D);
255 void VisitTypeDecl(TypeDecl *D);
256 void VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000257 void VisitTagDecl(TagDecl *D);
258 void VisitEnumDecl(EnumDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000259 void VisitRecordDecl(RecordDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000260 void VisitValueDecl(ValueDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000261 void VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000262 void VisitFunctionDecl(FunctionDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000263 void VisitFieldDecl(FieldDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000264 void VisitVarDecl(VarDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000265 void VisitParmVarDecl(ParmVarDecl *D);
266 void VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor2a491792009-04-13 22:49:25 +0000267 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
268 void VisitBlockDecl(BlockDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000269 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
270 uint64_t VisibleOffset);
271 };
272}
273
274void PCHDeclWriter::VisitDecl(Decl *D) {
275 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
276 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
277 Writer.AddSourceLocation(D->getLocation(), Record);
278 Record.push_back(D->isInvalidDecl());
279 // FIXME: hasAttrs
280 Record.push_back(D->isImplicit());
281 Record.push_back(D->getAccess());
282}
283
284void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
285 VisitDecl(D);
286 Code = pch::DECL_TRANSLATION_UNIT;
287}
288
289void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
290 VisitDecl(D);
291 Writer.AddDeclarationName(D->getDeclName(), Record);
292}
293
294void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
295 VisitNamedDecl(D);
296 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
297}
298
299void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
300 VisitTypeDecl(D);
301 Writer.AddTypeRef(D->getUnderlyingType(), Record);
302 Code = pch::DECL_TYPEDEF;
303}
304
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000305void PCHDeclWriter::VisitTagDecl(TagDecl *D) {
306 VisitTypeDecl(D);
307 Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
308 Record.push_back(D->isDefinition());
309 Writer.AddDeclRef(D->getTypedefForAnonDecl(), Record);
310}
311
312void PCHDeclWriter::VisitEnumDecl(EnumDecl *D) {
313 VisitTagDecl(D);
314 Writer.AddTypeRef(D->getIntegerType(), Record);
315 Code = pch::DECL_ENUM;
316}
317
Douglas Gregor982365e2009-04-13 21:20:57 +0000318void PCHDeclWriter::VisitRecordDecl(RecordDecl *D) {
319 VisitTagDecl(D);
320 Record.push_back(D->hasFlexibleArrayMember());
321 Record.push_back(D->isAnonymousStructOrUnion());
322 Code = pch::DECL_RECORD;
323}
324
Douglas Gregorc34897d2009-04-09 22:27:44 +0000325void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
326 VisitNamedDecl(D);
327 Writer.AddTypeRef(D->getType(), Record);
328}
329
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000330void PCHDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
331 VisitValueDecl(D);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000332 Record.push_back(D->getInitExpr()? 1 : 0);
333 if (D->getInitExpr())
334 Writer.AddExpr(D->getInitExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000335 Writer.AddAPSInt(D->getInitVal(), Record);
336 Code = pch::DECL_ENUM_CONSTANT;
337}
338
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000339void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
340 VisitValueDecl(D);
341 // FIXME: function body
342 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
343 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
344 Record.push_back(D->isInline());
345 Record.push_back(D->isVirtual());
346 Record.push_back(D->isPure());
347 Record.push_back(D->inheritedPrototype());
348 Record.push_back(D->hasPrototype() && !D->inheritedPrototype());
349 Record.push_back(D->isDeleted());
350 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
351 Record.push_back(D->param_size());
352 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
353 P != PEnd; ++P)
354 Writer.AddDeclRef(*P, Record);
355 Code = pch::DECL_FUNCTION;
356}
357
Douglas Gregor982365e2009-04-13 21:20:57 +0000358void PCHDeclWriter::VisitFieldDecl(FieldDecl *D) {
359 VisitValueDecl(D);
360 Record.push_back(D->isMutable());
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000361 Record.push_back(D->getBitWidth()? 1 : 0);
362 if (D->getBitWidth())
363 Writer.AddExpr(D->getBitWidth());
Douglas Gregor982365e2009-04-13 21:20:57 +0000364 Code = pch::DECL_FIELD;
365}
366
Douglas Gregorc34897d2009-04-09 22:27:44 +0000367void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
368 VisitValueDecl(D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000369 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
Douglas Gregorc34897d2009-04-09 22:27:44 +0000370 Record.push_back(D->isThreadSpecified());
371 Record.push_back(D->hasCXXDirectInitializer());
372 Record.push_back(D->isDeclaredInCondition());
373 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
374 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000375 Record.push_back(D->getInit()? 1 : 0);
376 if (D->getInit())
377 Writer.AddExpr(D->getInit());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000378 Code = pch::DECL_VAR;
379}
380
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000381void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
382 VisitVarDecl(D);
383 Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
384 // FIXME: emit default argument
385 // FIXME: why isn't the "default argument" just stored as the initializer
386 // in VarDecl?
387 Code = pch::DECL_PARM_VAR;
388}
389
390void PCHDeclWriter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
391 VisitParmVarDecl(D);
392 Writer.AddTypeRef(D->getOriginalType(), Record);
393 Code = pch::DECL_ORIGINAL_PARM_VAR;
394}
395
Douglas Gregor2a491792009-04-13 22:49:25 +0000396void PCHDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
397 VisitDecl(D);
398 // FIXME: Emit the string literal
399 Code = pch::DECL_FILE_SCOPE_ASM;
400}
401
402void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) {
403 VisitDecl(D);
404 // FIXME: emit block body
405 Record.push_back(D->param_size());
406 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
407 P != PEnd; ++P)
408 Writer.AddDeclRef(*P, Record);
409 Code = pch::DECL_BLOCK;
410}
411
Douglas Gregorc34897d2009-04-09 22:27:44 +0000412/// \brief Emit the DeclContext part of a declaration context decl.
413///
414/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
415/// block for this declaration context is stored. May be 0 to indicate
416/// that there are no declarations stored within this context.
417///
418/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
419/// block for this declaration context is stored. May be 0 to indicate
420/// that there are no declarations visible from this context. Note
421/// that this value will not be emitted for non-primary declaration
422/// contexts.
423void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
424 uint64_t VisibleOffset) {
425 Record.push_back(LexicalOffset);
426 if (DC->getPrimaryContext() == DC)
427 Record.push_back(VisibleOffset);
428}
429
430//===----------------------------------------------------------------------===//
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000431// Statement/expression serialization
432//===----------------------------------------------------------------------===//
433namespace {
434 class VISIBILITY_HIDDEN PCHStmtWriter
435 : public StmtVisitor<PCHStmtWriter, void> {
436
437 PCHWriter &Writer;
438 PCHWriter::RecordData &Record;
439
440 public:
441 pch::StmtCode Code;
442
443 PCHStmtWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
444 : Writer(Writer), Record(Record) { }
445
446 void VisitExpr(Expr *E);
Douglas Gregore2f37202009-04-14 21:55:33 +0000447 void VisitPredefinedExpr(PredefinedExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000448 void VisitDeclRefExpr(DeclRefExpr *E);
449 void VisitIntegerLiteral(IntegerLiteral *E);
Douglas Gregore2f37202009-04-14 21:55:33 +0000450 void VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000451 void VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000452 void VisitCastExpr(CastExpr *E);
453 void VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000454 };
455}
456
457void PCHStmtWriter::VisitExpr(Expr *E) {
458 Writer.AddTypeRef(E->getType(), Record);
459 Record.push_back(E->isTypeDependent());
460 Record.push_back(E->isValueDependent());
461}
462
Douglas Gregore2f37202009-04-14 21:55:33 +0000463void PCHStmtWriter::VisitPredefinedExpr(PredefinedExpr *E) {
464 VisitExpr(E);
465 Writer.AddSourceLocation(E->getLocation(), Record);
466 Record.push_back(E->getIdentType()); // FIXME: stable encoding
467 Code = pch::EXPR_PREDEFINED;
468}
469
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000470void PCHStmtWriter::VisitDeclRefExpr(DeclRefExpr *E) {
471 VisitExpr(E);
472 Writer.AddDeclRef(E->getDecl(), Record);
473 Writer.AddSourceLocation(E->getLocation(), Record);
474 Code = pch::EXPR_DECL_REF;
475}
476
477void PCHStmtWriter::VisitIntegerLiteral(IntegerLiteral *E) {
478 VisitExpr(E);
479 Writer.AddSourceLocation(E->getLocation(), Record);
480 Writer.AddAPInt(E->getValue(), Record);
481 Code = pch::EXPR_INTEGER_LITERAL;
482}
483
Douglas Gregore2f37202009-04-14 21:55:33 +0000484void PCHStmtWriter::VisitFloatingLiteral(FloatingLiteral *E) {
485 VisitExpr(E);
486 Writer.AddAPFloat(E->getValue(), Record);
487 Record.push_back(E->isExact());
488 Writer.AddSourceLocation(E->getLocation(), Record);
489 Code = pch::EXPR_FLOATING_LITERAL;
490}
491
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000492void PCHStmtWriter::VisitCharacterLiteral(CharacterLiteral *E) {
493 VisitExpr(E);
494 Record.push_back(E->getValue());
495 Writer.AddSourceLocation(E->getLoc(), Record);
496 Record.push_back(E->isWide());
497 Code = pch::EXPR_CHARACTER_LITERAL;
498}
499
Douglas Gregora151ba42009-04-14 23:32:43 +0000500void PCHStmtWriter::VisitCastExpr(CastExpr *E) {
501 VisitExpr(E);
502 Writer.WriteSubExpr(E->getSubExpr());
503}
504
505void PCHStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
506 VisitCastExpr(E);
507 Record.push_back(E->isLvalueCast());
508 Code = pch::EXPR_IMPLICIT_CAST;
509}
510
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000511//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000512// PCHWriter Implementation
513//===----------------------------------------------------------------------===//
514
Douglas Gregorb5887f32009-04-10 21:16:55 +0000515/// \brief Write the target triple (e.g., i686-apple-darwin9).
516void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
517 using namespace llvm;
518 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
519 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
521 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
522
523 RecordData Record;
524 Record.push_back(pch::TARGET_TRIPLE);
525 const char *Triple = Target.getTargetTriple();
526 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
527}
528
529/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000530void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
531 RecordData Record;
532 Record.push_back(LangOpts.Trigraphs);
533 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
534 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
535 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
536 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
537 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
538 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
539 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
540 Record.push_back(LangOpts.C99); // C99 Support
541 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
542 Record.push_back(LangOpts.CPlusPlus); // C++ Support
543 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
544 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
545 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
546
547 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
548 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
549 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
550
551 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
552 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
553 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
554 Record.push_back(LangOpts.LaxVectorConversions);
555 Record.push_back(LangOpts.Exceptions); // Support exception handling.
556
557 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
558 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
559 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
560
561 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
562 // by locks.
563 Record.push_back(LangOpts.Blocks); // block extension to C
564 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
565 // they are unused.
566 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
567 // (modulo the platform support).
568
569 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
570 // signed integer arithmetic overflows.
571
572 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
573 // may be ripped out at any time.
574
575 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
576 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
577 // defined.
578 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
579 // opposed to __DYNAMIC__).
580 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
581
582 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
583 // used (instead of C99 semantics).
584 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
585 Record.push_back(LangOpts.getGCMode());
586 Record.push_back(LangOpts.getVisibilityMode());
587 Record.push_back(LangOpts.InstantiationDepth);
588 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
589}
590
Douglas Gregorab1cef72009-04-10 03:52:48 +0000591//===----------------------------------------------------------------------===//
592// Source Manager Serialization
593//===----------------------------------------------------------------------===//
594
595/// \brief Create an abbreviation for the SLocEntry that refers to a
596/// file.
597static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
598 using namespace llvm;
599 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
600 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
602 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
603 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
604 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000605 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
606 return S.EmitAbbrev(Abbrev);
607}
608
609/// \brief Create an abbreviation for the SLocEntry that refers to a
610/// buffer.
611static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
612 using namespace llvm;
613 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
614 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
617 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
618 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
620 return S.EmitAbbrev(Abbrev);
621}
622
623/// \brief Create an abbreviation for the SLocEntry that refers to a
624/// buffer's blob.
625static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
626 using namespace llvm;
627 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
628 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
629 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
630 return S.EmitAbbrev(Abbrev);
631}
632
633/// \brief Create an abbreviation for the SLocEntry that refers to an
634/// buffer.
635static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
636 using namespace llvm;
637 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
638 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
641 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
642 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
643 return S.EmitAbbrev(Abbrev);
644}
645
646/// \brief Writes the block containing the serialized form of the
647/// source manager.
648///
649/// TODO: We should probably use an on-disk hash table (stored in a
650/// blob), indexed based on the file name, so that we only create
651/// entries for files that we actually need. In the common case (no
652/// errors), we probably won't have to create file entries for any of
653/// the files in the AST.
654void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000655 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000656 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
657
658 // Abbreviations for the various kinds of source-location entries.
659 int SLocFileAbbrv = -1;
660 int SLocBufferAbbrv = -1;
661 int SLocBufferBlobAbbrv = -1;
662 int SLocInstantiationAbbrv = -1;
663
664 // Write out the source location entry table. We skip the first
665 // entry, which is always the same dummy entry.
666 RecordData Record;
667 for (SourceManager::sloc_entry_iterator
668 SLoc = SourceMgr.sloc_entry_begin() + 1,
669 SLocEnd = SourceMgr.sloc_entry_end();
670 SLoc != SLocEnd; ++SLoc) {
671 // Figure out which record code to use.
672 unsigned Code;
673 if (SLoc->isFile()) {
674 if (SLoc->getFile().getContentCache()->Entry)
675 Code = pch::SM_SLOC_FILE_ENTRY;
676 else
677 Code = pch::SM_SLOC_BUFFER_ENTRY;
678 } else
679 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
680 Record.push_back(Code);
681
682 Record.push_back(SLoc->getOffset());
683 if (SLoc->isFile()) {
684 const SrcMgr::FileInfo &File = SLoc->getFile();
685 Record.push_back(File.getIncludeLoc().getRawEncoding());
686 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
Douglas Gregor635f97f2009-04-13 16:31:14 +0000687 Record.push_back(File.hasLineDirectives());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000688
689 const SrcMgr::ContentCache *Content = File.getContentCache();
690 if (Content->Entry) {
691 // The source location entry is a file. The blob associated
692 // with this entry is the file name.
693 if (SLocFileAbbrv == -1)
694 SLocFileAbbrv = CreateSLocFileAbbrev(S);
695 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
696 Content->Entry->getName(),
697 strlen(Content->Entry->getName()));
698 } else {
699 // The source location entry is a buffer. The blob associated
700 // with this entry contains the contents of the buffer.
701 if (SLocBufferAbbrv == -1) {
702 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
703 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
704 }
705
706 // We add one to the size so that we capture the trailing NULL
707 // that is required by llvm::MemoryBuffer::getMemBuffer (on
708 // the reader side).
709 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
710 const char *Name = Buffer->getBufferIdentifier();
711 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
712 Record.clear();
713 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
714 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
715 Buffer->getBufferStart(),
716 Buffer->getBufferSize() + 1);
717 }
718 } else {
719 // The source location entry is an instantiation.
720 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
721 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
722 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
723 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
724
725 if (SLocInstantiationAbbrv == -1)
726 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
727 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
728 }
729
730 Record.clear();
731 }
732
Douglas Gregor635f97f2009-04-13 16:31:14 +0000733 // Write the line table.
734 if (SourceMgr.hasLineTable()) {
735 LineTableInfo &LineTable = SourceMgr.getLineTable();
736
737 // Emit the file names
738 Record.push_back(LineTable.getNumFilenames());
739 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
740 // Emit the file name
741 const char *Filename = LineTable.getFilename(I);
742 unsigned FilenameLen = Filename? strlen(Filename) : 0;
743 Record.push_back(FilenameLen);
744 if (FilenameLen)
745 Record.insert(Record.end(), Filename, Filename + FilenameLen);
746 }
747
748 // Emit the line entries
749 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
750 L != LEnd; ++L) {
751 // Emit the file ID
752 Record.push_back(L->first);
753
754 // Emit the line entries
755 Record.push_back(L->second.size());
756 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
757 LEEnd = L->second.end();
758 LE != LEEnd; ++LE) {
759 Record.push_back(LE->FileOffset);
760 Record.push_back(LE->LineNo);
761 Record.push_back(LE->FilenameID);
762 Record.push_back((unsigned)LE->FileKind);
763 Record.push_back(LE->IncludeOffset);
764 }
765 S.EmitRecord(pch::SM_LINE_TABLE, Record);
766 }
767 }
768
Douglas Gregorab1cef72009-04-10 03:52:48 +0000769 S.ExitBlock();
770}
771
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000772/// \brief Writes the block containing the serialized form of the
773/// preprocessor.
774///
Chris Lattner850eabd2009-04-10 18:08:30 +0000775void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000776 // Enter the preprocessor block.
777 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
778
Chris Lattner1b094952009-04-10 18:00:12 +0000779 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
780 // FIXME: use diagnostics subsystem for localization etc.
781 if (PP.SawDateOrTime())
782 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000783
Chris Lattner1b094952009-04-10 18:00:12 +0000784 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000785
Chris Lattner4b21c202009-04-13 01:29:17 +0000786 // If the preprocessor __COUNTER__ value has been bumped, remember it.
787 if (PP.getCounterValue() != 0) {
788 Record.push_back(PP.getCounterValue());
789 S.EmitRecord(pch::PP_COUNTER_VALUE, Record);
790 Record.clear();
791 }
792
Chris Lattner1b094952009-04-10 18:00:12 +0000793 // Loop over all the macro definitions that are live at the end of the file,
794 // emitting each to the PP section.
795 // FIXME: Eventually we want to emit an index so that we can lazily load
796 // macros.
797 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
798 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000799 // FIXME: This emits macros in hash table order, we should do it in a stable
800 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000801 MacroInfo *MI = I->second;
802
803 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
804 // been redefined by the header (in which case they are not isBuiltinMacro).
805 if (MI->isBuiltinMacro())
806 continue;
807
Chris Lattner29241862009-04-11 21:15:38 +0000808 AddIdentifierRef(I->first, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000809 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
810 Record.push_back(MI->isUsed());
811
812 unsigned Code;
813 if (MI->isObjectLike()) {
814 Code = pch::PP_MACRO_OBJECT_LIKE;
815 } else {
816 Code = pch::PP_MACRO_FUNCTION_LIKE;
817
818 Record.push_back(MI->isC99Varargs());
819 Record.push_back(MI->isGNUVarargs());
820 Record.push_back(MI->getNumArgs());
821 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
822 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000823 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000824 }
825 S.EmitRecord(Code, Record);
826 Record.clear();
827
Chris Lattner850eabd2009-04-10 18:08:30 +0000828 // Emit the tokens array.
829 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
830 // Note that we know that the preprocessor does not have any annotation
831 // tokens in it because they are created by the parser, and thus can't be
832 // in a macro definition.
833 const Token &Tok = MI->getReplacementToken(TokNo);
834
835 Record.push_back(Tok.getLocation().getRawEncoding());
836 Record.push_back(Tok.getLength());
837
Chris Lattner850eabd2009-04-10 18:08:30 +0000838 // FIXME: When reading literal tokens, reconstruct the literal pointer if
839 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000840 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000841
842 // FIXME: Should translate token kind to a stable encoding.
843 Record.push_back(Tok.getKind());
844 // FIXME: Should translate token flags to a stable encoding.
845 Record.push_back(Tok.getFlags());
846
847 S.EmitRecord(pch::PP_TOKEN, Record);
848 Record.clear();
849 }
Chris Lattner1b094952009-04-10 18:00:12 +0000850
851 }
852
Chris Lattner84b04f12009-04-10 17:16:57 +0000853 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000854}
855
856
Douglas Gregorc34897d2009-04-09 22:27:44 +0000857/// \brief Write the representation of a type to the PCH stream.
858void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000859 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000860 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000861 ID = NextTypeID++;
862
863 // Record the offset for this type.
864 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
865 TypeOffsets.push_back(S.GetCurrentBitNo());
866 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
867 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
868 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
869 }
870
871 RecordData Record;
872
873 // Emit the type's representation.
874 PCHTypeWriter W(*this, Record);
875 switch (T->getTypeClass()) {
876 // For all of the concrete, non-dependent types, call the
877 // appropriate visitor function.
878#define TYPE(Class, Base) \
879 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
880#define ABSTRACT_TYPE(Class, Base)
881#define DEPENDENT_TYPE(Class, Base)
882#include "clang/AST/TypeNodes.def"
883
884 // For all of the dependent type nodes (which only occur in C++
885 // templates), produce an error.
886#define TYPE(Class, Base)
887#define DEPENDENT_TYPE(Class, Base) case Type::Class:
888#include "clang/AST/TypeNodes.def"
889 assert(false && "Cannot serialize dependent type nodes");
890 break;
891 }
892
893 // Emit the serialized record.
894 S.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000895
896 // Flush any expressions that were written as part of this type.
897 FlushExprs();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000898}
899
900/// \brief Write a block containing all of the types.
901void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000902 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000903 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
904
905 // Emit all of the types in the ASTContext
906 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
907 TEnd = Context.getTypes().end();
908 T != TEnd; ++T) {
909 // Builtin types are never serialized.
910 if (isa<BuiltinType>(*T))
911 continue;
912
913 WriteType(*T);
914 }
915
916 // Exit the types block
917 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000918}
919
920/// \brief Write the block containing all of the declaration IDs
921/// lexically declared within the given DeclContext.
922///
923/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
924/// bistream, or 0 if no block was written.
925uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
926 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000927 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000928 return 0;
929
930 uint64_t Offset = S.GetCurrentBitNo();
931 RecordData Record;
932 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
933 DEnd = DC->decls_end(Context);
934 D != DEnd; ++D)
935 AddDeclRef(*D, Record);
936
937 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
938 return Offset;
939}
940
941/// \brief Write the block containing all of the declaration IDs
942/// visible from the given DeclContext.
943///
944/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
945/// bistream, or 0 if no block was written.
946uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
947 DeclContext *DC) {
948 if (DC->getPrimaryContext() != DC)
949 return 0;
950
951 // Force the DeclContext to build a its name-lookup table.
952 DC->lookup(Context, DeclarationName());
953
954 // Serialize the contents of the mapping used for lookup. Note that,
955 // although we have two very different code paths, the serialized
956 // representation is the same for both cases: a declaration name,
957 // followed by a size, followed by references to the visible
958 // declarations that have that name.
959 uint64_t Offset = S.GetCurrentBitNo();
960 RecordData Record;
961 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000962 if (!Map)
963 return 0;
964
Douglas Gregorc34897d2009-04-09 22:27:44 +0000965 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
966 D != DEnd; ++D) {
967 AddDeclarationName(D->first, Record);
968 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
969 Record.push_back(Result.second - Result.first);
970 for(; Result.first != Result.second; ++Result.first)
971 AddDeclRef(*Result.first, Record);
972 }
973
974 if (Record.size() == 0)
975 return 0;
976
977 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
978 return Offset;
979}
980
981/// \brief Write a block containing all of the declarations.
982void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000983 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000984 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
985
986 // Emit all of the declarations.
987 RecordData Record;
988 PCHDeclWriter W(*this, Record);
989 while (!DeclsToEmit.empty()) {
990 // Pull the next declaration off the queue
991 Decl *D = DeclsToEmit.front();
992 DeclsToEmit.pop();
993
994 // If this declaration is also a DeclContext, write blocks for the
995 // declarations that lexically stored inside its context and those
996 // declarations that are visible from its context. These blocks
997 // are written before the declaration itself so that we can put
998 // their offsets into the record for the declaration.
999 uint64_t LexicalOffset = 0;
1000 uint64_t VisibleOffset = 0;
1001 DeclContext *DC = dyn_cast<DeclContext>(D);
1002 if (DC) {
1003 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
1004 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
1005 }
1006
1007 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +00001008 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001009 if (ID == 0)
1010 ID = DeclIDs.size();
1011
1012 unsigned Index = ID - 1;
1013
1014 // Record the offset for this declaration
1015 if (DeclOffsets.size() == Index)
1016 DeclOffsets.push_back(S.GetCurrentBitNo());
1017 else if (DeclOffsets.size() < Index) {
1018 DeclOffsets.resize(Index+1);
1019 DeclOffsets[Index] = S.GetCurrentBitNo();
1020 }
1021
1022 // Build and emit a record for this declaration
1023 Record.clear();
1024 W.Code = (pch::DeclCode)0;
1025 W.Visit(D);
1026 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001027 assert(W.Code && "Unhandled declaration kind while generating PCH");
Douglas Gregorc34897d2009-04-09 22:27:44 +00001028 S.EmitRecord(W.Code, Record);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001029
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001030 // Flush any expressions that were written as part of this declaration.
1031 FlushExprs();
1032
Douglas Gregor631f6c62009-04-14 00:24:19 +00001033 // Note external declarations so that we can add them to a record
1034 // in the PCH file later.
1035 if (isa<FileScopeAsmDecl>(D))
1036 ExternalDefinitions.push_back(ID);
1037 else if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
1038 if (// Non-static file-scope variables with initializers or that
1039 // are tentative definitions.
1040 (Var->isFileVarDecl() &&
1041 (Var->getInit() || Var->getStorageClass() == VarDecl::None)) ||
1042 // Out-of-line definitions of static data members (C++).
1043 (Var->getDeclContext()->isRecord() &&
1044 !Var->getLexicalDeclContext()->isRecord() &&
1045 Var->getStorageClass() == VarDecl::Static))
1046 ExternalDefinitions.push_back(ID);
1047 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1048 if (Func->isThisDeclarationADefinition() &&
1049 Func->getStorageClass() != FunctionDecl::Static &&
1050 !Func->isInline())
1051 ExternalDefinitions.push_back(ID);
1052 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001053 }
1054
1055 // Exit the declarations block
1056 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001057}
1058
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001059/// \brief Write the identifier table into the PCH file.
1060///
1061/// The identifier table consists of a blob containing string data
1062/// (the actual identifiers themselves) and a separate "offsets" index
1063/// that maps identifier IDs to locations within the blob.
1064void PCHWriter::WriteIdentifierTable() {
1065 using namespace llvm;
1066
1067 // Create and write out the blob that contains the identifier
1068 // strings.
1069 RecordData IdentOffsets;
1070 IdentOffsets.resize(IdentifierIDs.size());
1071 {
1072 // Create the identifier string data.
1073 std::vector<char> Data;
1074 Data.push_back(0); // Data must not be empty.
1075 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1076 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1077 ID != IDEnd; ++ID) {
1078 assert(ID->first && "NULL identifier in identifier table");
1079
1080 // Make sure we're starting on an odd byte. The PCH reader
1081 // expects the low bit to be set on all of the offsets.
1082 if ((Data.size() & 0x01) == 0)
1083 Data.push_back((char)0);
1084
1085 IdentOffsets[ID->second - 1] = Data.size();
1086 Data.insert(Data.end(),
1087 ID->first->getName(),
1088 ID->first->getName() + ID->first->getLength());
1089 Data.push_back((char)0);
1090 }
1091
1092 // Create a blob abbreviation
1093 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1094 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
1095 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
1096 unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev);
1097
1098 // Write the identifier table
1099 RecordData Record;
1100 Record.push_back(pch::IDENTIFIER_TABLE);
1101 S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size());
1102 }
1103
1104 // Write the offsets table for identifier IDs.
1105 S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets);
1106}
1107
Douglas Gregorc34897d2009-04-09 22:27:44 +00001108PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
1109 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
1110
Chris Lattner850eabd2009-04-10 18:08:30 +00001111void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001112 // Emit the file header.
1113 S.Emit((unsigned)'C', 8);
1114 S.Emit((unsigned)'P', 8);
1115 S.Emit((unsigned)'C', 8);
1116 S.Emit((unsigned)'H', 8);
1117
1118 // The translation unit is the first declaration we'll emit.
1119 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1120 DeclsToEmit.push(Context.getTranslationUnitDecl());
1121
1122 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +00001123 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
1124 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001125 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001126 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001127 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001128 WriteTypesBlock(Context);
1129 WriteDeclsBlock(Context);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001130 WriteIdentifierTable();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001131 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
1132 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001133 if (!ExternalDefinitions.empty())
1134 S.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001135 S.ExitBlock();
1136}
1137
1138void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1139 Record.push_back(Loc.getRawEncoding());
1140}
1141
1142void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1143 Record.push_back(Value.getBitWidth());
1144 unsigned N = Value.getNumWords();
1145 const uint64_t* Words = Value.getRawData();
1146 for (unsigned I = 0; I != N; ++I)
1147 Record.push_back(Words[I]);
1148}
1149
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001150void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1151 Record.push_back(Value.isUnsigned());
1152 AddAPInt(Value, Record);
1153}
1154
Douglas Gregore2f37202009-04-14 21:55:33 +00001155void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1156 AddAPInt(Value.bitcastToAPInt(), Record);
1157}
1158
Douglas Gregorc34897d2009-04-09 22:27:44 +00001159void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001160 if (II == 0) {
1161 Record.push_back(0);
1162 return;
1163 }
1164
1165 pch::IdentID &ID = IdentifierIDs[II];
1166 if (ID == 0)
1167 ID = IdentifierIDs.size();
1168
1169 Record.push_back(ID);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001170}
1171
1172void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1173 if (T.isNull()) {
1174 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1175 return;
1176 }
1177
1178 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001179 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001180 switch (BT->getKind()) {
1181 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1182 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1183 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1184 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1185 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1186 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1187 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1188 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1189 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1190 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1191 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1192 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1193 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1194 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1195 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1196 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1197 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1198 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1199 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1200 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1201 }
1202
1203 Record.push_back((ID << 3) | T.getCVRQualifiers());
1204 return;
1205 }
1206
Douglas Gregorac8f2802009-04-10 17:25:41 +00001207 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001208 if (ID == 0) // we haven't seen this type before
1209 ID = NextTypeID++;
1210
1211 // Encode the type qualifiers in the type reference.
1212 Record.push_back((ID << 3) | T.getCVRQualifiers());
1213}
1214
1215void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1216 if (D == 0) {
1217 Record.push_back(0);
1218 return;
1219 }
1220
Douglas Gregorac8f2802009-04-10 17:25:41 +00001221 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001222 if (ID == 0) {
1223 // We haven't seen this declaration before. Give it a new ID and
1224 // enqueue it in the list of declarations to emit.
1225 ID = DeclIDs.size();
1226 DeclsToEmit.push(const_cast<Decl *>(D));
1227 }
1228
1229 Record.push_back(ID);
1230}
1231
1232void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
1233 Record.push_back(Name.getNameKind());
1234 switch (Name.getNameKind()) {
1235 case DeclarationName::Identifier:
1236 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1237 break;
1238
1239 case DeclarationName::ObjCZeroArgSelector:
1240 case DeclarationName::ObjCOneArgSelector:
1241 case DeclarationName::ObjCMultiArgSelector:
1242 assert(false && "Serialization of Objective-C selectors unavailable");
1243 break;
1244
1245 case DeclarationName::CXXConstructorName:
1246 case DeclarationName::CXXDestructorName:
1247 case DeclarationName::CXXConversionFunctionName:
1248 AddTypeRef(Name.getCXXNameType(), Record);
1249 break;
1250
1251 case DeclarationName::CXXOperatorName:
1252 Record.push_back(Name.getCXXOverloadedOperator());
1253 break;
1254
1255 case DeclarationName::CXXUsingDirective:
1256 // No extra data to emit
1257 break;
1258 }
1259}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001260
Douglas Gregora151ba42009-04-14 23:32:43 +00001261/// \brief Write the given subexpression to the bitstream.
1262void PCHWriter::WriteSubExpr(Expr *E) {
1263 RecordData Record;
1264 PCHStmtWriter Writer(*this, Record);
1265
1266 if (!E) {
1267 S.EmitRecord(pch::EXPR_NULL, Record);
1268 return;
1269 }
1270
1271 Writer.Code = pch::EXPR_NULL;
1272 Writer.Visit(E);
1273 assert(Writer.Code != pch::EXPR_NULL &&
1274 "Unhandled expression writing PCH file");
1275 S.EmitRecord(Writer.Code, Record);
1276}
1277
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001278/// \brief Flush all of the expressions that have been added to the
1279/// queue via AddExpr().
1280void PCHWriter::FlushExprs() {
1281 RecordData Record;
1282 PCHStmtWriter Writer(*this, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001283
Douglas Gregora151ba42009-04-14 23:32:43 +00001284 for (unsigned I = 0, N = ExprsToEmit.size(); I != N; ++I) {
1285 Expr *E = ExprsToEmit[I];
1286
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001287 if (!E) {
1288 S.EmitRecord(pch::EXPR_NULL, Record);
1289 continue;
1290 }
1291
1292 Writer.Code = pch::EXPR_NULL;
1293 Writer.Visit(E);
1294 assert(Writer.Code != pch::EXPR_NULL &&
1295 "Unhandled expression writing PCH file");
1296 S.EmitRecord(Writer.Code, Record);
Douglas Gregora151ba42009-04-14 23:32:43 +00001297
1298 assert(N == ExprsToEmit.size() &&
1299 "Subexpression writen via AddExpr rather than WriteSubExpr!");
1300
1301 // Note that we are at the end of a full expression. Any
1302 // expression records that follow this one are part of a different
1303 // expression.
1304 Record.clear();
1305 S.EmitRecord(pch::EXPR_STOP, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001306 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001307
1308 ExprsToEmit.clear();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001309}