blob: 20aee9c441960234560a8f77c2e8aaa7dfcb0226 [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);
452 };
453}
454
455void PCHStmtWriter::VisitExpr(Expr *E) {
456 Writer.AddTypeRef(E->getType(), Record);
457 Record.push_back(E->isTypeDependent());
458 Record.push_back(E->isValueDependent());
459}
460
Douglas Gregore2f37202009-04-14 21:55:33 +0000461void PCHStmtWriter::VisitPredefinedExpr(PredefinedExpr *E) {
462 VisitExpr(E);
463 Writer.AddSourceLocation(E->getLocation(), Record);
464 Record.push_back(E->getIdentType()); // FIXME: stable encoding
465 Code = pch::EXPR_PREDEFINED;
466}
467
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000468void PCHStmtWriter::VisitDeclRefExpr(DeclRefExpr *E) {
469 VisitExpr(E);
470 Writer.AddDeclRef(E->getDecl(), Record);
471 Writer.AddSourceLocation(E->getLocation(), Record);
472 Code = pch::EXPR_DECL_REF;
473}
474
475void PCHStmtWriter::VisitIntegerLiteral(IntegerLiteral *E) {
476 VisitExpr(E);
477 Writer.AddSourceLocation(E->getLocation(), Record);
478 Writer.AddAPInt(E->getValue(), Record);
479 Code = pch::EXPR_INTEGER_LITERAL;
480}
481
Douglas Gregore2f37202009-04-14 21:55:33 +0000482void PCHStmtWriter::VisitFloatingLiteral(FloatingLiteral *E) {
483 VisitExpr(E);
484 Writer.AddAPFloat(E->getValue(), Record);
485 Record.push_back(E->isExact());
486 Writer.AddSourceLocation(E->getLocation(), Record);
487 Code = pch::EXPR_FLOATING_LITERAL;
488}
489
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000490void PCHStmtWriter::VisitCharacterLiteral(CharacterLiteral *E) {
491 VisitExpr(E);
492 Record.push_back(E->getValue());
493 Writer.AddSourceLocation(E->getLoc(), Record);
494 Record.push_back(E->isWide());
495 Code = pch::EXPR_CHARACTER_LITERAL;
496}
497
498//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000499// PCHWriter Implementation
500//===----------------------------------------------------------------------===//
501
Douglas Gregorb5887f32009-04-10 21:16:55 +0000502/// \brief Write the target triple (e.g., i686-apple-darwin9).
503void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
504 using namespace llvm;
505 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
506 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
508 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
509
510 RecordData Record;
511 Record.push_back(pch::TARGET_TRIPLE);
512 const char *Triple = Target.getTargetTriple();
513 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
514}
515
516/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000517void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
518 RecordData Record;
519 Record.push_back(LangOpts.Trigraphs);
520 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
521 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
522 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
523 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
524 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
525 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
526 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
527 Record.push_back(LangOpts.C99); // C99 Support
528 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
529 Record.push_back(LangOpts.CPlusPlus); // C++ Support
530 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
531 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
532 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
533
534 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
535 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
536 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
537
538 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
539 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
540 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
541 Record.push_back(LangOpts.LaxVectorConversions);
542 Record.push_back(LangOpts.Exceptions); // Support exception handling.
543
544 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
545 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
546 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
547
548 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
549 // by locks.
550 Record.push_back(LangOpts.Blocks); // block extension to C
551 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
552 // they are unused.
553 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
554 // (modulo the platform support).
555
556 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
557 // signed integer arithmetic overflows.
558
559 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
560 // may be ripped out at any time.
561
562 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
563 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
564 // defined.
565 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
566 // opposed to __DYNAMIC__).
567 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
568
569 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
570 // used (instead of C99 semantics).
571 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
572 Record.push_back(LangOpts.getGCMode());
573 Record.push_back(LangOpts.getVisibilityMode());
574 Record.push_back(LangOpts.InstantiationDepth);
575 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
576}
577
Douglas Gregorab1cef72009-04-10 03:52:48 +0000578//===----------------------------------------------------------------------===//
579// Source Manager Serialization
580//===----------------------------------------------------------------------===//
581
582/// \brief Create an abbreviation for the SLocEntry that refers to a
583/// file.
584static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
585 using namespace llvm;
586 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
587 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
588 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
590 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
591 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000592 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
593 return S.EmitAbbrev(Abbrev);
594}
595
596/// \brief Create an abbreviation for the SLocEntry that refers to a
597/// buffer.
598static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
599 using namespace llvm;
600 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
601 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
602 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
603 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
604 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
605 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
607 return S.EmitAbbrev(Abbrev);
608}
609
610/// \brief Create an abbreviation for the SLocEntry that refers to a
611/// buffer's blob.
612static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
613 using namespace llvm;
614 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
615 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
617 return S.EmitAbbrev(Abbrev);
618}
619
620/// \brief Create an abbreviation for the SLocEntry that refers to an
621/// buffer.
622static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
623 using namespace llvm;
624 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
625 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
628 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
629 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
630 return S.EmitAbbrev(Abbrev);
631}
632
633/// \brief Writes the block containing the serialized form of the
634/// source manager.
635///
636/// TODO: We should probably use an on-disk hash table (stored in a
637/// blob), indexed based on the file name, so that we only create
638/// entries for files that we actually need. In the common case (no
639/// errors), we probably won't have to create file entries for any of
640/// the files in the AST.
641void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000642 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000643 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
644
645 // Abbreviations for the various kinds of source-location entries.
646 int SLocFileAbbrv = -1;
647 int SLocBufferAbbrv = -1;
648 int SLocBufferBlobAbbrv = -1;
649 int SLocInstantiationAbbrv = -1;
650
651 // Write out the source location entry table. We skip the first
652 // entry, which is always the same dummy entry.
653 RecordData Record;
654 for (SourceManager::sloc_entry_iterator
655 SLoc = SourceMgr.sloc_entry_begin() + 1,
656 SLocEnd = SourceMgr.sloc_entry_end();
657 SLoc != SLocEnd; ++SLoc) {
658 // Figure out which record code to use.
659 unsigned Code;
660 if (SLoc->isFile()) {
661 if (SLoc->getFile().getContentCache()->Entry)
662 Code = pch::SM_SLOC_FILE_ENTRY;
663 else
664 Code = pch::SM_SLOC_BUFFER_ENTRY;
665 } else
666 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
667 Record.push_back(Code);
668
669 Record.push_back(SLoc->getOffset());
670 if (SLoc->isFile()) {
671 const SrcMgr::FileInfo &File = SLoc->getFile();
672 Record.push_back(File.getIncludeLoc().getRawEncoding());
673 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
Douglas Gregor635f97f2009-04-13 16:31:14 +0000674 Record.push_back(File.hasLineDirectives());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000675
676 const SrcMgr::ContentCache *Content = File.getContentCache();
677 if (Content->Entry) {
678 // The source location entry is a file. The blob associated
679 // with this entry is the file name.
680 if (SLocFileAbbrv == -1)
681 SLocFileAbbrv = CreateSLocFileAbbrev(S);
682 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
683 Content->Entry->getName(),
684 strlen(Content->Entry->getName()));
685 } else {
686 // The source location entry is a buffer. The blob associated
687 // with this entry contains the contents of the buffer.
688 if (SLocBufferAbbrv == -1) {
689 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
690 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
691 }
692
693 // We add one to the size so that we capture the trailing NULL
694 // that is required by llvm::MemoryBuffer::getMemBuffer (on
695 // the reader side).
696 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
697 const char *Name = Buffer->getBufferIdentifier();
698 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
699 Record.clear();
700 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
701 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
702 Buffer->getBufferStart(),
703 Buffer->getBufferSize() + 1);
704 }
705 } else {
706 // The source location entry is an instantiation.
707 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
708 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
709 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
710 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
711
712 if (SLocInstantiationAbbrv == -1)
713 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
714 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
715 }
716
717 Record.clear();
718 }
719
Douglas Gregor635f97f2009-04-13 16:31:14 +0000720 // Write the line table.
721 if (SourceMgr.hasLineTable()) {
722 LineTableInfo &LineTable = SourceMgr.getLineTable();
723
724 // Emit the file names
725 Record.push_back(LineTable.getNumFilenames());
726 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
727 // Emit the file name
728 const char *Filename = LineTable.getFilename(I);
729 unsigned FilenameLen = Filename? strlen(Filename) : 0;
730 Record.push_back(FilenameLen);
731 if (FilenameLen)
732 Record.insert(Record.end(), Filename, Filename + FilenameLen);
733 }
734
735 // Emit the line entries
736 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
737 L != LEnd; ++L) {
738 // Emit the file ID
739 Record.push_back(L->first);
740
741 // Emit the line entries
742 Record.push_back(L->second.size());
743 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
744 LEEnd = L->second.end();
745 LE != LEEnd; ++LE) {
746 Record.push_back(LE->FileOffset);
747 Record.push_back(LE->LineNo);
748 Record.push_back(LE->FilenameID);
749 Record.push_back((unsigned)LE->FileKind);
750 Record.push_back(LE->IncludeOffset);
751 }
752 S.EmitRecord(pch::SM_LINE_TABLE, Record);
753 }
754 }
755
Douglas Gregorab1cef72009-04-10 03:52:48 +0000756 S.ExitBlock();
757}
758
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000759/// \brief Writes the block containing the serialized form of the
760/// preprocessor.
761///
Chris Lattner850eabd2009-04-10 18:08:30 +0000762void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000763 // Enter the preprocessor block.
764 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
765
Chris Lattner1b094952009-04-10 18:00:12 +0000766 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
767 // FIXME: use diagnostics subsystem for localization etc.
768 if (PP.SawDateOrTime())
769 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000770
Chris Lattner1b094952009-04-10 18:00:12 +0000771 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000772
Chris Lattner4b21c202009-04-13 01:29:17 +0000773 // If the preprocessor __COUNTER__ value has been bumped, remember it.
774 if (PP.getCounterValue() != 0) {
775 Record.push_back(PP.getCounterValue());
776 S.EmitRecord(pch::PP_COUNTER_VALUE, Record);
777 Record.clear();
778 }
779
Chris Lattner1b094952009-04-10 18:00:12 +0000780 // Loop over all the macro definitions that are live at the end of the file,
781 // emitting each to the PP section.
782 // FIXME: Eventually we want to emit an index so that we can lazily load
783 // macros.
784 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
785 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000786 // FIXME: This emits macros in hash table order, we should do it in a stable
787 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000788 MacroInfo *MI = I->second;
789
790 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
791 // been redefined by the header (in which case they are not isBuiltinMacro).
792 if (MI->isBuiltinMacro())
793 continue;
794
Chris Lattner29241862009-04-11 21:15:38 +0000795 AddIdentifierRef(I->first, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000796 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
797 Record.push_back(MI->isUsed());
798
799 unsigned Code;
800 if (MI->isObjectLike()) {
801 Code = pch::PP_MACRO_OBJECT_LIKE;
802 } else {
803 Code = pch::PP_MACRO_FUNCTION_LIKE;
804
805 Record.push_back(MI->isC99Varargs());
806 Record.push_back(MI->isGNUVarargs());
807 Record.push_back(MI->getNumArgs());
808 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
809 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000810 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000811 }
812 S.EmitRecord(Code, Record);
813 Record.clear();
814
Chris Lattner850eabd2009-04-10 18:08:30 +0000815 // Emit the tokens array.
816 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
817 // Note that we know that the preprocessor does not have any annotation
818 // tokens in it because they are created by the parser, and thus can't be
819 // in a macro definition.
820 const Token &Tok = MI->getReplacementToken(TokNo);
821
822 Record.push_back(Tok.getLocation().getRawEncoding());
823 Record.push_back(Tok.getLength());
824
Chris Lattner850eabd2009-04-10 18:08:30 +0000825 // FIXME: When reading literal tokens, reconstruct the literal pointer if
826 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000827 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000828
829 // FIXME: Should translate token kind to a stable encoding.
830 Record.push_back(Tok.getKind());
831 // FIXME: Should translate token flags to a stable encoding.
832 Record.push_back(Tok.getFlags());
833
834 S.EmitRecord(pch::PP_TOKEN, Record);
835 Record.clear();
836 }
Chris Lattner1b094952009-04-10 18:00:12 +0000837
838 }
839
Chris Lattner84b04f12009-04-10 17:16:57 +0000840 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000841}
842
843
Douglas Gregorc34897d2009-04-09 22:27:44 +0000844/// \brief Write the representation of a type to the PCH stream.
845void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000846 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000847 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000848 ID = NextTypeID++;
849
850 // Record the offset for this type.
851 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
852 TypeOffsets.push_back(S.GetCurrentBitNo());
853 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
854 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
855 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
856 }
857
858 RecordData Record;
859
860 // Emit the type's representation.
861 PCHTypeWriter W(*this, Record);
862 switch (T->getTypeClass()) {
863 // For all of the concrete, non-dependent types, call the
864 // appropriate visitor function.
865#define TYPE(Class, Base) \
866 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
867#define ABSTRACT_TYPE(Class, Base)
868#define DEPENDENT_TYPE(Class, Base)
869#include "clang/AST/TypeNodes.def"
870
871 // For all of the dependent type nodes (which only occur in C++
872 // templates), produce an error.
873#define TYPE(Class, Base)
874#define DEPENDENT_TYPE(Class, Base) case Type::Class:
875#include "clang/AST/TypeNodes.def"
876 assert(false && "Cannot serialize dependent type nodes");
877 break;
878 }
879
880 // Emit the serialized record.
881 S.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000882
883 // Flush any expressions that were written as part of this type.
884 FlushExprs();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000885}
886
887/// \brief Write a block containing all of the types.
888void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000889 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000890 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
891
892 // Emit all of the types in the ASTContext
893 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
894 TEnd = Context.getTypes().end();
895 T != TEnd; ++T) {
896 // Builtin types are never serialized.
897 if (isa<BuiltinType>(*T))
898 continue;
899
900 WriteType(*T);
901 }
902
903 // Exit the types block
904 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000905}
906
907/// \brief Write the block containing all of the declaration IDs
908/// lexically declared within the given DeclContext.
909///
910/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
911/// bistream, or 0 if no block was written.
912uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
913 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000914 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000915 return 0;
916
917 uint64_t Offset = S.GetCurrentBitNo();
918 RecordData Record;
919 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
920 DEnd = DC->decls_end(Context);
921 D != DEnd; ++D)
922 AddDeclRef(*D, Record);
923
924 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
925 return Offset;
926}
927
928/// \brief Write the block containing all of the declaration IDs
929/// visible from the given DeclContext.
930///
931/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
932/// bistream, or 0 if no block was written.
933uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
934 DeclContext *DC) {
935 if (DC->getPrimaryContext() != DC)
936 return 0;
937
938 // Force the DeclContext to build a its name-lookup table.
939 DC->lookup(Context, DeclarationName());
940
941 // Serialize the contents of the mapping used for lookup. Note that,
942 // although we have two very different code paths, the serialized
943 // representation is the same for both cases: a declaration name,
944 // followed by a size, followed by references to the visible
945 // declarations that have that name.
946 uint64_t Offset = S.GetCurrentBitNo();
947 RecordData Record;
948 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000949 if (!Map)
950 return 0;
951
Douglas Gregorc34897d2009-04-09 22:27:44 +0000952 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
953 D != DEnd; ++D) {
954 AddDeclarationName(D->first, Record);
955 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
956 Record.push_back(Result.second - Result.first);
957 for(; Result.first != Result.second; ++Result.first)
958 AddDeclRef(*Result.first, Record);
959 }
960
961 if (Record.size() == 0)
962 return 0;
963
964 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
965 return Offset;
966}
967
968/// \brief Write a block containing all of the declarations.
969void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000970 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000971 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
972
973 // Emit all of the declarations.
974 RecordData Record;
975 PCHDeclWriter W(*this, Record);
976 while (!DeclsToEmit.empty()) {
977 // Pull the next declaration off the queue
978 Decl *D = DeclsToEmit.front();
979 DeclsToEmit.pop();
980
981 // If this declaration is also a DeclContext, write blocks for the
982 // declarations that lexically stored inside its context and those
983 // declarations that are visible from its context. These blocks
984 // are written before the declaration itself so that we can put
985 // their offsets into the record for the declaration.
986 uint64_t LexicalOffset = 0;
987 uint64_t VisibleOffset = 0;
988 DeclContext *DC = dyn_cast<DeclContext>(D);
989 if (DC) {
990 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
991 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
992 }
993
994 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +0000995 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000996 if (ID == 0)
997 ID = DeclIDs.size();
998
999 unsigned Index = ID - 1;
1000
1001 // Record the offset for this declaration
1002 if (DeclOffsets.size() == Index)
1003 DeclOffsets.push_back(S.GetCurrentBitNo());
1004 else if (DeclOffsets.size() < Index) {
1005 DeclOffsets.resize(Index+1);
1006 DeclOffsets[Index] = S.GetCurrentBitNo();
1007 }
1008
1009 // Build and emit a record for this declaration
1010 Record.clear();
1011 W.Code = (pch::DeclCode)0;
1012 W.Visit(D);
1013 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001014 assert(W.Code && "Unhandled declaration kind while generating PCH");
Douglas Gregorc34897d2009-04-09 22:27:44 +00001015 S.EmitRecord(W.Code, Record);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001016
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001017 // Flush any expressions that were written as part of this declaration.
1018 FlushExprs();
1019
Douglas Gregor631f6c62009-04-14 00:24:19 +00001020 // Note external declarations so that we can add them to a record
1021 // in the PCH file later.
1022 if (isa<FileScopeAsmDecl>(D))
1023 ExternalDefinitions.push_back(ID);
1024 else if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
1025 if (// Non-static file-scope variables with initializers or that
1026 // are tentative definitions.
1027 (Var->isFileVarDecl() &&
1028 (Var->getInit() || Var->getStorageClass() == VarDecl::None)) ||
1029 // Out-of-line definitions of static data members (C++).
1030 (Var->getDeclContext()->isRecord() &&
1031 !Var->getLexicalDeclContext()->isRecord() &&
1032 Var->getStorageClass() == VarDecl::Static))
1033 ExternalDefinitions.push_back(ID);
1034 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1035 if (Func->isThisDeclarationADefinition() &&
1036 Func->getStorageClass() != FunctionDecl::Static &&
1037 !Func->isInline())
1038 ExternalDefinitions.push_back(ID);
1039 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001040 }
1041
1042 // Exit the declarations block
1043 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001044}
1045
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001046/// \brief Write the identifier table into the PCH file.
1047///
1048/// The identifier table consists of a blob containing string data
1049/// (the actual identifiers themselves) and a separate "offsets" index
1050/// that maps identifier IDs to locations within the blob.
1051void PCHWriter::WriteIdentifierTable() {
1052 using namespace llvm;
1053
1054 // Create and write out the blob that contains the identifier
1055 // strings.
1056 RecordData IdentOffsets;
1057 IdentOffsets.resize(IdentifierIDs.size());
1058 {
1059 // Create the identifier string data.
1060 std::vector<char> Data;
1061 Data.push_back(0); // Data must not be empty.
1062 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1063 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1064 ID != IDEnd; ++ID) {
1065 assert(ID->first && "NULL identifier in identifier table");
1066
1067 // Make sure we're starting on an odd byte. The PCH reader
1068 // expects the low bit to be set on all of the offsets.
1069 if ((Data.size() & 0x01) == 0)
1070 Data.push_back((char)0);
1071
1072 IdentOffsets[ID->second - 1] = Data.size();
1073 Data.insert(Data.end(),
1074 ID->first->getName(),
1075 ID->first->getName() + ID->first->getLength());
1076 Data.push_back((char)0);
1077 }
1078
1079 // Create a blob abbreviation
1080 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1081 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
1082 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
1083 unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev);
1084
1085 // Write the identifier table
1086 RecordData Record;
1087 Record.push_back(pch::IDENTIFIER_TABLE);
1088 S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size());
1089 }
1090
1091 // Write the offsets table for identifier IDs.
1092 S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets);
1093}
1094
Douglas Gregorc34897d2009-04-09 22:27:44 +00001095PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
1096 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
1097
Chris Lattner850eabd2009-04-10 18:08:30 +00001098void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001099 // Emit the file header.
1100 S.Emit((unsigned)'C', 8);
1101 S.Emit((unsigned)'P', 8);
1102 S.Emit((unsigned)'C', 8);
1103 S.Emit((unsigned)'H', 8);
1104
1105 // The translation unit is the first declaration we'll emit.
1106 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1107 DeclsToEmit.push(Context.getTranslationUnitDecl());
1108
1109 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +00001110 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
1111 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001112 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001113 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001114 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001115 WriteTypesBlock(Context);
1116 WriteDeclsBlock(Context);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001117 WriteIdentifierTable();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001118 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
1119 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001120 if (!ExternalDefinitions.empty())
1121 S.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001122 S.ExitBlock();
1123}
1124
1125void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1126 Record.push_back(Loc.getRawEncoding());
1127}
1128
1129void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1130 Record.push_back(Value.getBitWidth());
1131 unsigned N = Value.getNumWords();
1132 const uint64_t* Words = Value.getRawData();
1133 for (unsigned I = 0; I != N; ++I)
1134 Record.push_back(Words[I]);
1135}
1136
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001137void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1138 Record.push_back(Value.isUnsigned());
1139 AddAPInt(Value, Record);
1140}
1141
Douglas Gregore2f37202009-04-14 21:55:33 +00001142void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1143 AddAPInt(Value.bitcastToAPInt(), Record);
1144}
1145
Douglas Gregorc34897d2009-04-09 22:27:44 +00001146void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001147 if (II == 0) {
1148 Record.push_back(0);
1149 return;
1150 }
1151
1152 pch::IdentID &ID = IdentifierIDs[II];
1153 if (ID == 0)
1154 ID = IdentifierIDs.size();
1155
1156 Record.push_back(ID);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001157}
1158
1159void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1160 if (T.isNull()) {
1161 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1162 return;
1163 }
1164
1165 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001166 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001167 switch (BT->getKind()) {
1168 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1169 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1170 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1171 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1172 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1173 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1174 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1175 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1176 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1177 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1178 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1179 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1180 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1181 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1182 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1183 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1184 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1185 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1186 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1187 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1188 }
1189
1190 Record.push_back((ID << 3) | T.getCVRQualifiers());
1191 return;
1192 }
1193
Douglas Gregorac8f2802009-04-10 17:25:41 +00001194 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001195 if (ID == 0) // we haven't seen this type before
1196 ID = NextTypeID++;
1197
1198 // Encode the type qualifiers in the type reference.
1199 Record.push_back((ID << 3) | T.getCVRQualifiers());
1200}
1201
1202void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1203 if (D == 0) {
1204 Record.push_back(0);
1205 return;
1206 }
1207
Douglas Gregorac8f2802009-04-10 17:25:41 +00001208 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001209 if (ID == 0) {
1210 // We haven't seen this declaration before. Give it a new ID and
1211 // enqueue it in the list of declarations to emit.
1212 ID = DeclIDs.size();
1213 DeclsToEmit.push(const_cast<Decl *>(D));
1214 }
1215
1216 Record.push_back(ID);
1217}
1218
1219void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
1220 Record.push_back(Name.getNameKind());
1221 switch (Name.getNameKind()) {
1222 case DeclarationName::Identifier:
1223 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1224 break;
1225
1226 case DeclarationName::ObjCZeroArgSelector:
1227 case DeclarationName::ObjCOneArgSelector:
1228 case DeclarationName::ObjCMultiArgSelector:
1229 assert(false && "Serialization of Objective-C selectors unavailable");
1230 break;
1231
1232 case DeclarationName::CXXConstructorName:
1233 case DeclarationName::CXXDestructorName:
1234 case DeclarationName::CXXConversionFunctionName:
1235 AddTypeRef(Name.getCXXNameType(), Record);
1236 break;
1237
1238 case DeclarationName::CXXOperatorName:
1239 Record.push_back(Name.getCXXOverloadedOperator());
1240 break;
1241
1242 case DeclarationName::CXXUsingDirective:
1243 // No extra data to emit
1244 break;
1245 }
1246}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001247
1248/// \brief Flush all of the expressions that have been added to the
1249/// queue via AddExpr().
1250void PCHWriter::FlushExprs() {
1251 RecordData Record;
1252 PCHStmtWriter Writer(*this, Record);
1253 while (!ExprsToEmit.empty()) {
1254 Expr *E = ExprsToEmit.front();
1255 ExprsToEmit.pop();
1256
1257 Record.clear();
1258 if (!E) {
1259 S.EmitRecord(pch::EXPR_NULL, Record);
1260 continue;
1261 }
1262
1263 Writer.Code = pch::EXPR_NULL;
1264 Writer.Visit(E);
1265 assert(Writer.Code != pch::EXPR_NULL &&
1266 "Unhandled expression writing PCH file");
1267 S.EmitRecord(Writer.Code, Record);
1268 }
1269}