blob: 738e5c1879ba8539587ba338f5c31aed7f52cb02 [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"
19#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000020#include "clang/Lex/MacroInfo.h"
21#include "clang/Lex/Preprocessor.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000022#include "clang/Basic/FileManager.h"
23#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000024#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000025#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000026#include "llvm/Bitcode/BitstreamWriter.h"
27#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000028#include "llvm/Support/MemoryBuffer.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000029#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000030using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Type serialization
34//===----------------------------------------------------------------------===//
35namespace {
36 class VISIBILITY_HIDDEN PCHTypeWriter {
37 PCHWriter &Writer;
38 PCHWriter::RecordData &Record;
39
40 public:
41 /// \brief Type code that corresponds to the record generated.
42 pch::TypeCode Code;
43
44 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
45 : Writer(Writer), Record(Record) { }
46
47 void VisitArrayType(const ArrayType *T);
48 void VisitFunctionType(const FunctionType *T);
49 void VisitTagType(const TagType *T);
50
51#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
52#define ABSTRACT_TYPE(Class, Base)
53#define DEPENDENT_TYPE(Class, Base)
54#include "clang/AST/TypeNodes.def"
55 };
56}
57
58void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
59 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
60 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
61 Record.push_back(T->getAddressSpace());
62 Code = pch::TYPE_EXT_QUAL;
63}
64
65void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
66 assert(false && "Built-in types are never serialized");
67}
68
69void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
70 Record.push_back(T->getWidth());
71 Record.push_back(T->isSigned());
72 Code = pch::TYPE_FIXED_WIDTH_INT;
73}
74
75void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
76 Writer.AddTypeRef(T->getElementType(), Record);
77 Code = pch::TYPE_COMPLEX;
78}
79
80void PCHTypeWriter::VisitPointerType(const PointerType *T) {
81 Writer.AddTypeRef(T->getPointeeType(), Record);
82 Code = pch::TYPE_POINTER;
83}
84
85void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
86 Writer.AddTypeRef(T->getPointeeType(), Record);
87 Code = pch::TYPE_BLOCK_POINTER;
88}
89
90void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
91 Writer.AddTypeRef(T->getPointeeType(), Record);
92 Code = pch::TYPE_LVALUE_REFERENCE;
93}
94
95void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
96 Writer.AddTypeRef(T->getPointeeType(), Record);
97 Code = pch::TYPE_RVALUE_REFERENCE;
98}
99
100void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
101 Writer.AddTypeRef(T->getPointeeType(), Record);
102 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
103 Code = pch::TYPE_MEMBER_POINTER;
104}
105
106void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
107 Writer.AddTypeRef(T->getElementType(), Record);
108 Record.push_back(T->getSizeModifier()); // FIXME: stable values
109 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
110}
111
112void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
113 VisitArrayType(T);
114 Writer.AddAPInt(T->getSize(), Record);
115 Code = pch::TYPE_CONSTANT_ARRAY;
116}
117
118void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
119 VisitArrayType(T);
120 Code = pch::TYPE_INCOMPLETE_ARRAY;
121}
122
123void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
124 VisitArrayType(T);
125 // FIXME: Serialize array size expression.
126 assert(false && "Cannot serialize variable-length arrays");
127 Code = pch::TYPE_VARIABLE_ARRAY;
128}
129
130void PCHTypeWriter::VisitVectorType(const VectorType *T) {
131 Writer.AddTypeRef(T->getElementType(), Record);
132 Record.push_back(T->getNumElements());
133 Code = pch::TYPE_VECTOR;
134}
135
136void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
137 VisitVectorType(T);
138 Code = pch::TYPE_EXT_VECTOR;
139}
140
141void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
142 Writer.AddTypeRef(T->getResultType(), Record);
143}
144
145void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
146 VisitFunctionType(T);
147 Code = pch::TYPE_FUNCTION_NO_PROTO;
148}
149
150void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
151 VisitFunctionType(T);
152 Record.push_back(T->getNumArgs());
153 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
154 Writer.AddTypeRef(T->getArgType(I), Record);
155 Record.push_back(T->isVariadic());
156 Record.push_back(T->getTypeQuals());
157 Code = pch::TYPE_FUNCTION_PROTO;
158}
159
160void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
161 Writer.AddDeclRef(T->getDecl(), Record);
162 Code = pch::TYPE_TYPEDEF;
163}
164
165void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
166 // FIXME: serialize the typeof expression
167 assert(false && "Cannot serialize typeof(expr)");
168 Code = pch::TYPE_TYPEOF_EXPR;
169}
170
171void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
172 Writer.AddTypeRef(T->getUnderlyingType(), Record);
173 Code = pch::TYPE_TYPEOF;
174}
175
176void PCHTypeWriter::VisitTagType(const TagType *T) {
177 Writer.AddDeclRef(T->getDecl(), Record);
178 assert(!T->isBeingDefined() &&
179 "Cannot serialize in the middle of a type definition");
180}
181
182void PCHTypeWriter::VisitRecordType(const RecordType *T) {
183 VisitTagType(T);
184 Code = pch::TYPE_RECORD;
185}
186
187void PCHTypeWriter::VisitEnumType(const EnumType *T) {
188 VisitTagType(T);
189 Code = pch::TYPE_ENUM;
190}
191
192void
193PCHTypeWriter::VisitTemplateSpecializationType(
194 const TemplateSpecializationType *T) {
195 // FIXME: Serialize this type
196 assert(false && "Cannot serialize template specialization types");
197}
198
199void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
200 // FIXME: Serialize this type
201 assert(false && "Cannot serialize qualified name types");
202}
203
204void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
205 Writer.AddDeclRef(T->getDecl(), Record);
206 Code = pch::TYPE_OBJC_INTERFACE;
207}
208
209void
210PCHTypeWriter::VisitObjCQualifiedInterfaceType(
211 const ObjCQualifiedInterfaceType *T) {
212 VisitObjCInterfaceType(T);
213 Record.push_back(T->getNumProtocols());
214 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
215 Writer.AddDeclRef(T->getProtocol(I), Record);
216 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
217}
218
219void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
220 Record.push_back(T->getNumProtocols());
221 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
222 Writer.AddDeclRef(T->getProtocols(I), Record);
223 Code = pch::TYPE_OBJC_QUALIFIED_ID;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
228 Record.push_back(T->getNumProtocols());
229 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
230 Writer.AddDeclRef(T->getProtocols(I), Record);
231 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
232}
233
234//===----------------------------------------------------------------------===//
235// Declaration serialization
236//===----------------------------------------------------------------------===//
237namespace {
238 class VISIBILITY_HIDDEN PCHDeclWriter
239 : public DeclVisitor<PCHDeclWriter, void> {
240
241 PCHWriter &Writer;
242 PCHWriter::RecordData &Record;
243
244 public:
245 pch::DeclCode Code;
246
247 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
248 : Writer(Writer), Record(Record) { }
249
250 void VisitDecl(Decl *D);
251 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
252 void VisitNamedDecl(NamedDecl *D);
253 void VisitTypeDecl(TypeDecl *D);
254 void VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000255 void VisitTagDecl(TagDecl *D);
256 void VisitEnumDecl(EnumDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000257 void VisitRecordDecl(RecordDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000258 void VisitValueDecl(ValueDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000259 void VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000260 void VisitFunctionDecl(FunctionDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000261 void VisitFieldDecl(FieldDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000262 void VisitVarDecl(VarDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000263 void VisitParmVarDecl(ParmVarDecl *D);
264 void VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor2a491792009-04-13 22:49:25 +0000265 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
266 void VisitBlockDecl(BlockDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000267 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
268 uint64_t VisibleOffset);
269 };
270}
271
272void PCHDeclWriter::VisitDecl(Decl *D) {
273 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
274 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
275 Writer.AddSourceLocation(D->getLocation(), Record);
276 Record.push_back(D->isInvalidDecl());
277 // FIXME: hasAttrs
278 Record.push_back(D->isImplicit());
279 Record.push_back(D->getAccess());
280}
281
282void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
283 VisitDecl(D);
284 Code = pch::DECL_TRANSLATION_UNIT;
285}
286
287void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
288 VisitDecl(D);
289 Writer.AddDeclarationName(D->getDeclName(), Record);
290}
291
292void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
293 VisitNamedDecl(D);
294 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
295}
296
297void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
298 VisitTypeDecl(D);
299 Writer.AddTypeRef(D->getUnderlyingType(), Record);
300 Code = pch::DECL_TYPEDEF;
301}
302
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000303void PCHDeclWriter::VisitTagDecl(TagDecl *D) {
304 VisitTypeDecl(D);
305 Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
306 Record.push_back(D->isDefinition());
307 Writer.AddDeclRef(D->getTypedefForAnonDecl(), Record);
308}
309
310void PCHDeclWriter::VisitEnumDecl(EnumDecl *D) {
311 VisitTagDecl(D);
312 Writer.AddTypeRef(D->getIntegerType(), Record);
313 Code = pch::DECL_ENUM;
314}
315
Douglas Gregor982365e2009-04-13 21:20:57 +0000316void PCHDeclWriter::VisitRecordDecl(RecordDecl *D) {
317 VisitTagDecl(D);
318 Record.push_back(D->hasFlexibleArrayMember());
319 Record.push_back(D->isAnonymousStructOrUnion());
320 Code = pch::DECL_RECORD;
321}
322
Douglas Gregorc34897d2009-04-09 22:27:44 +0000323void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
324 VisitNamedDecl(D);
325 Writer.AddTypeRef(D->getType(), Record);
326}
327
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000328void PCHDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
329 VisitValueDecl(D);
330 // FIXME: Writer.AddExprRef(D->getInitExpr());
331 Writer.AddAPSInt(D->getInitVal(), Record);
332 Code = pch::DECL_ENUM_CONSTANT;
333}
334
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000335void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
336 VisitValueDecl(D);
337 // FIXME: function body
338 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
339 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
340 Record.push_back(D->isInline());
341 Record.push_back(D->isVirtual());
342 Record.push_back(D->isPure());
343 Record.push_back(D->inheritedPrototype());
344 Record.push_back(D->hasPrototype() && !D->inheritedPrototype());
345 Record.push_back(D->isDeleted());
346 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
347 Record.push_back(D->param_size());
348 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
349 P != PEnd; ++P)
350 Writer.AddDeclRef(*P, Record);
351 Code = pch::DECL_FUNCTION;
352}
353
Douglas Gregor982365e2009-04-13 21:20:57 +0000354void PCHDeclWriter::VisitFieldDecl(FieldDecl *D) {
355 VisitValueDecl(D);
356 Record.push_back(D->isMutable());
357 // FIXME: Writer.AddExprRef(D->getBitWidth());
358 Code = pch::DECL_FIELD;
359}
360
Douglas Gregorc34897d2009-04-09 22:27:44 +0000361void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
362 VisitValueDecl(D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000363 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
Douglas Gregorc34897d2009-04-09 22:27:44 +0000364 Record.push_back(D->isThreadSpecified());
365 Record.push_back(D->hasCXXDirectInitializer());
366 Record.push_back(D->isDeclaredInCondition());
367 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
368 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
369 // FIXME: emit initializer
370 Code = pch::DECL_VAR;
371}
372
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000373void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
374 VisitVarDecl(D);
375 Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
376 // FIXME: emit default argument
377 // FIXME: why isn't the "default argument" just stored as the initializer
378 // in VarDecl?
379 Code = pch::DECL_PARM_VAR;
380}
381
382void PCHDeclWriter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
383 VisitParmVarDecl(D);
384 Writer.AddTypeRef(D->getOriginalType(), Record);
385 Code = pch::DECL_ORIGINAL_PARM_VAR;
386}
387
Douglas Gregor2a491792009-04-13 22:49:25 +0000388void PCHDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
389 VisitDecl(D);
390 // FIXME: Emit the string literal
391 Code = pch::DECL_FILE_SCOPE_ASM;
392}
393
394void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) {
395 VisitDecl(D);
396 // FIXME: emit block body
397 Record.push_back(D->param_size());
398 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
399 P != PEnd; ++P)
400 Writer.AddDeclRef(*P, Record);
401 Code = pch::DECL_BLOCK;
402}
403
Douglas Gregorc34897d2009-04-09 22:27:44 +0000404/// \brief Emit the DeclContext part of a declaration context decl.
405///
406/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
407/// block for this declaration context is stored. May be 0 to indicate
408/// that there are no declarations stored within this context.
409///
410/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
411/// block for this declaration context is stored. May be 0 to indicate
412/// that there are no declarations visible from this context. Note
413/// that this value will not be emitted for non-primary declaration
414/// contexts.
415void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
416 uint64_t VisibleOffset) {
417 Record.push_back(LexicalOffset);
418 if (DC->getPrimaryContext() == DC)
419 Record.push_back(VisibleOffset);
420}
421
422//===----------------------------------------------------------------------===//
423// PCHWriter Implementation
424//===----------------------------------------------------------------------===//
425
Douglas Gregorb5887f32009-04-10 21:16:55 +0000426/// \brief Write the target triple (e.g., i686-apple-darwin9).
427void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
428 using namespace llvm;
429 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
430 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
432 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
433
434 RecordData Record;
435 Record.push_back(pch::TARGET_TRIPLE);
436 const char *Triple = Target.getTargetTriple();
437 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
438}
439
440/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000441void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
442 RecordData Record;
443 Record.push_back(LangOpts.Trigraphs);
444 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
445 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
446 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
447 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
448 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
449 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
450 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
451 Record.push_back(LangOpts.C99); // C99 Support
452 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
453 Record.push_back(LangOpts.CPlusPlus); // C++ Support
454 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
455 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
456 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
457
458 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
459 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
460 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
461
462 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
463 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
464 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
465 Record.push_back(LangOpts.LaxVectorConversions);
466 Record.push_back(LangOpts.Exceptions); // Support exception handling.
467
468 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
469 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
470 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
471
472 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
473 // by locks.
474 Record.push_back(LangOpts.Blocks); // block extension to C
475 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
476 // they are unused.
477 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
478 // (modulo the platform support).
479
480 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
481 // signed integer arithmetic overflows.
482
483 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
484 // may be ripped out at any time.
485
486 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
487 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
488 // defined.
489 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
490 // opposed to __DYNAMIC__).
491 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
492
493 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
494 // used (instead of C99 semantics).
495 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
496 Record.push_back(LangOpts.getGCMode());
497 Record.push_back(LangOpts.getVisibilityMode());
498 Record.push_back(LangOpts.InstantiationDepth);
499 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
500}
501
Douglas Gregorab1cef72009-04-10 03:52:48 +0000502//===----------------------------------------------------------------------===//
503// Source Manager Serialization
504//===----------------------------------------------------------------------===//
505
506/// \brief Create an abbreviation for the SLocEntry that refers to a
507/// file.
508static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
509 using namespace llvm;
510 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
511 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
516 // FIXME: Need an actual encoding for the line directives; maybe
517 // this should be an array?
518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
519 return S.EmitAbbrev(Abbrev);
520}
521
522/// \brief Create an abbreviation for the SLocEntry that refers to a
523/// buffer.
524static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
525 using namespace llvm;
526 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
527 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
533 return S.EmitAbbrev(Abbrev);
534}
535
536/// \brief Create an abbreviation for the SLocEntry that refers to a
537/// buffer's blob.
538static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
539 using namespace llvm;
540 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
541 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
543 return S.EmitAbbrev(Abbrev);
544}
545
546/// \brief Create an abbreviation for the SLocEntry that refers to an
547/// buffer.
548static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
549 using namespace llvm;
550 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
551 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
556 return S.EmitAbbrev(Abbrev);
557}
558
559/// \brief Writes the block containing the serialized form of the
560/// source manager.
561///
562/// TODO: We should probably use an on-disk hash table (stored in a
563/// blob), indexed based on the file name, so that we only create
564/// entries for files that we actually need. In the common case (no
565/// errors), we probably won't have to create file entries for any of
566/// the files in the AST.
567void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000568 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000569 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
570
571 // Abbreviations for the various kinds of source-location entries.
572 int SLocFileAbbrv = -1;
573 int SLocBufferAbbrv = -1;
574 int SLocBufferBlobAbbrv = -1;
575 int SLocInstantiationAbbrv = -1;
576
577 // Write out the source location entry table. We skip the first
578 // entry, which is always the same dummy entry.
579 RecordData Record;
580 for (SourceManager::sloc_entry_iterator
581 SLoc = SourceMgr.sloc_entry_begin() + 1,
582 SLocEnd = SourceMgr.sloc_entry_end();
583 SLoc != SLocEnd; ++SLoc) {
584 // Figure out which record code to use.
585 unsigned Code;
586 if (SLoc->isFile()) {
587 if (SLoc->getFile().getContentCache()->Entry)
588 Code = pch::SM_SLOC_FILE_ENTRY;
589 else
590 Code = pch::SM_SLOC_BUFFER_ENTRY;
591 } else
592 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
593 Record.push_back(Code);
594
595 Record.push_back(SLoc->getOffset());
596 if (SLoc->isFile()) {
597 const SrcMgr::FileInfo &File = SLoc->getFile();
598 Record.push_back(File.getIncludeLoc().getRawEncoding());
599 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
Douglas Gregor635f97f2009-04-13 16:31:14 +0000600 Record.push_back(File.hasLineDirectives());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000601
602 const SrcMgr::ContentCache *Content = File.getContentCache();
603 if (Content->Entry) {
604 // The source location entry is a file. The blob associated
605 // with this entry is the file name.
606 if (SLocFileAbbrv == -1)
607 SLocFileAbbrv = CreateSLocFileAbbrev(S);
608 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
609 Content->Entry->getName(),
610 strlen(Content->Entry->getName()));
611 } else {
612 // The source location entry is a buffer. The blob associated
613 // with this entry contains the contents of the buffer.
614 if (SLocBufferAbbrv == -1) {
615 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
616 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
617 }
618
619 // We add one to the size so that we capture the trailing NULL
620 // that is required by llvm::MemoryBuffer::getMemBuffer (on
621 // the reader side).
622 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
623 const char *Name = Buffer->getBufferIdentifier();
624 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
625 Record.clear();
626 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
627 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
628 Buffer->getBufferStart(),
629 Buffer->getBufferSize() + 1);
630 }
631 } else {
632 // The source location entry is an instantiation.
633 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
634 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
635 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
636 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
637
638 if (SLocInstantiationAbbrv == -1)
639 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
640 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
641 }
642
643 Record.clear();
644 }
645
Douglas Gregor635f97f2009-04-13 16:31:14 +0000646 // Write the line table.
647 if (SourceMgr.hasLineTable()) {
648 LineTableInfo &LineTable = SourceMgr.getLineTable();
649
650 // Emit the file names
651 Record.push_back(LineTable.getNumFilenames());
652 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
653 // Emit the file name
654 const char *Filename = LineTable.getFilename(I);
655 unsigned FilenameLen = Filename? strlen(Filename) : 0;
656 Record.push_back(FilenameLen);
657 if (FilenameLen)
658 Record.insert(Record.end(), Filename, Filename + FilenameLen);
659 }
660
661 // Emit the line entries
662 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
663 L != LEnd; ++L) {
664 // Emit the file ID
665 Record.push_back(L->first);
666
667 // Emit the line entries
668 Record.push_back(L->second.size());
669 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
670 LEEnd = L->second.end();
671 LE != LEEnd; ++LE) {
672 Record.push_back(LE->FileOffset);
673 Record.push_back(LE->LineNo);
674 Record.push_back(LE->FilenameID);
675 Record.push_back((unsigned)LE->FileKind);
676 Record.push_back(LE->IncludeOffset);
677 }
678 S.EmitRecord(pch::SM_LINE_TABLE, Record);
679 }
680 }
681
Douglas Gregorab1cef72009-04-10 03:52:48 +0000682 S.ExitBlock();
683}
684
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000685/// \brief Writes the block containing the serialized form of the
686/// preprocessor.
687///
Chris Lattner850eabd2009-04-10 18:08:30 +0000688void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000689 // Enter the preprocessor block.
690 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
691
Chris Lattner1b094952009-04-10 18:00:12 +0000692 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
693 // FIXME: use diagnostics subsystem for localization etc.
694 if (PP.SawDateOrTime())
695 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000696
Chris Lattner1b094952009-04-10 18:00:12 +0000697 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000698
Chris Lattner4b21c202009-04-13 01:29:17 +0000699 // If the preprocessor __COUNTER__ value has been bumped, remember it.
700 if (PP.getCounterValue() != 0) {
701 Record.push_back(PP.getCounterValue());
702 S.EmitRecord(pch::PP_COUNTER_VALUE, Record);
703 Record.clear();
704 }
705
Chris Lattner1b094952009-04-10 18:00:12 +0000706 // Loop over all the macro definitions that are live at the end of the file,
707 // emitting each to the PP section.
708 // FIXME: Eventually we want to emit an index so that we can lazily load
709 // macros.
710 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
711 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000712 // FIXME: This emits macros in hash table order, we should do it in a stable
713 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000714 MacroInfo *MI = I->second;
715
716 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
717 // been redefined by the header (in which case they are not isBuiltinMacro).
718 if (MI->isBuiltinMacro())
719 continue;
720
Chris Lattner29241862009-04-11 21:15:38 +0000721 AddIdentifierRef(I->first, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000722 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
723 Record.push_back(MI->isUsed());
724
725 unsigned Code;
726 if (MI->isObjectLike()) {
727 Code = pch::PP_MACRO_OBJECT_LIKE;
728 } else {
729 Code = pch::PP_MACRO_FUNCTION_LIKE;
730
731 Record.push_back(MI->isC99Varargs());
732 Record.push_back(MI->isGNUVarargs());
733 Record.push_back(MI->getNumArgs());
734 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
735 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000736 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000737 }
738 S.EmitRecord(Code, Record);
739 Record.clear();
740
Chris Lattner850eabd2009-04-10 18:08:30 +0000741 // Emit the tokens array.
742 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
743 // Note that we know that the preprocessor does not have any annotation
744 // tokens in it because they are created by the parser, and thus can't be
745 // in a macro definition.
746 const Token &Tok = MI->getReplacementToken(TokNo);
747
748 Record.push_back(Tok.getLocation().getRawEncoding());
749 Record.push_back(Tok.getLength());
750
Chris Lattner850eabd2009-04-10 18:08:30 +0000751 // FIXME: When reading literal tokens, reconstruct the literal pointer if
752 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000753 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000754
755 // FIXME: Should translate token kind to a stable encoding.
756 Record.push_back(Tok.getKind());
757 // FIXME: Should translate token flags to a stable encoding.
758 Record.push_back(Tok.getFlags());
759
760 S.EmitRecord(pch::PP_TOKEN, Record);
761 Record.clear();
762 }
Chris Lattner1b094952009-04-10 18:00:12 +0000763
764 }
765
Chris Lattner84b04f12009-04-10 17:16:57 +0000766 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000767}
768
769
Douglas Gregorc34897d2009-04-09 22:27:44 +0000770/// \brief Write the representation of a type to the PCH stream.
771void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000772 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000773 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000774 ID = NextTypeID++;
775
776 // Record the offset for this type.
777 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
778 TypeOffsets.push_back(S.GetCurrentBitNo());
779 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
780 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
781 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
782 }
783
784 RecordData Record;
785
786 // Emit the type's representation.
787 PCHTypeWriter W(*this, Record);
788 switch (T->getTypeClass()) {
789 // For all of the concrete, non-dependent types, call the
790 // appropriate visitor function.
791#define TYPE(Class, Base) \
792 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
793#define ABSTRACT_TYPE(Class, Base)
794#define DEPENDENT_TYPE(Class, Base)
795#include "clang/AST/TypeNodes.def"
796
797 // For all of the dependent type nodes (which only occur in C++
798 // templates), produce an error.
799#define TYPE(Class, Base)
800#define DEPENDENT_TYPE(Class, Base) case Type::Class:
801#include "clang/AST/TypeNodes.def"
802 assert(false && "Cannot serialize dependent type nodes");
803 break;
804 }
805
806 // Emit the serialized record.
807 S.EmitRecord(W.Code, Record);
808}
809
810/// \brief Write a block containing all of the types.
811void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000812 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000813 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
814
815 // Emit all of the types in the ASTContext
816 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
817 TEnd = Context.getTypes().end();
818 T != TEnd; ++T) {
819 // Builtin types are never serialized.
820 if (isa<BuiltinType>(*T))
821 continue;
822
823 WriteType(*T);
824 }
825
826 // Exit the types block
827 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000828}
829
830/// \brief Write the block containing all of the declaration IDs
831/// lexically declared within the given DeclContext.
832///
833/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
834/// bistream, or 0 if no block was written.
835uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
836 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000837 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000838 return 0;
839
840 uint64_t Offset = S.GetCurrentBitNo();
841 RecordData Record;
842 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
843 DEnd = DC->decls_end(Context);
844 D != DEnd; ++D)
845 AddDeclRef(*D, Record);
846
847 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
848 return Offset;
849}
850
851/// \brief Write the block containing all of the declaration IDs
852/// visible from the given DeclContext.
853///
854/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
855/// bistream, or 0 if no block was written.
856uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
857 DeclContext *DC) {
858 if (DC->getPrimaryContext() != DC)
859 return 0;
860
861 // Force the DeclContext to build a its name-lookup table.
862 DC->lookup(Context, DeclarationName());
863
864 // Serialize the contents of the mapping used for lookup. Note that,
865 // although we have two very different code paths, the serialized
866 // representation is the same for both cases: a declaration name,
867 // followed by a size, followed by references to the visible
868 // declarations that have that name.
869 uint64_t Offset = S.GetCurrentBitNo();
870 RecordData Record;
871 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000872 if (!Map)
873 return 0;
874
Douglas Gregorc34897d2009-04-09 22:27:44 +0000875 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
876 D != DEnd; ++D) {
877 AddDeclarationName(D->first, Record);
878 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
879 Record.push_back(Result.second - Result.first);
880 for(; Result.first != Result.second; ++Result.first)
881 AddDeclRef(*Result.first, Record);
882 }
883
884 if (Record.size() == 0)
885 return 0;
886
887 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
888 return Offset;
889}
890
891/// \brief Write a block containing all of the declarations.
892void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000893 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000894 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
895
896 // Emit all of the declarations.
897 RecordData Record;
898 PCHDeclWriter W(*this, Record);
899 while (!DeclsToEmit.empty()) {
900 // Pull the next declaration off the queue
901 Decl *D = DeclsToEmit.front();
902 DeclsToEmit.pop();
903
904 // If this declaration is also a DeclContext, write blocks for the
905 // declarations that lexically stored inside its context and those
906 // declarations that are visible from its context. These blocks
907 // are written before the declaration itself so that we can put
908 // their offsets into the record for the declaration.
909 uint64_t LexicalOffset = 0;
910 uint64_t VisibleOffset = 0;
911 DeclContext *DC = dyn_cast<DeclContext>(D);
912 if (DC) {
913 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
914 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
915 }
916
917 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +0000918 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000919 if (ID == 0)
920 ID = DeclIDs.size();
921
922 unsigned Index = ID - 1;
923
924 // Record the offset for this declaration
925 if (DeclOffsets.size() == Index)
926 DeclOffsets.push_back(S.GetCurrentBitNo());
927 else if (DeclOffsets.size() < Index) {
928 DeclOffsets.resize(Index+1);
929 DeclOffsets[Index] = S.GetCurrentBitNo();
930 }
931
932 // Build and emit a record for this declaration
933 Record.clear();
934 W.Code = (pch::DeclCode)0;
935 W.Visit(D);
936 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
937 assert(W.Code && "Visitor did not set record code");
938 S.EmitRecord(W.Code, Record);
939 }
940
941 // Exit the declarations block
942 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000943}
944
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000945/// \brief Write the identifier table into the PCH file.
946///
947/// The identifier table consists of a blob containing string data
948/// (the actual identifiers themselves) and a separate "offsets" index
949/// that maps identifier IDs to locations within the blob.
950void PCHWriter::WriteIdentifierTable() {
951 using namespace llvm;
952
953 // Create and write out the blob that contains the identifier
954 // strings.
955 RecordData IdentOffsets;
956 IdentOffsets.resize(IdentifierIDs.size());
957 {
958 // Create the identifier string data.
959 std::vector<char> Data;
960 Data.push_back(0); // Data must not be empty.
961 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
962 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
963 ID != IDEnd; ++ID) {
964 assert(ID->first && "NULL identifier in identifier table");
965
966 // Make sure we're starting on an odd byte. The PCH reader
967 // expects the low bit to be set on all of the offsets.
968 if ((Data.size() & 0x01) == 0)
969 Data.push_back((char)0);
970
971 IdentOffsets[ID->second - 1] = Data.size();
972 Data.insert(Data.end(),
973 ID->first->getName(),
974 ID->first->getName() + ID->first->getLength());
975 Data.push_back((char)0);
976 }
977
978 // Create a blob abbreviation
979 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
980 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
981 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
982 unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev);
983
984 // Write the identifier table
985 RecordData Record;
986 Record.push_back(pch::IDENTIFIER_TABLE);
987 S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size());
988 }
989
990 // Write the offsets table for identifier IDs.
991 S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets);
992}
993
Douglas Gregorc34897d2009-04-09 22:27:44 +0000994PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
995 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
996
Chris Lattner850eabd2009-04-10 18:08:30 +0000997void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000998 // Emit the file header.
999 S.Emit((unsigned)'C', 8);
1000 S.Emit((unsigned)'P', 8);
1001 S.Emit((unsigned)'C', 8);
1002 S.Emit((unsigned)'H', 8);
1003
1004 // The translation unit is the first declaration we'll emit.
1005 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1006 DeclsToEmit.push(Context.getTranslationUnitDecl());
1007
1008 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +00001009 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
1010 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001011 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001012 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001013 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001014 WriteTypesBlock(Context);
1015 WriteDeclsBlock(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001016 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
1017 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001018 WriteIdentifierTable();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001019 S.ExitBlock();
1020}
1021
1022void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1023 Record.push_back(Loc.getRawEncoding());
1024}
1025
1026void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1027 Record.push_back(Value.getBitWidth());
1028 unsigned N = Value.getNumWords();
1029 const uint64_t* Words = Value.getRawData();
1030 for (unsigned I = 0; I != N; ++I)
1031 Record.push_back(Words[I]);
1032}
1033
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001034void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1035 Record.push_back(Value.isUnsigned());
1036 AddAPInt(Value, Record);
1037}
1038
Douglas Gregorc34897d2009-04-09 22:27:44 +00001039void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001040 if (II == 0) {
1041 Record.push_back(0);
1042 return;
1043 }
1044
1045 pch::IdentID &ID = IdentifierIDs[II];
1046 if (ID == 0)
1047 ID = IdentifierIDs.size();
1048
1049 Record.push_back(ID);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001050}
1051
1052void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1053 if (T.isNull()) {
1054 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1055 return;
1056 }
1057
1058 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001059 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001060 switch (BT->getKind()) {
1061 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1062 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1063 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1064 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1065 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1066 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1067 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1068 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1069 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1070 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1071 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1072 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1073 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1074 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1075 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1076 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1077 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1078 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1079 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1080 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1081 }
1082
1083 Record.push_back((ID << 3) | T.getCVRQualifiers());
1084 return;
1085 }
1086
Douglas Gregorac8f2802009-04-10 17:25:41 +00001087 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001088 if (ID == 0) // we haven't seen this type before
1089 ID = NextTypeID++;
1090
1091 // Encode the type qualifiers in the type reference.
1092 Record.push_back((ID << 3) | T.getCVRQualifiers());
1093}
1094
1095void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1096 if (D == 0) {
1097 Record.push_back(0);
1098 return;
1099 }
1100
Douglas Gregorac8f2802009-04-10 17:25:41 +00001101 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001102 if (ID == 0) {
1103 // We haven't seen this declaration before. Give it a new ID and
1104 // enqueue it in the list of declarations to emit.
1105 ID = DeclIDs.size();
1106 DeclsToEmit.push(const_cast<Decl *>(D));
1107 }
1108
1109 Record.push_back(ID);
1110}
1111
1112void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
1113 Record.push_back(Name.getNameKind());
1114 switch (Name.getNameKind()) {
1115 case DeclarationName::Identifier:
1116 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1117 break;
1118
1119 case DeclarationName::ObjCZeroArgSelector:
1120 case DeclarationName::ObjCOneArgSelector:
1121 case DeclarationName::ObjCMultiArgSelector:
1122 assert(false && "Serialization of Objective-C selectors unavailable");
1123 break;
1124
1125 case DeclarationName::CXXConstructorName:
1126 case DeclarationName::CXXDestructorName:
1127 case DeclarationName::CXXConversionFunctionName:
1128 AddTypeRef(Name.getCXXNameType(), Record);
1129 break;
1130
1131 case DeclarationName::CXXOperatorName:
1132 Record.push_back(Name.getCXXOverloadedOperator());
1133 break;
1134
1135 case DeclarationName::CXXUsingDirective:
1136 // No extra data to emit
1137 break;
1138 }
1139}