blob: a31c0c79855af3ec9d79374f7653fabadda1ec6a [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 Gregorb5887f32009-04-10 21:16:55 +000024#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000025#include "llvm/Bitcode/BitstreamWriter.h"
26#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "llvm/Support/MemoryBuffer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000028
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Type serialization
33//===----------------------------------------------------------------------===//
34namespace {
35 class VISIBILITY_HIDDEN PCHTypeWriter {
36 PCHWriter &Writer;
37 PCHWriter::RecordData &Record;
38
39 public:
40 /// \brief Type code that corresponds to the record generated.
41 pch::TypeCode Code;
42
43 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
44 : Writer(Writer), Record(Record) { }
45
46 void VisitArrayType(const ArrayType *T);
47 void VisitFunctionType(const FunctionType *T);
48 void VisitTagType(const TagType *T);
49
50#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
51#define ABSTRACT_TYPE(Class, Base)
52#define DEPENDENT_TYPE(Class, Base)
53#include "clang/AST/TypeNodes.def"
54 };
55}
56
57void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
58 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
59 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
60 Record.push_back(T->getAddressSpace());
61 Code = pch::TYPE_EXT_QUAL;
62}
63
64void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
65 assert(false && "Built-in types are never serialized");
66}
67
68void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
69 Record.push_back(T->getWidth());
70 Record.push_back(T->isSigned());
71 Code = pch::TYPE_FIXED_WIDTH_INT;
72}
73
74void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
75 Writer.AddTypeRef(T->getElementType(), Record);
76 Code = pch::TYPE_COMPLEX;
77}
78
79void PCHTypeWriter::VisitPointerType(const PointerType *T) {
80 Writer.AddTypeRef(T->getPointeeType(), Record);
81 Code = pch::TYPE_POINTER;
82}
83
84void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
85 Writer.AddTypeRef(T->getPointeeType(), Record);
86 Code = pch::TYPE_BLOCK_POINTER;
87}
88
89void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_LVALUE_REFERENCE;
92}
93
94void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_RVALUE_REFERENCE;
97}
98
99void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
102 Code = pch::TYPE_MEMBER_POINTER;
103}
104
105void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
106 Writer.AddTypeRef(T->getElementType(), Record);
107 Record.push_back(T->getSizeModifier()); // FIXME: stable values
108 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
109}
110
111void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
112 VisitArrayType(T);
113 Writer.AddAPInt(T->getSize(), Record);
114 Code = pch::TYPE_CONSTANT_ARRAY;
115}
116
117void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
118 VisitArrayType(T);
119 Code = pch::TYPE_INCOMPLETE_ARRAY;
120}
121
122void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
123 VisitArrayType(T);
124 // FIXME: Serialize array size expression.
125 assert(false && "Cannot serialize variable-length arrays");
126 Code = pch::TYPE_VARIABLE_ARRAY;
127}
128
129void PCHTypeWriter::VisitVectorType(const VectorType *T) {
130 Writer.AddTypeRef(T->getElementType(), Record);
131 Record.push_back(T->getNumElements());
132 Code = pch::TYPE_VECTOR;
133}
134
135void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
136 VisitVectorType(T);
137 Code = pch::TYPE_EXT_VECTOR;
138}
139
140void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
141 Writer.AddTypeRef(T->getResultType(), Record);
142}
143
144void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
145 VisitFunctionType(T);
146 Code = pch::TYPE_FUNCTION_NO_PROTO;
147}
148
149void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
150 VisitFunctionType(T);
151 Record.push_back(T->getNumArgs());
152 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
153 Writer.AddTypeRef(T->getArgType(I), Record);
154 Record.push_back(T->isVariadic());
155 Record.push_back(T->getTypeQuals());
156 Code = pch::TYPE_FUNCTION_PROTO;
157}
158
159void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
160 Writer.AddDeclRef(T->getDecl(), Record);
161 Code = pch::TYPE_TYPEDEF;
162}
163
164void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
165 // FIXME: serialize the typeof expression
166 assert(false && "Cannot serialize typeof(expr)");
167 Code = pch::TYPE_TYPEOF_EXPR;
168}
169
170void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
171 Writer.AddTypeRef(T->getUnderlyingType(), Record);
172 Code = pch::TYPE_TYPEOF;
173}
174
175void PCHTypeWriter::VisitTagType(const TagType *T) {
176 Writer.AddDeclRef(T->getDecl(), Record);
177 assert(!T->isBeingDefined() &&
178 "Cannot serialize in the middle of a type definition");
179}
180
181void PCHTypeWriter::VisitRecordType(const RecordType *T) {
182 VisitTagType(T);
183 Code = pch::TYPE_RECORD;
184}
185
186void PCHTypeWriter::VisitEnumType(const EnumType *T) {
187 VisitTagType(T);
188 Code = pch::TYPE_ENUM;
189}
190
191void
192PCHTypeWriter::VisitTemplateSpecializationType(
193 const TemplateSpecializationType *T) {
194 // FIXME: Serialize this type
195 assert(false && "Cannot serialize template specialization types");
196}
197
198void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
199 // FIXME: Serialize this type
200 assert(false && "Cannot serialize qualified name types");
201}
202
203void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
204 Writer.AddDeclRef(T->getDecl(), Record);
205 Code = pch::TYPE_OBJC_INTERFACE;
206}
207
208void
209PCHTypeWriter::VisitObjCQualifiedInterfaceType(
210 const ObjCQualifiedInterfaceType *T) {
211 VisitObjCInterfaceType(T);
212 Record.push_back(T->getNumProtocols());
213 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
214 Writer.AddDeclRef(T->getProtocol(I), Record);
215 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
216}
217
218void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
219 Record.push_back(T->getNumProtocols());
220 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
221 Writer.AddDeclRef(T->getProtocols(I), Record);
222 Code = pch::TYPE_OBJC_QUALIFIED_ID;
223}
224
225void
226PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
227 Record.push_back(T->getNumProtocols());
228 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
229 Writer.AddDeclRef(T->getProtocols(I), Record);
230 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
231}
232
233//===----------------------------------------------------------------------===//
234// Declaration serialization
235//===----------------------------------------------------------------------===//
236namespace {
237 class VISIBILITY_HIDDEN PCHDeclWriter
238 : public DeclVisitor<PCHDeclWriter, void> {
239
240 PCHWriter &Writer;
241 PCHWriter::RecordData &Record;
242
243 public:
244 pch::DeclCode Code;
245
246 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
247 : Writer(Writer), Record(Record) { }
248
249 void VisitDecl(Decl *D);
250 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
251 void VisitNamedDecl(NamedDecl *D);
252 void VisitTypeDecl(TypeDecl *D);
253 void VisitTypedefDecl(TypedefDecl *D);
254 void VisitValueDecl(ValueDecl *D);
255 void VisitVarDecl(VarDecl *D);
256
257 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
258 uint64_t VisibleOffset);
259 };
260}
261
262void PCHDeclWriter::VisitDecl(Decl *D) {
263 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
264 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
265 Writer.AddSourceLocation(D->getLocation(), Record);
266 Record.push_back(D->isInvalidDecl());
267 // FIXME: hasAttrs
268 Record.push_back(D->isImplicit());
269 Record.push_back(D->getAccess());
270}
271
272void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
273 VisitDecl(D);
274 Code = pch::DECL_TRANSLATION_UNIT;
275}
276
277void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
278 VisitDecl(D);
279 Writer.AddDeclarationName(D->getDeclName(), Record);
280}
281
282void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
283 VisitNamedDecl(D);
284 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
285}
286
287void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
288 VisitTypeDecl(D);
289 Writer.AddTypeRef(D->getUnderlyingType(), Record);
290 Code = pch::DECL_TYPEDEF;
291}
292
293void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
294 VisitNamedDecl(D);
295 Writer.AddTypeRef(D->getType(), Record);
296}
297
298void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
299 VisitValueDecl(D);
300 Record.push_back(D->getStorageClass());
301 Record.push_back(D->isThreadSpecified());
302 Record.push_back(D->hasCXXDirectInitializer());
303 Record.push_back(D->isDeclaredInCondition());
304 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
305 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
306 // FIXME: emit initializer
307 Code = pch::DECL_VAR;
308}
309
310/// \brief Emit the DeclContext part of a declaration context decl.
311///
312/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
313/// block for this declaration context is stored. May be 0 to indicate
314/// that there are no declarations stored within this context.
315///
316/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
317/// block for this declaration context is stored. May be 0 to indicate
318/// that there are no declarations visible from this context. Note
319/// that this value will not be emitted for non-primary declaration
320/// contexts.
321void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
322 uint64_t VisibleOffset) {
323 Record.push_back(LexicalOffset);
324 if (DC->getPrimaryContext() == DC)
325 Record.push_back(VisibleOffset);
326}
327
328//===----------------------------------------------------------------------===//
329// PCHWriter Implementation
330//===----------------------------------------------------------------------===//
331
Douglas Gregorb5887f32009-04-10 21:16:55 +0000332/// \brief Write the target triple (e.g., i686-apple-darwin9).
333void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
334 using namespace llvm;
335 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
336 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
338 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
339
340 RecordData Record;
341 Record.push_back(pch::TARGET_TRIPLE);
342 const char *Triple = Target.getTargetTriple();
343 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
344}
345
346/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000347void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
348 RecordData Record;
349 Record.push_back(LangOpts.Trigraphs);
350 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
351 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
352 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
353 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
354 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
355 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
356 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
357 Record.push_back(LangOpts.C99); // C99 Support
358 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
359 Record.push_back(LangOpts.CPlusPlus); // C++ Support
360 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
361 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
362 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
363
364 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
365 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
366 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
367
368 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
369 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
370 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
371 Record.push_back(LangOpts.LaxVectorConversions);
372 Record.push_back(LangOpts.Exceptions); // Support exception handling.
373
374 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
375 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
376 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
377
378 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
379 // by locks.
380 Record.push_back(LangOpts.Blocks); // block extension to C
381 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
382 // they are unused.
383 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
384 // (modulo the platform support).
385
386 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
387 // signed integer arithmetic overflows.
388
389 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
390 // may be ripped out at any time.
391
392 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
393 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
394 // defined.
395 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
396 // opposed to __DYNAMIC__).
397 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
398
399 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
400 // used (instead of C99 semantics).
401 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
402 Record.push_back(LangOpts.getGCMode());
403 Record.push_back(LangOpts.getVisibilityMode());
404 Record.push_back(LangOpts.InstantiationDepth);
405 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
406}
407
Douglas Gregorab1cef72009-04-10 03:52:48 +0000408//===----------------------------------------------------------------------===//
409// Source Manager Serialization
410//===----------------------------------------------------------------------===//
411
412/// \brief Create an abbreviation for the SLocEntry that refers to a
413/// file.
414static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
415 using namespace llvm;
416 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
417 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
422 // FIXME: Need an actual encoding for the line directives; maybe
423 // this should be an array?
424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
425 return S.EmitAbbrev(Abbrev);
426}
427
428/// \brief Create an abbreviation for the SLocEntry that refers to a
429/// buffer.
430static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
431 using namespace llvm;
432 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
433 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
437 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
438 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
439 return S.EmitAbbrev(Abbrev);
440}
441
442/// \brief Create an abbreviation for the SLocEntry that refers to a
443/// buffer's blob.
444static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
445 using namespace llvm;
446 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
447 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
449 return S.EmitAbbrev(Abbrev);
450}
451
452/// \brief Create an abbreviation for the SLocEntry that refers to an
453/// buffer.
454static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
455 using namespace llvm;
456 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
457 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
462 return S.EmitAbbrev(Abbrev);
463}
464
465/// \brief Writes the block containing the serialized form of the
466/// source manager.
467///
468/// TODO: We should probably use an on-disk hash table (stored in a
469/// blob), indexed based on the file name, so that we only create
470/// entries for files that we actually need. In the common case (no
471/// errors), we probably won't have to create file entries for any of
472/// the files in the AST.
473void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000474 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000475 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
476
477 // Abbreviations for the various kinds of source-location entries.
478 int SLocFileAbbrv = -1;
479 int SLocBufferAbbrv = -1;
480 int SLocBufferBlobAbbrv = -1;
481 int SLocInstantiationAbbrv = -1;
482
483 // Write out the source location entry table. We skip the first
484 // entry, which is always the same dummy entry.
485 RecordData Record;
486 for (SourceManager::sloc_entry_iterator
487 SLoc = SourceMgr.sloc_entry_begin() + 1,
488 SLocEnd = SourceMgr.sloc_entry_end();
489 SLoc != SLocEnd; ++SLoc) {
490 // Figure out which record code to use.
491 unsigned Code;
492 if (SLoc->isFile()) {
493 if (SLoc->getFile().getContentCache()->Entry)
494 Code = pch::SM_SLOC_FILE_ENTRY;
495 else
496 Code = pch::SM_SLOC_BUFFER_ENTRY;
497 } else
498 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
499 Record.push_back(Code);
500
501 Record.push_back(SLoc->getOffset());
502 if (SLoc->isFile()) {
503 const SrcMgr::FileInfo &File = SLoc->getFile();
504 Record.push_back(File.getIncludeLoc().getRawEncoding());
505 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
506 Record.push_back(File.hasLineDirectives()); // FIXME: encode the
507 // line directives?
508
509 const SrcMgr::ContentCache *Content = File.getContentCache();
510 if (Content->Entry) {
511 // The source location entry is a file. The blob associated
512 // with this entry is the file name.
513 if (SLocFileAbbrv == -1)
514 SLocFileAbbrv = CreateSLocFileAbbrev(S);
515 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
516 Content->Entry->getName(),
517 strlen(Content->Entry->getName()));
518 } else {
519 // The source location entry is a buffer. The blob associated
520 // with this entry contains the contents of the buffer.
521 if (SLocBufferAbbrv == -1) {
522 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
523 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
524 }
525
526 // We add one to the size so that we capture the trailing NULL
527 // that is required by llvm::MemoryBuffer::getMemBuffer (on
528 // the reader side).
529 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
530 const char *Name = Buffer->getBufferIdentifier();
531 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
532 Record.clear();
533 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
534 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
535 Buffer->getBufferStart(),
536 Buffer->getBufferSize() + 1);
537 }
538 } else {
539 // The source location entry is an instantiation.
540 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
541 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
542 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
543 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
544
545 if (SLocInstantiationAbbrv == -1)
546 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
547 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
548 }
549
550 Record.clear();
551 }
552
553 S.ExitBlock();
554}
555
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000556/// \brief Writes the block containing the serialized form of the
557/// preprocessor.
558///
Chris Lattner850eabd2009-04-10 18:08:30 +0000559void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000560 // Enter the preprocessor block.
561 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
562
Chris Lattner1b094952009-04-10 18:00:12 +0000563 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
564 // FIXME: use diagnostics subsystem for localization etc.
565 if (PP.SawDateOrTime())
566 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000567
Chris Lattner1b094952009-04-10 18:00:12 +0000568 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000569
Chris Lattner1b094952009-04-10 18:00:12 +0000570 // Loop over all the macro definitions that are live at the end of the file,
571 // emitting each to the PP section.
572 // FIXME: Eventually we want to emit an index so that we can lazily load
573 // macros.
574 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
575 I != E; ++I) {
576 MacroInfo *MI = I->second;
577
578 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
579 // been redefined by the header (in which case they are not isBuiltinMacro).
580 if (MI->isBuiltinMacro())
581 continue;
582
583 IdentifierInfo *II = I->first;
584
Chris Lattner0523c012009-04-10 18:22:18 +0000585 // FIXME: Emit a PP_MACRO_NAME for testing. This should be removed when we
586 // have identifierinfo id's.
587 for (unsigned i = 0, e = II->getLength(); i != e; ++i)
588 Record.push_back(II->getName()[i]);
589 S.EmitRecord(pch::PP_MACRO_NAME, Record);
590 Record.clear();
591
Chris Lattner1b094952009-04-10 18:00:12 +0000592 // FIXME: Output the identifier Info ID #!
593 Record.push_back((intptr_t)II);
594 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
595 Record.push_back(MI->isUsed());
596
597 unsigned Code;
598 if (MI->isObjectLike()) {
599 Code = pch::PP_MACRO_OBJECT_LIKE;
600 } else {
601 Code = pch::PP_MACRO_FUNCTION_LIKE;
602
603 Record.push_back(MI->isC99Varargs());
604 Record.push_back(MI->isGNUVarargs());
605 Record.push_back(MI->getNumArgs());
606 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
607 I != E; ++I)
608 // FIXME: Output the identifier Info ID #!
609 Record.push_back((intptr_t)II);
610 }
611 S.EmitRecord(Code, Record);
612 Record.clear();
613
Chris Lattner850eabd2009-04-10 18:08:30 +0000614 // Emit the tokens array.
615 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
616 // Note that we know that the preprocessor does not have any annotation
617 // tokens in it because they are created by the parser, and thus can't be
618 // in a macro definition.
619 const Token &Tok = MI->getReplacementToken(TokNo);
620
621 Record.push_back(Tok.getLocation().getRawEncoding());
622 Record.push_back(Tok.getLength());
623
624 // FIXME: Output the identifier Info ID #!
625 // FIXME: When reading literal tokens, reconstruct the literal pointer if
626 // it is needed.
627 Record.push_back((intptr_t)Tok.getIdentifierInfo());
628
629 // FIXME: Should translate token kind to a stable encoding.
630 Record.push_back(Tok.getKind());
631 // FIXME: Should translate token flags to a stable encoding.
632 Record.push_back(Tok.getFlags());
633
634 S.EmitRecord(pch::PP_TOKEN, Record);
635 Record.clear();
636 }
Chris Lattner1b094952009-04-10 18:00:12 +0000637
638 }
639
640 // TODO: someday when PP supports __COUNTER__, emit a record for its value if
641 // non-zero.
Chris Lattner84b04f12009-04-10 17:16:57 +0000642
643 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000644}
645
646
Douglas Gregorc34897d2009-04-09 22:27:44 +0000647/// \brief Write the representation of a type to the PCH stream.
648void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000649 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000650 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000651 ID = NextTypeID++;
652
653 // Record the offset for this type.
654 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
655 TypeOffsets.push_back(S.GetCurrentBitNo());
656 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
657 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
658 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
659 }
660
661 RecordData Record;
662
663 // Emit the type's representation.
664 PCHTypeWriter W(*this, Record);
665 switch (T->getTypeClass()) {
666 // For all of the concrete, non-dependent types, call the
667 // appropriate visitor function.
668#define TYPE(Class, Base) \
669 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
670#define ABSTRACT_TYPE(Class, Base)
671#define DEPENDENT_TYPE(Class, Base)
672#include "clang/AST/TypeNodes.def"
673
674 // For all of the dependent type nodes (which only occur in C++
675 // templates), produce an error.
676#define TYPE(Class, Base)
677#define DEPENDENT_TYPE(Class, Base) case Type::Class:
678#include "clang/AST/TypeNodes.def"
679 assert(false && "Cannot serialize dependent type nodes");
680 break;
681 }
682
683 // Emit the serialized record.
684 S.EmitRecord(W.Code, Record);
685}
686
687/// \brief Write a block containing all of the types.
688void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000689 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000690 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
691
692 // Emit all of the types in the ASTContext
693 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
694 TEnd = Context.getTypes().end();
695 T != TEnd; ++T) {
696 // Builtin types are never serialized.
697 if (isa<BuiltinType>(*T))
698 continue;
699
700 WriteType(*T);
701 }
702
703 // Exit the types block
704 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000705}
706
707/// \brief Write the block containing all of the declaration IDs
708/// lexically declared within the given DeclContext.
709///
710/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
711/// bistream, or 0 if no block was written.
712uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
713 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000714 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000715 return 0;
716
717 uint64_t Offset = S.GetCurrentBitNo();
718 RecordData Record;
719 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
720 DEnd = DC->decls_end(Context);
721 D != DEnd; ++D)
722 AddDeclRef(*D, Record);
723
724 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
725 return Offset;
726}
727
728/// \brief Write the block containing all of the declaration IDs
729/// visible from the given DeclContext.
730///
731/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
732/// bistream, or 0 if no block was written.
733uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
734 DeclContext *DC) {
735 if (DC->getPrimaryContext() != DC)
736 return 0;
737
738 // Force the DeclContext to build a its name-lookup table.
739 DC->lookup(Context, DeclarationName());
740
741 // Serialize the contents of the mapping used for lookup. Note that,
742 // although we have two very different code paths, the serialized
743 // representation is the same for both cases: a declaration name,
744 // followed by a size, followed by references to the visible
745 // declarations that have that name.
746 uint64_t Offset = S.GetCurrentBitNo();
747 RecordData Record;
748 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
749 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
750 D != DEnd; ++D) {
751 AddDeclarationName(D->first, Record);
752 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
753 Record.push_back(Result.second - Result.first);
754 for(; Result.first != Result.second; ++Result.first)
755 AddDeclRef(*Result.first, Record);
756 }
757
758 if (Record.size() == 0)
759 return 0;
760
761 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
762 return Offset;
763}
764
765/// \brief Write a block containing all of the declarations.
766void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000767 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000768 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
769
770 // Emit all of the declarations.
771 RecordData Record;
772 PCHDeclWriter W(*this, Record);
773 while (!DeclsToEmit.empty()) {
774 // Pull the next declaration off the queue
775 Decl *D = DeclsToEmit.front();
776 DeclsToEmit.pop();
777
778 // If this declaration is also a DeclContext, write blocks for the
779 // declarations that lexically stored inside its context and those
780 // declarations that are visible from its context. These blocks
781 // are written before the declaration itself so that we can put
782 // their offsets into the record for the declaration.
783 uint64_t LexicalOffset = 0;
784 uint64_t VisibleOffset = 0;
785 DeclContext *DC = dyn_cast<DeclContext>(D);
786 if (DC) {
787 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
788 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
789 }
790
791 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +0000792 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000793 if (ID == 0)
794 ID = DeclIDs.size();
795
796 unsigned Index = ID - 1;
797
798 // Record the offset for this declaration
799 if (DeclOffsets.size() == Index)
800 DeclOffsets.push_back(S.GetCurrentBitNo());
801 else if (DeclOffsets.size() < Index) {
802 DeclOffsets.resize(Index+1);
803 DeclOffsets[Index] = S.GetCurrentBitNo();
804 }
805
806 // Build and emit a record for this declaration
807 Record.clear();
808 W.Code = (pch::DeclCode)0;
809 W.Visit(D);
810 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
811 assert(W.Code && "Visitor did not set record code");
812 S.EmitRecord(W.Code, Record);
813 }
814
815 // Exit the declarations block
816 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000817}
818
819PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
820 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
821
Chris Lattner850eabd2009-04-10 18:08:30 +0000822void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000823 // Emit the file header.
824 S.Emit((unsigned)'C', 8);
825 S.Emit((unsigned)'P', 8);
826 S.Emit((unsigned)'C', 8);
827 S.Emit((unsigned)'H', 8);
828
829 // The translation unit is the first declaration we'll emit.
830 DeclIDs[Context.getTranslationUnitDecl()] = 1;
831 DeclsToEmit.push(Context.getTranslationUnitDecl());
832
833 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +0000834 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
835 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000836 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000837 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000838 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000839 WriteTypesBlock(Context);
840 WriteDeclsBlock(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000841 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
842 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000843 S.ExitBlock();
844}
845
846void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
847 Record.push_back(Loc.getRawEncoding());
848}
849
850void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
851 Record.push_back(Value.getBitWidth());
852 unsigned N = Value.getNumWords();
853 const uint64_t* Words = Value.getRawData();
854 for (unsigned I = 0; I != N; ++I)
855 Record.push_back(Words[I]);
856}
857
858void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
859 // FIXME: Emit an identifier ID, not the actual string!
860 const char *Name = II->getName();
861 unsigned Len = strlen(Name);
862 Record.push_back(Len);
863 Record.insert(Record.end(), Name, Name + Len);
864}
865
866void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
867 if (T.isNull()) {
868 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
869 return;
870 }
871
872 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000873 pch::TypeID ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000874 switch (BT->getKind()) {
875 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
876 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
877 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
878 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
879 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
880 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
881 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
882 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
883 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
884 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
885 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
886 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
887 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
888 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
889 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
890 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
891 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
892 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
893 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
894 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
895 }
896
897 Record.push_back((ID << 3) | T.getCVRQualifiers());
898 return;
899 }
900
Douglas Gregorac8f2802009-04-10 17:25:41 +0000901 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000902 if (ID == 0) // we haven't seen this type before
903 ID = NextTypeID++;
904
905 // Encode the type qualifiers in the type reference.
906 Record.push_back((ID << 3) | T.getCVRQualifiers());
907}
908
909void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
910 if (D == 0) {
911 Record.push_back(0);
912 return;
913 }
914
Douglas Gregorac8f2802009-04-10 17:25:41 +0000915 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000916 if (ID == 0) {
917 // We haven't seen this declaration before. Give it a new ID and
918 // enqueue it in the list of declarations to emit.
919 ID = DeclIDs.size();
920 DeclsToEmit.push(const_cast<Decl *>(D));
921 }
922
923 Record.push_back(ID);
924}
925
926void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
927 Record.push_back(Name.getNameKind());
928 switch (Name.getNameKind()) {
929 case DeclarationName::Identifier:
930 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
931 break;
932
933 case DeclarationName::ObjCZeroArgSelector:
934 case DeclarationName::ObjCOneArgSelector:
935 case DeclarationName::ObjCMultiArgSelector:
936 assert(false && "Serialization of Objective-C selectors unavailable");
937 break;
938
939 case DeclarationName::CXXConstructorName:
940 case DeclarationName::CXXDestructorName:
941 case DeclarationName::CXXConversionFunctionName:
942 AddTypeRef(Name.getCXXNameType(), Record);
943 break;
944
945 case DeclarationName::CXXOperatorName:
946 Record.push_back(Name.getCXXOverloadedOperator());
947 break;
948
949 case DeclarationName::CXXUsingDirective:
950 // No extra data to emit
951 break;
952 }
953}