1 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTWriter class, which writes AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTWriter.h"
15 #include "clang/Serialization/ASTSerializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Sema/Sema.h"
18 #include "clang/Sema/IdentifierResolver.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemStatCache.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Basic/VersionTuple.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/APInt.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Bitcode/BitstreamWriter.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
50 using namespace clang;
51 using namespace clang::serialization;
53 template <typename T, typename Allocator>
54 static llvm::StringRef data(const std::vector<T, Allocator> &v) {
55 if (v.empty()) return llvm::StringRef();
56 return llvm::StringRef(reinterpret_cast<const char*>(&v[0]),
57 sizeof(T) * v.size());
61 static llvm::StringRef data(const llvm::SmallVectorImpl<T> &v) {
62 return llvm::StringRef(reinterpret_cast<const char*>(v.data()),
63 sizeof(T) * v.size());
66 //===----------------------------------------------------------------------===//
68 //===----------------------------------------------------------------------===//
73 ASTWriter::RecordDataImpl &Record;
76 /// \brief Type code that corresponds to the record generated.
79 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
80 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
82 void VisitArrayType(const ArrayType *T);
83 void VisitFunctionType(const FunctionType *T);
84 void VisitTagType(const TagType *T);
86 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
87 #define ABSTRACT_TYPE(Class, Base)
88 #include "clang/AST/TypeNodes.def"
92 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
93 assert(false && "Built-in types are never serialized");
96 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
97 Writer.AddTypeRef(T->getElementType(), Record);
101 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
102 Writer.AddTypeRef(T->getPointeeType(), Record);
106 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
107 Writer.AddTypeRef(T->getPointeeType(), Record);
108 Code = TYPE_BLOCK_POINTER;
111 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
112 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
113 Record.push_back(T->isSpelledAsLValue());
114 Code = TYPE_LVALUE_REFERENCE;
117 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
118 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
119 Code = TYPE_RVALUE_REFERENCE;
122 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
123 Writer.AddTypeRef(T->getPointeeType(), Record);
124 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
125 Code = TYPE_MEMBER_POINTER;
128 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
129 Writer.AddTypeRef(T->getElementType(), Record);
130 Record.push_back(T->getSizeModifier()); // FIXME: stable values
131 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
134 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
136 Writer.AddAPInt(T->getSize(), Record);
137 Code = TYPE_CONSTANT_ARRAY;
140 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
142 Code = TYPE_INCOMPLETE_ARRAY;
145 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
147 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
148 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
149 Writer.AddStmt(T->getSizeExpr());
150 Code = TYPE_VARIABLE_ARRAY;
153 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
154 Writer.AddTypeRef(T->getElementType(), Record);
155 Record.push_back(T->getNumElements());
156 Record.push_back(T->getVectorKind());
160 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
162 Code = TYPE_EXT_VECTOR;
165 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
166 Writer.AddTypeRef(T->getResultType(), Record);
167 FunctionType::ExtInfo C = T->getExtInfo();
168 Record.push_back(C.getNoReturn());
169 Record.push_back(C.getHasRegParm());
170 Record.push_back(C.getRegParm());
171 // FIXME: need to stabilize encoding of calling convention...
172 Record.push_back(C.getCC());
173 Record.push_back(C.getProducesResult());
176 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
177 VisitFunctionType(T);
178 Code = TYPE_FUNCTION_NO_PROTO;
181 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
182 VisitFunctionType(T);
183 Record.push_back(T->getNumArgs());
184 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
185 Writer.AddTypeRef(T->getArgType(I), Record);
186 Record.push_back(T->isVariadic());
187 Record.push_back(T->getTypeQuals());
188 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
189 Record.push_back(T->getExceptionSpecType());
190 if (T->getExceptionSpecType() == EST_Dynamic) {
191 Record.push_back(T->getNumExceptions());
192 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
193 Writer.AddTypeRef(T->getExceptionType(I), Record);
194 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
195 Writer.AddStmt(T->getNoexceptExpr());
197 Code = TYPE_FUNCTION_PROTO;
200 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
201 Writer.AddDeclRef(T->getDecl(), Record);
202 Code = TYPE_UNRESOLVED_USING;
205 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
206 Writer.AddDeclRef(T->getDecl(), Record);
207 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
208 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
212 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
213 Writer.AddStmt(T->getUnderlyingExpr());
214 Code = TYPE_TYPEOF_EXPR;
217 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
218 Writer.AddTypeRef(T->getUnderlyingType(), Record);
222 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
223 Writer.AddStmt(T->getUnderlyingExpr());
224 Code = TYPE_DECLTYPE;
227 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
228 Writer.AddTypeRef(T->getBaseType(), Record);
229 Writer.AddTypeRef(T->getUnderlyingType(), Record);
230 Record.push_back(T->getUTTKind());
231 Code = TYPE_UNARY_TRANSFORM;
234 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
235 Writer.AddTypeRef(T->getDeducedType(), Record);
239 void ASTTypeWriter::VisitTagType(const TagType *T) {
240 Record.push_back(T->isDependentType());
241 Writer.AddDeclRef(T->getDecl(), Record);
242 assert(!T->isBeingDefined() &&
243 "Cannot serialize in the middle of a type definition");
246 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
251 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
256 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
257 Writer.AddTypeRef(T->getModifiedType(), Record);
258 Writer.AddTypeRef(T->getEquivalentType(), Record);
259 Record.push_back(T->getAttrKind());
260 Code = TYPE_ATTRIBUTED;
264 ASTTypeWriter::VisitSubstTemplateTypeParmType(
265 const SubstTemplateTypeParmType *T) {
266 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
267 Writer.AddTypeRef(T->getReplacementType(), Record);
268 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
272 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
273 const SubstTemplateTypeParmPackType *T) {
274 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
275 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
276 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
280 ASTTypeWriter::VisitTemplateSpecializationType(
281 const TemplateSpecializationType *T) {
282 Record.push_back(T->isDependentType());
283 Writer.AddTemplateName(T->getTemplateName(), Record);
284 Record.push_back(T->getNumArgs());
285 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
286 ArgI != ArgE; ++ArgI)
287 Writer.AddTemplateArgument(*ArgI, Record);
288 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
289 T->isCanonicalUnqualified() ? QualType()
290 : T->getCanonicalTypeInternal(),
292 Code = TYPE_TEMPLATE_SPECIALIZATION;
296 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
298 Writer.AddStmt(T->getSizeExpr());
299 Writer.AddSourceRange(T->getBracketsRange(), Record);
300 Code = TYPE_DEPENDENT_SIZED_ARRAY;
304 ASTTypeWriter::VisitDependentSizedExtVectorType(
305 const DependentSizedExtVectorType *T) {
306 // FIXME: Serialize this type (C++ only)
307 assert(false && "Cannot serialize dependent sized extended vector types");
311 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
312 Record.push_back(T->getDepth());
313 Record.push_back(T->getIndex());
314 Record.push_back(T->isParameterPack());
315 Writer.AddDeclRef(T->getDecl(), Record);
316 Code = TYPE_TEMPLATE_TYPE_PARM;
320 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
321 Record.push_back(T->getKeyword());
322 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
323 Writer.AddIdentifierRef(T->getIdentifier(), Record);
324 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
325 : T->getCanonicalTypeInternal(),
327 Code = TYPE_DEPENDENT_NAME;
331 ASTTypeWriter::VisitDependentTemplateSpecializationType(
332 const DependentTemplateSpecializationType *T) {
333 Record.push_back(T->getKeyword());
334 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
335 Writer.AddIdentifierRef(T->getIdentifier(), Record);
336 Record.push_back(T->getNumArgs());
337 for (DependentTemplateSpecializationType::iterator
338 I = T->begin(), E = T->end(); I != E; ++I)
339 Writer.AddTemplateArgument(*I, Record);
340 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
343 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
344 Writer.AddTypeRef(T->getPattern(), Record);
345 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
346 Record.push_back(*NumExpansions + 1);
349 Code = TYPE_PACK_EXPANSION;
352 void ASTTypeWriter::VisitParenType(const ParenType *T) {
353 Writer.AddTypeRef(T->getInnerType(), Record);
357 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
358 Record.push_back(T->getKeyword());
359 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
360 Writer.AddTypeRef(T->getNamedType(), Record);
361 Code = TYPE_ELABORATED;
364 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
365 Writer.AddDeclRef(T->getDecl(), Record);
366 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
367 Code = TYPE_INJECTED_CLASS_NAME;
370 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
371 Writer.AddDeclRef(T->getDecl(), Record);
372 Code = TYPE_OBJC_INTERFACE;
375 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
376 Writer.AddTypeRef(T->getBaseType(), Record);
377 Record.push_back(T->getNumProtocols());
378 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
379 E = T->qual_end(); I != E; ++I)
380 Writer.AddDeclRef(*I, Record);
381 Code = TYPE_OBJC_OBJECT;
385 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
386 Writer.AddTypeRef(T->getPointeeType(), Record);
387 Code = TYPE_OBJC_OBJECT_POINTER;
392 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
394 ASTWriter::RecordDataImpl &Record;
397 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
398 : Writer(Writer), Record(Record) { }
400 #define ABSTRACT_TYPELOC(CLASS, PARENT)
401 #define TYPELOC(CLASS, PARENT) \
402 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
403 #include "clang/AST/TypeLocNodes.def"
405 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
406 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
411 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
414 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
415 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
416 if (TL.needsExtraLocalData()) {
417 Record.push_back(TL.getWrittenTypeSpec());
418 Record.push_back(TL.getWrittenSignSpec());
419 Record.push_back(TL.getWrittenWidthSpec());
420 Record.push_back(TL.hasModeAttr());
423 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
424 Writer.AddSourceLocation(TL.getNameLoc(), Record);
426 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
427 Writer.AddSourceLocation(TL.getStarLoc(), Record);
429 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
430 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
432 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
433 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
435 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
436 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
438 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
439 Writer.AddSourceLocation(TL.getStarLoc(), Record);
440 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
442 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
443 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
444 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
445 Record.push_back(TL.getSizeExpr() ? 1 : 0);
446 if (TL.getSizeExpr())
447 Writer.AddStmt(TL.getSizeExpr());
449 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
450 VisitArrayTypeLoc(TL);
452 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
453 VisitArrayTypeLoc(TL);
455 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
456 VisitArrayTypeLoc(TL);
458 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
459 DependentSizedArrayTypeLoc TL) {
460 VisitArrayTypeLoc(TL);
462 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
463 DependentSizedExtVectorTypeLoc TL) {
464 Writer.AddSourceLocation(TL.getNameLoc(), Record);
466 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
467 Writer.AddSourceLocation(TL.getNameLoc(), Record);
469 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
470 Writer.AddSourceLocation(TL.getNameLoc(), Record);
472 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
473 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
474 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
475 Record.push_back(TL.getTrailingReturn());
476 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
477 Writer.AddDeclRef(TL.getArg(i), Record);
479 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
480 VisitFunctionTypeLoc(TL);
482 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
483 VisitFunctionTypeLoc(TL);
485 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
486 Writer.AddSourceLocation(TL.getNameLoc(), Record);
488 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
489 Writer.AddSourceLocation(TL.getNameLoc(), Record);
491 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
492 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
493 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
494 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
496 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
497 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
498 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
499 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
500 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
502 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
503 Writer.AddSourceLocation(TL.getNameLoc(), Record);
505 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
506 Writer.AddSourceLocation(TL.getKWLoc(), Record);
507 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
508 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
509 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
511 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
512 Writer.AddSourceLocation(TL.getNameLoc(), Record);
514 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
515 Writer.AddSourceLocation(TL.getNameLoc(), Record);
517 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
518 Writer.AddSourceLocation(TL.getNameLoc(), Record);
520 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
521 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
522 if (TL.hasAttrOperand()) {
523 SourceRange range = TL.getAttrOperandParensRange();
524 Writer.AddSourceLocation(range.getBegin(), Record);
525 Writer.AddSourceLocation(range.getEnd(), Record);
527 if (TL.hasAttrExprOperand()) {
528 Expr *operand = TL.getAttrExprOperand();
529 Record.push_back(operand ? 1 : 0);
530 if (operand) Writer.AddStmt(operand);
531 } else if (TL.hasAttrEnumOperand()) {
532 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
535 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
536 Writer.AddSourceLocation(TL.getNameLoc(), Record);
538 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
539 SubstTemplateTypeParmTypeLoc TL) {
540 Writer.AddSourceLocation(TL.getNameLoc(), Record);
542 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
543 SubstTemplateTypeParmPackTypeLoc TL) {
544 Writer.AddSourceLocation(TL.getNameLoc(), Record);
546 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
547 TemplateSpecializationTypeLoc TL) {
548 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
549 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
550 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
551 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
552 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
553 TL.getArgLoc(i).getLocInfo(), Record);
555 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
556 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
557 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
559 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
560 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
561 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
563 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
564 Writer.AddSourceLocation(TL.getNameLoc(), Record);
566 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
567 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
568 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
569 Writer.AddSourceLocation(TL.getNameLoc(), Record);
571 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
572 DependentTemplateSpecializationTypeLoc TL) {
573 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
574 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
575 Writer.AddSourceLocation(TL.getNameLoc(), Record);
576 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
577 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
578 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
579 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
580 TL.getArgLoc(I).getLocInfo(), Record);
582 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
583 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
585 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
586 Writer.AddSourceLocation(TL.getNameLoc(), Record);
588 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
589 Record.push_back(TL.hasBaseTypeAsWritten());
590 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
591 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
592 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
593 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
595 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
596 Writer.AddSourceLocation(TL.getStarLoc(), Record);
599 //===----------------------------------------------------------------------===//
600 // ASTWriter Implementation
601 //===----------------------------------------------------------------------===//
603 static void EmitBlockID(unsigned ID, const char *Name,
604 llvm::BitstreamWriter &Stream,
605 ASTWriter::RecordDataImpl &Record) {
607 Record.push_back(ID);
608 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
610 // Emit the block name if present.
611 if (Name == 0 || Name[0] == 0) return;
614 Record.push_back(*Name++);
615 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
618 static void EmitRecordID(unsigned ID, const char *Name,
619 llvm::BitstreamWriter &Stream,
620 ASTWriter::RecordDataImpl &Record) {
622 Record.push_back(ID);
624 Record.push_back(*Name++);
625 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
628 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
629 ASTWriter::RecordDataImpl &Record) {
630 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
632 RECORD(STMT_NULL_PTR);
634 RECORD(STMT_COMPOUND);
636 RECORD(STMT_DEFAULT);
644 RECORD(STMT_INDIRECT_GOTO);
645 RECORD(STMT_CONTINUE);
650 RECORD(EXPR_PREDEFINED);
651 RECORD(EXPR_DECL_REF);
652 RECORD(EXPR_INTEGER_LITERAL);
653 RECORD(EXPR_FLOATING_LITERAL);
654 RECORD(EXPR_IMAGINARY_LITERAL);
655 RECORD(EXPR_STRING_LITERAL);
656 RECORD(EXPR_CHARACTER_LITERAL);
658 RECORD(EXPR_UNARY_OPERATOR);
659 RECORD(EXPR_SIZEOF_ALIGN_OF);
660 RECORD(EXPR_ARRAY_SUBSCRIPT);
663 RECORD(EXPR_BINARY_OPERATOR);
664 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
665 RECORD(EXPR_CONDITIONAL_OPERATOR);
666 RECORD(EXPR_IMPLICIT_CAST);
667 RECORD(EXPR_CSTYLE_CAST);
668 RECORD(EXPR_COMPOUND_LITERAL);
669 RECORD(EXPR_EXT_VECTOR_ELEMENT);
670 RECORD(EXPR_INIT_LIST);
671 RECORD(EXPR_DESIGNATED_INIT);
672 RECORD(EXPR_IMPLICIT_VALUE_INIT);
674 RECORD(EXPR_ADDR_LABEL);
677 RECORD(EXPR_GNU_NULL);
678 RECORD(EXPR_SHUFFLE_VECTOR);
680 RECORD(EXPR_BLOCK_DECL_REF);
681 RECORD(EXPR_GENERIC_SELECTION);
682 RECORD(EXPR_OBJC_STRING_LITERAL);
683 RECORD(EXPR_OBJC_ENCODE);
684 RECORD(EXPR_OBJC_SELECTOR_EXPR);
685 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
686 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
687 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
688 RECORD(EXPR_OBJC_KVC_REF_EXPR);
689 RECORD(EXPR_OBJC_MESSAGE_EXPR);
690 RECORD(STMT_OBJC_FOR_COLLECTION);
691 RECORD(STMT_OBJC_CATCH);
692 RECORD(STMT_OBJC_FINALLY);
693 RECORD(STMT_OBJC_AT_TRY);
694 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
695 RECORD(STMT_OBJC_AT_THROW);
696 RECORD(EXPR_CXX_OPERATOR_CALL);
697 RECORD(EXPR_CXX_CONSTRUCT);
698 RECORD(EXPR_CXX_STATIC_CAST);
699 RECORD(EXPR_CXX_DYNAMIC_CAST);
700 RECORD(EXPR_CXX_REINTERPRET_CAST);
701 RECORD(EXPR_CXX_CONST_CAST);
702 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
703 RECORD(EXPR_CXX_BOOL_LITERAL);
704 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
705 RECORD(EXPR_CXX_TYPEID_EXPR);
706 RECORD(EXPR_CXX_TYPEID_TYPE);
707 RECORD(EXPR_CXX_UUIDOF_EXPR);
708 RECORD(EXPR_CXX_UUIDOF_TYPE);
709 RECORD(EXPR_CXX_THIS);
710 RECORD(EXPR_CXX_THROW);
711 RECORD(EXPR_CXX_DEFAULT_ARG);
712 RECORD(EXPR_CXX_BIND_TEMPORARY);
713 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
714 RECORD(EXPR_CXX_NEW);
715 RECORD(EXPR_CXX_DELETE);
716 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
717 RECORD(EXPR_EXPR_WITH_CLEANUPS);
718 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
719 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
720 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
721 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
722 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
723 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
724 RECORD(EXPR_CXX_NOEXCEPT);
725 RECORD(EXPR_OPAQUE_VALUE);
726 RECORD(EXPR_BINARY_TYPE_TRAIT);
727 RECORD(EXPR_PACK_EXPANSION);
728 RECORD(EXPR_SIZEOF_PACK);
729 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
730 RECORD(EXPR_CUDA_KERNEL_CALL);
734 void ASTWriter::WriteBlockInfoBlock() {
736 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
738 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
739 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
741 // AST Top-Level Block.
743 RECORD(ORIGINAL_FILE_NAME);
744 RECORD(ORIGINAL_FILE_ID);
747 RECORD(LANGUAGE_OPTIONS);
749 RECORD(IDENTIFIER_OFFSET);
750 RECORD(IDENTIFIER_TABLE);
751 RECORD(EXTERNAL_DEFINITIONS);
752 RECORD(SPECIAL_TYPES);
754 RECORD(TENTATIVE_DEFINITIONS);
755 RECORD(UNUSED_FILESCOPED_DECLS);
756 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
757 RECORD(SELECTOR_OFFSETS);
759 RECORD(PP_COUNTER_VALUE);
760 RECORD(SOURCE_LOCATION_OFFSETS);
761 RECORD(SOURCE_LOCATION_PRELOADS);
763 RECORD(EXT_VECTOR_DECLS);
764 RECORD(VERSION_CONTROL_BRANCH_REVISION);
765 RECORD(MACRO_DEFINITION_OFFSETS);
766 RECORD(CHAINED_METADATA);
767 RECORD(REFERENCED_SELECTOR_POOL);
768 RECORD(TU_UPDATE_LEXICAL);
769 RECORD(REDECLS_UPDATE_LATEST);
770 RECORD(SEMA_DECL_REFS);
771 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
772 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
773 RECORD(DECL_REPLACEMENTS);
774 RECORD(UPDATE_VISIBLE);
775 RECORD(DECL_UPDATE_OFFSETS);
776 RECORD(DECL_UPDATES);
777 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
778 RECORD(DIAG_PRAGMA_MAPPINGS);
779 RECORD(CUDA_SPECIAL_DECL_REFS);
780 RECORD(HEADER_SEARCH_TABLE);
781 RECORD(FP_PRAGMA_OPTIONS);
782 RECORD(OPENCL_EXTENSIONS);
783 RECORD(DELEGATING_CTORS);
784 RECORD(FILE_SOURCE_LOCATION_OFFSETS);
785 RECORD(KNOWN_NAMESPACES);
787 // SourceManager Block.
788 BLOCK(SOURCE_MANAGER_BLOCK);
789 RECORD(SM_SLOC_FILE_ENTRY);
790 RECORD(SM_SLOC_BUFFER_ENTRY);
791 RECORD(SM_SLOC_BUFFER_BLOB);
792 RECORD(SM_SLOC_EXPANSION_ENTRY);
793 RECORD(SM_LINE_TABLE);
795 // Preprocessor Block.
796 BLOCK(PREPROCESSOR_BLOCK);
797 RECORD(PP_MACRO_OBJECT_LIKE);
798 RECORD(PP_MACRO_FUNCTION_LIKE);
801 // Decls and Types block.
802 BLOCK(DECLTYPES_BLOCK);
803 RECORD(TYPE_EXT_QUAL);
804 RECORD(TYPE_COMPLEX);
805 RECORD(TYPE_POINTER);
806 RECORD(TYPE_BLOCK_POINTER);
807 RECORD(TYPE_LVALUE_REFERENCE);
808 RECORD(TYPE_RVALUE_REFERENCE);
809 RECORD(TYPE_MEMBER_POINTER);
810 RECORD(TYPE_CONSTANT_ARRAY);
811 RECORD(TYPE_INCOMPLETE_ARRAY);
812 RECORD(TYPE_VARIABLE_ARRAY);
814 RECORD(TYPE_EXT_VECTOR);
815 RECORD(TYPE_FUNCTION_PROTO);
816 RECORD(TYPE_FUNCTION_NO_PROTO);
817 RECORD(TYPE_TYPEDEF);
818 RECORD(TYPE_TYPEOF_EXPR);
822 RECORD(TYPE_OBJC_INTERFACE);
823 RECORD(TYPE_OBJC_OBJECT);
824 RECORD(TYPE_OBJC_OBJECT_POINTER);
825 RECORD(TYPE_DECLTYPE);
826 RECORD(TYPE_ELABORATED);
827 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
828 RECORD(TYPE_UNRESOLVED_USING);
829 RECORD(TYPE_INJECTED_CLASS_NAME);
830 RECORD(TYPE_OBJC_OBJECT);
831 RECORD(TYPE_TEMPLATE_TYPE_PARM);
832 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
833 RECORD(TYPE_DEPENDENT_NAME);
834 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
835 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
837 RECORD(TYPE_PACK_EXPANSION);
838 RECORD(TYPE_ATTRIBUTED);
839 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
840 RECORD(DECL_TRANSLATION_UNIT);
841 RECORD(DECL_TYPEDEF);
844 RECORD(DECL_ENUM_CONSTANT);
845 RECORD(DECL_FUNCTION);
846 RECORD(DECL_OBJC_METHOD);
847 RECORD(DECL_OBJC_INTERFACE);
848 RECORD(DECL_OBJC_PROTOCOL);
849 RECORD(DECL_OBJC_IVAR);
850 RECORD(DECL_OBJC_AT_DEFS_FIELD);
851 RECORD(DECL_OBJC_CLASS);
852 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
853 RECORD(DECL_OBJC_CATEGORY);
854 RECORD(DECL_OBJC_CATEGORY_IMPL);
855 RECORD(DECL_OBJC_IMPLEMENTATION);
856 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
857 RECORD(DECL_OBJC_PROPERTY);
858 RECORD(DECL_OBJC_PROPERTY_IMPL);
861 RECORD(DECL_IMPLICIT_PARAM);
862 RECORD(DECL_PARM_VAR);
863 RECORD(DECL_FILE_SCOPE_ASM);
865 RECORD(DECL_CONTEXT_LEXICAL);
866 RECORD(DECL_CONTEXT_VISIBLE);
867 RECORD(DECL_NAMESPACE);
868 RECORD(DECL_NAMESPACE_ALIAS);
870 RECORD(DECL_USING_SHADOW);
871 RECORD(DECL_USING_DIRECTIVE);
872 RECORD(DECL_UNRESOLVED_USING_VALUE);
873 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
874 RECORD(DECL_LINKAGE_SPEC);
875 RECORD(DECL_CXX_RECORD);
876 RECORD(DECL_CXX_METHOD);
877 RECORD(DECL_CXX_CONSTRUCTOR);
878 RECORD(DECL_CXX_DESTRUCTOR);
879 RECORD(DECL_CXX_CONVERSION);
880 RECORD(DECL_ACCESS_SPEC);
882 RECORD(DECL_FRIEND_TEMPLATE);
883 RECORD(DECL_CLASS_TEMPLATE);
884 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
885 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
886 RECORD(DECL_FUNCTION_TEMPLATE);
887 RECORD(DECL_TEMPLATE_TYPE_PARM);
888 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
889 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
890 RECORD(DECL_STATIC_ASSERT);
891 RECORD(DECL_CXX_BASE_SPECIFIERS);
892 RECORD(DECL_INDIRECTFIELD);
893 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
895 // Statements and Exprs can occur in the Decls and Types block.
896 AddStmtsExprs(Stream, Record);
898 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
899 RECORD(PPD_MACRO_EXPANSION);
900 RECORD(PPD_MACRO_DEFINITION);
901 RECORD(PPD_INCLUSION_DIRECTIVE);
908 /// \brief Adjusts the given filename to only write out the portion of the
909 /// filename that is not part of the system root directory.
911 /// \param Filename the file name to adjust.
913 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
914 /// the returned filename will be adjusted by this system root.
916 /// \returns either the original filename (if it needs no adjustment) or the
917 /// adjusted filename (which points into the @p Filename parameter).
919 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
920 assert(Filename && "No file name to adjust?");
925 // Verify that the filename and the system root have the same prefix.
927 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
928 if (Filename[Pos] != isysroot[Pos])
929 return Filename; // Prefixes don't match.
931 // We hit the end of the filename before we hit the end of the system root.
935 // If the file name has a '/' at the current position, skip over the '/'.
936 // We distinguish sysroot-based includes from absolute includes by the
937 // absence of '/' at the beginning of sysroot-based includes.
938 if (Filename[Pos] == '/')
941 return Filename + Pos;
944 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
945 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot,
946 const std::string &OutputFile) {
947 using namespace llvm;
950 const TargetInfo &Target = Context.Target;
951 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
952 MetaAbbrev->Add(BitCodeAbbrevOp(
953 Chain ? CHAINED_METADATA : METADATA));
954 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
955 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
956 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
957 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
958 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
959 // Target triple or chained PCH name
960 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
961 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
964 Record.push_back(Chain ? CHAINED_METADATA : METADATA);
965 Record.push_back(VERSION_MAJOR);
966 Record.push_back(VERSION_MINOR);
967 Record.push_back(CLANG_VERSION_MAJOR);
968 Record.push_back(CLANG_VERSION_MINOR);
969 Record.push_back(isysroot != 0);
970 // FIXME: This writes the absolute path for chained headers.
971 const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
972 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
974 // Original file name and file ID
975 SourceManager &SM = Context.getSourceManager();
976 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
977 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
978 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
979 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
980 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
982 llvm::SmallString<128> MainFilePath(MainFile->getName());
984 llvm::sys::fs::make_absolute(MainFilePath);
986 const char *MainFileNameStr = MainFilePath.c_str();
987 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
990 Record.push_back(ORIGINAL_FILE_NAME);
991 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
994 Record.push_back(SM.getMainFileID().getOpaqueValue());
995 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
998 // Original PCH directory
999 if (!OutputFile.empty() && OutputFile != "-") {
1000 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1001 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1002 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1003 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1005 llvm::SmallString<128> OutputPath(OutputFile);
1007 llvm::sys::fs::make_absolute(OutputPath);
1008 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1011 Record.push_back(ORIGINAL_PCH_DIR);
1012 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1015 // Repository branch/version information.
1016 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
1017 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
1018 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1019 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
1021 Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
1022 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
1023 getClangFullRepositoryVersion());
1026 /// \brief Write the LangOptions structure.
1027 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1029 Record.push_back(LangOpts.Trigraphs);
1030 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
1031 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
1032 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
1033 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
1034 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords
1035 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
1036 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
1037 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
1038 Record.push_back(LangOpts.C99); // C99 Support
1039 Record.push_back(LangOpts.C1X); // C1X Support
1040 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
1041 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
1042 // already saved elsewhere.
1043 Record.push_back(LangOpts.CPlusPlus); // C++ Support
1044 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
1045 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
1047 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
1048 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
1049 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C
1050 // modern abi enabled.
1051 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
1052 // modern abi enabled.
1053 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI
1054 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
1055 // properties enabled.
1056 Record.push_back(LangOpts.ObjCInferRelatedResultType);
1057 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
1059 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
1060 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
1061 Record.push_back(LangOpts.LaxVectorConversions);
1062 Record.push_back(LangOpts.AltiVec);
1063 Record.push_back(LangOpts.Exceptions); // Support exception handling.
1064 Record.push_back(LangOpts.ObjCExceptions);
1065 Record.push_back(LangOpts.CXXExceptions);
1066 Record.push_back(LangOpts.SjLjExceptions);
1068 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout
1069 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
1070 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
1071 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
1073 // Whether static initializers are protected by locks.
1074 Record.push_back(LangOpts.ThreadsafeStatics);
1075 Record.push_back(LangOpts.POSIXThreads);
1076 Record.push_back(LangOpts.Blocks); // block extension to C
1077 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
1079 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
1080 // (modulo the platform support).
1082 Record.push_back(LangOpts.getSignedOverflowBehavior());
1083 Record.push_back(LangOpts.HeinousExtensions);
1085 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
1086 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
1088 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
1089 // opposed to __DYNAMIC__).
1090 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
1092 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
1093 // used (instead of C99 semantics).
1094 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
1095 Record.push_back(LangOpts.Deprecated); // Should __DEPRECATED be defined.
1096 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
1098 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
1100 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short
1101 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent
1102 // to the smallest integer type with
1104 Record.push_back(LangOpts.getGCMode());
1105 Record.push_back(LangOpts.getVisibilityMode());
1106 Record.push_back(LangOpts.getStackProtectorMode());
1107 Record.push_back(LangOpts.InstantiationDepth);
1108 Record.push_back(LangOpts.OpenCL);
1109 Record.push_back(LangOpts.CUDA);
1110 Record.push_back(LangOpts.CatchUndefined);
1111 Record.push_back(LangOpts.DefaultFPContract);
1112 Record.push_back(LangOpts.ElideConstructors);
1113 Record.push_back(LangOpts.SpellChecking);
1114 Record.push_back(LangOpts.MRTD);
1115 Record.push_back(LangOpts.ObjCAutoRefCount);
1116 Record.push_back(LangOpts.ObjCInferRelatedReturnType);
1117 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1120 //===----------------------------------------------------------------------===//
1121 // stat cache Serialization
1122 //===----------------------------------------------------------------------===//
1125 // Trait used for the on-disk hash table of stat cache results.
1126 class ASTStatCacheTrait {
1128 typedef const char * key_type;
1129 typedef key_type key_type_ref;
1131 typedef struct stat data_type;
1132 typedef const data_type &data_type_ref;
1134 static unsigned ComputeHash(const char *path) {
1135 return llvm::HashString(path);
1138 std::pair<unsigned,unsigned>
1139 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1140 data_type_ref Data) {
1141 unsigned StrLen = strlen(path);
1142 clang::io::Emit16(Out, StrLen);
1143 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1144 clang::io::Emit8(Out, DataLen);
1145 return std::make_pair(StrLen + 1, DataLen);
1148 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1149 Out.write(path, KeyLen);
1152 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1153 data_type_ref Data, unsigned DataLen) {
1154 using namespace clang::io;
1155 uint64_t Start = Out.tell(); (void)Start;
1157 Emit32(Out, (uint32_t) Data.st_ino);
1158 Emit32(Out, (uint32_t) Data.st_dev);
1159 Emit16(Out, (uint16_t) Data.st_mode);
1160 Emit64(Out, (uint64_t) Data.st_mtime);
1161 Emit64(Out, (uint64_t) Data.st_size);
1163 assert(Out.tell() - Start == DataLen && "Wrong data length");
1166 } // end anonymous namespace
1168 /// \brief Write the stat() system call cache to the AST file.
1169 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1170 // Build the on-disk hash table containing information about every
1172 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1173 unsigned NumStatEntries = 0;
1174 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1175 StatEnd = StatCalls.end();
1176 Stat != StatEnd; ++Stat, ++NumStatEntries) {
1177 llvm::StringRef Filename = Stat->first();
1178 Generator.insert(Filename.data(), Stat->second);
1181 // Create the on-disk hash table in a buffer.
1182 llvm::SmallString<4096> StatCacheData;
1183 uint32_t BucketOffset;
1185 llvm::raw_svector_ostream Out(StatCacheData);
1186 // Make sure that no bucket is at offset 0
1187 clang::io::Emit32(Out, 0);
1188 BucketOffset = Generator.Emit(Out);
1191 // Create a blob abbreviation
1192 using namespace llvm;
1193 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1194 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1198 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1200 // Write the stat cache
1202 Record.push_back(STAT_CACHE);
1203 Record.push_back(BucketOffset);
1204 Record.push_back(NumStatEntries);
1205 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1208 //===----------------------------------------------------------------------===//
1209 // Source Manager Serialization
1210 //===----------------------------------------------------------------------===//
1212 /// \brief Create an abbreviation for the SLocEntry that refers to a
1214 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1215 using namespace llvm;
1216 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1217 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1222 // FileEntry fields.
1223 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1224 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1226 return Stream.EmitAbbrev(Abbrev);
1229 /// \brief Create an abbreviation for the SLocEntry that refers to a
1231 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1232 using namespace llvm;
1233 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1234 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1235 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1236 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1237 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1238 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1240 return Stream.EmitAbbrev(Abbrev);
1243 /// \brief Create an abbreviation for the SLocEntry that refers to a
1245 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1246 using namespace llvm;
1247 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1248 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1249 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1250 return Stream.EmitAbbrev(Abbrev);
1253 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1255 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1256 using namespace llvm;
1257 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1258 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1259 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1260 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1262 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1264 return Stream.EmitAbbrev(Abbrev);
1268 // Trait used for the on-disk hash table of header search information.
1269 class HeaderFileInfoTrait {
1274 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)
1275 : Writer(Writer), HS(HS) { }
1277 typedef const char *key_type;
1278 typedef key_type key_type_ref;
1280 typedef HeaderFileInfo data_type;
1281 typedef const data_type &data_type_ref;
1283 static unsigned ComputeHash(const char *path) {
1284 // The hash is based only on the filename portion of the key, so that the
1285 // reader can match based on filenames when symlinking or excess path
1286 // elements ("foo/../", "../") change the form of the name. However,
1287 // complete path is still the key.
1288 return llvm::HashString(llvm::sys::path::filename(path));
1291 std::pair<unsigned,unsigned>
1292 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1293 data_type_ref Data) {
1294 unsigned StrLen = strlen(path);
1295 clang::io::Emit16(Out, StrLen);
1296 unsigned DataLen = 1 + 2 + 4;
1297 clang::io::Emit8(Out, DataLen);
1298 return std::make_pair(StrLen + 1, DataLen);
1301 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1302 Out.write(path, KeyLen);
1305 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1306 data_type_ref Data, unsigned DataLen) {
1307 using namespace clang::io;
1308 uint64_t Start = Out.tell(); (void)Start;
1310 unsigned char Flags = (Data.isImport << 4)
1311 | (Data.isPragmaOnce << 3)
1312 | (Data.DirInfo << 1)
1314 Emit8(Out, (uint8_t)Flags);
1315 Emit16(Out, (uint16_t) Data.NumIncludes);
1317 if (!Data.ControllingMacro)
1318 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1320 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1321 assert(Out.tell() - Start == DataLen && "Wrong data length");
1324 } // end anonymous namespace
1326 /// \brief Write the header search block for the list of files that
1328 /// \param HS The header search structure to save.
1330 /// \param Chain Whether we're creating a chained AST file.
1331 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, const char* isysroot) {
1332 llvm::SmallVector<const FileEntry *, 16> FilesByUID;
1333 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1335 if (FilesByUID.size() > HS.header_file_size())
1336 FilesByUID.resize(HS.header_file_size());
1338 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1339 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1340 llvm::SmallVector<const char *, 4> SavedStrings;
1341 unsigned NumHeaderSearchEntries = 0;
1342 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1343 const FileEntry *File = FilesByUID[UID];
1347 const HeaderFileInfo &HFI = HS.header_file_begin()[UID];
1348 if (HFI.External && Chain)
1351 // Turn the file name into an absolute path, if it isn't already.
1352 const char *Filename = File->getName();
1353 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1355 // If we performed any translation on the file name at all, we need to
1356 // save this string, since the generator will refer to it later.
1357 if (Filename != File->getName()) {
1358 Filename = strdup(Filename);
1359 SavedStrings.push_back(Filename);
1362 Generator.insert(Filename, HFI, GeneratorTrait);
1363 ++NumHeaderSearchEntries;
1366 // Create the on-disk hash table in a buffer.
1367 llvm::SmallString<4096> TableData;
1368 uint32_t BucketOffset;
1370 llvm::raw_svector_ostream Out(TableData);
1371 // Make sure that no bucket is at offset 0
1372 clang::io::Emit32(Out, 0);
1373 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1376 // Create a blob abbreviation
1377 using namespace llvm;
1378 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1379 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1383 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1385 // Write the stat cache
1387 Record.push_back(HEADER_SEARCH_TABLE);
1388 Record.push_back(BucketOffset);
1389 Record.push_back(NumHeaderSearchEntries);
1390 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1392 // Free all of the strings we had to duplicate.
1393 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1394 free((void*)SavedStrings[I]);
1397 /// \brief Writes the block containing the serialized form of the
1400 /// TODO: We should probably use an on-disk hash table (stored in a
1401 /// blob), indexed based on the file name, so that we only create
1402 /// entries for files that we actually need. In the common case (no
1403 /// errors), we probably won't have to create file entries for any of
1404 /// the files in the AST.
1405 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1406 const Preprocessor &PP,
1407 const char *isysroot) {
1410 // Enter the source manager block.
1411 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1413 // Abbreviations for the various kinds of source-location entries.
1414 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1415 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1416 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1417 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1419 // Write the line table.
1420 if (SourceMgr.hasLineTable()) {
1421 LineTableInfo &LineTable = SourceMgr.getLineTable();
1423 // Emit the file names
1424 Record.push_back(LineTable.getNumFilenames());
1425 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1426 // Emit the file name
1427 const char *Filename = LineTable.getFilename(I);
1428 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1429 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1430 Record.push_back(FilenameLen);
1432 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1435 // Emit the line entries
1436 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1439 Record.push_back(L->first);
1441 // Emit the line entries
1442 Record.push_back(L->second.size());
1443 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1444 LEEnd = L->second.end();
1445 LE != LEEnd; ++LE) {
1446 Record.push_back(LE->FileOffset);
1447 Record.push_back(LE->LineNo);
1448 Record.push_back(LE->FilenameID);
1449 Record.push_back((unsigned)LE->FileKind);
1450 Record.push_back(LE->IncludeOffset);
1453 Stream.EmitRecord(SM_LINE_TABLE, Record);
1456 // Write out the source location entry table. We skip the first
1457 // entry, which is always the same dummy entry.
1458 std::vector<uint32_t> SLocEntryOffsets;
1459 // Write out the offsets of only source location file entries.
1460 // We will go through them in ASTReader::validateFileEntries().
1461 std::vector<uint32_t> SLocFileEntryOffsets;
1462 RecordData PreloadSLocs;
1463 unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1464 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1465 for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1467 // Get this source location entry.
1468 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1470 // Record the offset of this source-location entry.
1471 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1473 // Figure out which record code to use.
1475 if (SLoc->isFile()) {
1476 if (SLoc->getFile().getContentCache()->OrigEntry) {
1477 Code = SM_SLOC_FILE_ENTRY;
1478 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
1480 Code = SM_SLOC_BUFFER_ENTRY;
1482 Code = SM_SLOC_EXPANSION_ENTRY;
1484 Record.push_back(Code);
1486 Record.push_back(SLoc->getOffset());
1487 if (SLoc->isFile()) {
1488 const SrcMgr::FileInfo &File = SLoc->getFile();
1489 Record.push_back(File.getIncludeLoc().getRawEncoding());
1490 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1491 Record.push_back(File.hasLineDirectives());
1493 const SrcMgr::ContentCache *Content = File.getContentCache();
1494 if (Content->OrigEntry) {
1495 assert(Content->OrigEntry == Content->ContentsEntry &&
1496 "Writing to AST an overriden file is not supported");
1498 // The source location entry is a file. The blob associated
1499 // with this entry is the file name.
1501 // Emit size/modification time for this file.
1502 Record.push_back(Content->OrigEntry->getSize());
1503 Record.push_back(Content->OrigEntry->getModificationTime());
1505 // Turn the file name into an absolute path, if it isn't already.
1506 const char *Filename = Content->OrigEntry->getName();
1507 llvm::SmallString<128> FilePath(Filename);
1509 // Ask the file manager to fixup the relative path for us. This will
1510 // honor the working directory.
1511 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1513 // FIXME: This call to make_absolute shouldn't be necessary, the
1514 // call to FixupRelativePath should always return an absolute path.
1515 llvm::sys::fs::make_absolute(FilePath);
1516 Filename = FilePath.c_str();
1518 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1519 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1521 // The source location entry is a buffer. The blob associated
1522 // with this entry contains the contents of the buffer.
1524 // We add one to the size so that we capture the trailing NULL
1525 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1526 // the reader side).
1527 const llvm::MemoryBuffer *Buffer
1528 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1529 const char *Name = Buffer->getBufferIdentifier();
1530 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1531 llvm::StringRef(Name, strlen(Name) + 1));
1533 Record.push_back(SM_SLOC_BUFFER_BLOB);
1534 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1535 llvm::StringRef(Buffer->getBufferStart(),
1536 Buffer->getBufferSize() + 1));
1538 if (strcmp(Name, "<built-in>") == 0)
1539 PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1542 // The source location entry is a macro expansion.
1543 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1544 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1545 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1546 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1548 // Compute the token length for this macro expansion.
1549 unsigned NextOffset = SourceMgr.getNextOffset();
1551 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1552 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1553 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1559 if (SLocEntryOffsets.empty())
1562 // Write the source-location offsets table into the AST block. This
1563 // table is used for lazily loading source-location information.
1564 using namespace llvm;
1565 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1566 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1570 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1573 Record.push_back(SOURCE_LOCATION_OFFSETS);
1574 Record.push_back(SLocEntryOffsets.size());
1575 unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1576 Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1577 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1579 Abbrev = new BitCodeAbbrev();
1580 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
1581 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1582 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1583 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1586 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
1587 Record.push_back(SLocFileEntryOffsets.size());
1588 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
1589 data(SLocFileEntryOffsets));
1591 // Write the source location entry preloads array, telling the AST
1592 // reader which source locations entries it should load eagerly.
1593 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1596 //===----------------------------------------------------------------------===//
1597 // Preprocessor Serialization
1598 //===----------------------------------------------------------------------===//
1600 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1601 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1602 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1603 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1604 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1605 return X.first->getName().compare(Y.first->getName());
1608 /// \brief Writes the block containing the serialized form of the
1611 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1614 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1615 if (PP.getCounterValue() != 0) {
1616 Record.push_back(PP.getCounterValue());
1617 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1621 // Enter the preprocessor block.
1622 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1624 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1625 // FIXME: use diagnostics subsystem for localization etc.
1626 if (PP.SawDateOrTime())
1627 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1630 // Loop over all the macro definitions that are live at the end of the file,
1631 // emitting each to the PP section.
1632 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1634 // Construct the list of macro definitions that need to be serialized.
1635 llvm::SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1637 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1638 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1639 E = PP.macro_end(Chain == 0);
1641 MacroDefinitionsSeen.insert(I->first);
1642 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1645 // Sort the set of macro definitions that need to be serialized by the
1646 // name of the macro, to provide a stable ordering.
1647 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1648 &compareMacroDefinitions);
1650 // Resolve any identifiers that defined macros at the time they were
1651 // deserialized, adding them to the list of macros to emit (if appropriate).
1652 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1653 IdentifierInfo *Name
1654 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1655 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1656 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1659 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1660 const IdentifierInfo *Name = MacrosToEmit[I].first;
1661 MacroInfo *MI = MacrosToEmit[I].second;
1665 // Don't emit builtin macros like __LINE__ to the AST file unless they have
1666 // been redefined by the header (in which case they are not isBuiltinMacro).
1667 // Also skip macros from a AST file if we're chaining.
1669 // FIXME: There is a (probably minor) optimization we could do here, if
1670 // the macro comes from the original PCH but the identifier comes from a
1671 // chained PCH, by storing the offset into the original PCH rather than
1672 // writing the macro definition a second time.
1673 if (MI->isBuiltinMacro() ||
1674 (Chain && Name->isFromAST() && MI->isFromAST()))
1677 AddIdentifierRef(Name, Record);
1678 MacroOffsets[Name] = Stream.GetCurrentBitNo();
1679 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1680 Record.push_back(MI->isUsed());
1683 if (MI->isObjectLike()) {
1684 Code = PP_MACRO_OBJECT_LIKE;
1686 Code = PP_MACRO_FUNCTION_LIKE;
1688 Record.push_back(MI->isC99Varargs());
1689 Record.push_back(MI->isGNUVarargs());
1690 Record.push_back(MI->getNumArgs());
1691 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1693 AddIdentifierRef(*I, Record);
1696 // If we have a detailed preprocessing record, record the macro definition
1697 // ID that corresponds to this macro.
1699 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1701 Stream.EmitRecord(Code, Record);
1704 // Emit the tokens array.
1705 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1706 // Note that we know that the preprocessor does not have any annotation
1707 // tokens in it because they are created by the parser, and thus can't be
1708 // in a macro definition.
1709 const Token &Tok = MI->getReplacementToken(TokNo);
1711 Record.push_back(Tok.getLocation().getRawEncoding());
1712 Record.push_back(Tok.getLength());
1714 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1716 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1717 // FIXME: Should translate token kind to a stable encoding.
1718 Record.push_back(Tok.getKind());
1719 // FIXME: Should translate token flags to a stable encoding.
1720 Record.push_back(Tok.getFlags());
1722 Stream.EmitRecord(PP_TOKEN, Record);
1730 WritePreprocessorDetail(*PPRec);
1733 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1734 if (PPRec.begin(Chain) == PPRec.end(Chain))
1737 // Enter the preprocessor block.
1738 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1740 // If the preprocessor has a preprocessing record, emit it.
1741 unsigned NumPreprocessingRecords = 0;
1742 using namespace llvm;
1744 // Set up the abbreviation for
1745 unsigned InclusionAbbrev = 0;
1747 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1748 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1756 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1759 unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0;
1761 for (PreprocessingRecord::iterator E = PPRec.begin(Chain),
1762 EEnd = PPRec.end(Chain);
1766 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1767 // Record this macro definition's location.
1768 MacroID ID = getMacroDefinitionID(MD);
1770 // Don't write the macro definition if it is from another AST file.
1771 if (ID < FirstMacroID)
1774 // Notify the serialization listener that we're serializing this entity.
1775 if (SerializationListener)
1776 SerializationListener->SerializedPreprocessedEntity(*E,
1777 Stream.GetCurrentBitNo());
1779 unsigned Position = ID - FirstMacroID;
1780 if (Position != MacroDefinitionOffsets.size()) {
1781 if (Position > MacroDefinitionOffsets.size())
1782 MacroDefinitionOffsets.resize(Position + 1);
1784 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1786 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1788 Record.push_back(IndexBase + NumPreprocessingRecords++);
1789 Record.push_back(ID);
1790 AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1791 AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1792 AddIdentifierRef(MD->getName(), Record);
1793 AddSourceLocation(MD->getLocation(), Record);
1794 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1798 // Notify the serialization listener that we're serializing this entity.
1799 if (SerializationListener)
1800 SerializationListener->SerializedPreprocessedEntity(*E,
1801 Stream.GetCurrentBitNo());
1803 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
1804 Record.push_back(IndexBase + NumPreprocessingRecords++);
1805 AddSourceLocation(ME->getSourceRange().getBegin(), Record);
1806 AddSourceLocation(ME->getSourceRange().getEnd(), Record);
1807 AddIdentifierRef(ME->getName(), Record);
1808 Record.push_back(getMacroDefinitionID(ME->getDefinition()));
1809 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
1813 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1814 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1815 Record.push_back(IndexBase + NumPreprocessingRecords++);
1816 AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1817 AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1818 Record.push_back(ID->getFileName().size());
1819 Record.push_back(ID->wasInQuotes());
1820 Record.push_back(static_cast<unsigned>(ID->getKind()));
1821 llvm::SmallString<64> Buffer;
1822 Buffer += ID->getFileName();
1823 Buffer += ID->getFile()->getName();
1824 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1828 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1832 // Write the offsets table for the preprocessing record.
1833 if (NumPreprocessingRecords > 0) {
1834 // Write the offsets table for identifier IDs.
1835 using namespace llvm;
1836 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1837 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1841 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1844 Record.push_back(MACRO_DEFINITION_OFFSETS);
1845 Record.push_back(NumPreprocessingRecords);
1846 Record.push_back(MacroDefinitionOffsets.size());
1847 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1848 data(MacroDefinitionOffsets));
1852 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) {
1854 for (Diagnostic::DiagStatePointsTy::const_iterator
1855 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
1857 const Diagnostic::DiagStatePoint &point = *I;
1858 if (point.Loc.isInvalid())
1861 Record.push_back(point.Loc.getRawEncoding());
1862 for (Diagnostic::DiagState::iterator
1863 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
1864 unsigned diag = I->first, map = I->second;
1865 if (map & 0x10) { // mapping from a diagnostic pragma.
1866 Record.push_back(diag);
1867 Record.push_back(map & 0x7);
1870 Record.push_back(-1); // mark the end of the diag/map pairs for this
1874 if (!Record.empty())
1875 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
1878 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
1879 if (CXXBaseSpecifiersOffsets.empty())
1884 // Create a blob abbreviation for the C++ base specifiers offsets.
1885 using namespace llvm;
1887 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1888 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
1889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1891 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1893 // Write the selector offsets table.
1895 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
1896 Record.push_back(CXXBaseSpecifiersOffsets.size());
1897 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
1898 data(CXXBaseSpecifiersOffsets));
1901 //===----------------------------------------------------------------------===//
1902 // Type Serialization
1903 //===----------------------------------------------------------------------===//
1905 /// \brief Write the representation of a type to the AST stream.
1906 void ASTWriter::WriteType(QualType T) {
1907 TypeIdx &Idx = TypeIdxs[T];
1908 if (Idx.getIndex() == 0) // we haven't seen this type before.
1909 Idx = TypeIdx(NextTypeID++);
1911 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1913 // Record the offset for this type.
1914 unsigned Index = Idx.getIndex() - FirstTypeID;
1915 if (TypeOffsets.size() == Index)
1916 TypeOffsets.push_back(Stream.GetCurrentBitNo());
1917 else if (TypeOffsets.size() < Index) {
1918 TypeOffsets.resize(Index + 1);
1919 TypeOffsets[Index] = Stream.GetCurrentBitNo();
1924 // Emit the type's representation.
1925 ASTTypeWriter W(*this, Record);
1927 if (T.hasLocalNonFastQualifiers()) {
1928 Qualifiers Qs = T.getLocalQualifiers();
1929 AddTypeRef(T.getLocalUnqualifiedType(), Record);
1930 Record.push_back(Qs.getAsOpaqueValue());
1931 W.Code = TYPE_EXT_QUAL;
1933 switch (T->getTypeClass()) {
1934 // For all of the concrete, non-dependent types, call the
1935 // appropriate visitor function.
1936 #define TYPE(Class, Base) \
1937 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1938 #define ABSTRACT_TYPE(Class, Base)
1939 #include "clang/AST/TypeNodes.def"
1943 // Emit the serialized record.
1944 Stream.EmitRecord(W.Code, Record);
1946 // Flush any expressions that were written as part of this type.
1950 //===----------------------------------------------------------------------===//
1951 // Declaration Serialization
1952 //===----------------------------------------------------------------------===//
1954 /// \brief Write the block containing all of the declaration IDs
1955 /// lexically declared within the given DeclContext.
1957 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1958 /// bistream, or 0 if no block was written.
1959 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1961 if (DC->decls_empty())
1964 uint64_t Offset = Stream.GetCurrentBitNo();
1966 Record.push_back(DECL_CONTEXT_LEXICAL);
1967 llvm::SmallVector<KindDeclIDPair, 64> Decls;
1968 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1970 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1972 ++NumLexicalDeclContexts;
1973 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
1977 void ASTWriter::WriteTypeDeclOffsets() {
1978 using namespace llvm;
1981 // Write the type offsets array
1982 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1983 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1984 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1985 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1986 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1988 Record.push_back(TYPE_OFFSET);
1989 Record.push_back(TypeOffsets.size());
1990 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
1992 // Write the declaration offsets array
1993 Abbrev = new BitCodeAbbrev();
1994 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1995 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1996 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1997 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1999 Record.push_back(DECL_OFFSET);
2000 Record.push_back(DeclOffsets.size());
2001 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2004 //===----------------------------------------------------------------------===//
2005 // Global Method Pool and Selector Serialization
2006 //===----------------------------------------------------------------------===//
2009 // Trait used for the on-disk hash table used in the method pool.
2010 class ASTMethodPoolTrait {
2014 typedef Selector key_type;
2015 typedef key_type key_type_ref;
2019 ObjCMethodList Instance, Factory;
2021 typedef const data_type& data_type_ref;
2023 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2025 static unsigned ComputeHash(Selector Sel) {
2026 return serialization::ComputeHash(Sel);
2029 std::pair<unsigned,unsigned>
2030 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
2031 data_type_ref Methods) {
2032 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2033 clang::io::Emit16(Out, KeyLen);
2034 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2035 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2036 Method = Method->Next)
2039 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2040 Method = Method->Next)
2043 clang::io::Emit16(Out, DataLen);
2044 return std::make_pair(KeyLen, DataLen);
2047 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
2048 uint64_t Start = Out.tell();
2049 assert((Start >> 32) == 0 && "Selector key offset too large");
2050 Writer.SetSelectorOffset(Sel, Start);
2051 unsigned N = Sel.getNumArgs();
2052 clang::io::Emit16(Out, N);
2055 for (unsigned I = 0; I != N; ++I)
2056 clang::io::Emit32(Out,
2057 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2060 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2061 data_type_ref Methods, unsigned DataLen) {
2062 uint64_t Start = Out.tell(); (void)Start;
2063 clang::io::Emit32(Out, Methods.ID);
2064 unsigned NumInstanceMethods = 0;
2065 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2066 Method = Method->Next)
2068 ++NumInstanceMethods;
2070 unsigned NumFactoryMethods = 0;
2071 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2072 Method = Method->Next)
2074 ++NumFactoryMethods;
2076 clang::io::Emit16(Out, NumInstanceMethods);
2077 clang::io::Emit16(Out, NumFactoryMethods);
2078 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2079 Method = Method->Next)
2081 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2082 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2083 Method = Method->Next)
2085 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2087 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2090 } // end anonymous namespace
2092 /// \brief Write ObjC data: selectors and the method pool.
2094 /// The method pool contains both instance and factory methods, stored
2095 /// in an on-disk hash table indexed by the selector. The hash table also
2096 /// contains an empty entry for every other selector known to Sema.
2097 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2098 using namespace llvm;
2100 // Do we have to do anything at all?
2101 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2103 unsigned NumTableEntries = 0;
2104 // Create and write out the blob that contains selectors and the method pool.
2106 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2107 ASTMethodPoolTrait Trait(*this);
2109 // Create the on-disk hash table representation. We walk through every
2110 // selector we've seen and look it up in the method pool.
2111 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2112 for (llvm::DenseMap<Selector, SelectorID>::iterator
2113 I = SelectorIDs.begin(), E = SelectorIDs.end();
2115 Selector S = I->first;
2116 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2117 ASTMethodPoolTrait::data_type Data = {
2122 if (F != SemaRef.MethodPool.end()) {
2123 Data.Instance = F->second.first;
2124 Data.Factory = F->second.second;
2126 // Only write this selector if it's not in an existing AST or something
2128 if (Chain && I->second < FirstSelectorID) {
2129 // Selector already exists. Did it change?
2130 bool changed = false;
2131 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2133 if (M->Method->getPCHLevel() == 0)
2136 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2138 if (M->Method->getPCHLevel() == 0)
2143 } else if (Data.Instance.Method || Data.Factory.Method) {
2144 // A new method pool entry.
2147 Generator.insert(S, Data, Trait);
2150 // Create the on-disk hash table in a buffer.
2151 llvm::SmallString<4096> MethodPool;
2152 uint32_t BucketOffset;
2154 ASTMethodPoolTrait Trait(*this);
2155 llvm::raw_svector_ostream Out(MethodPool);
2156 // Make sure that no bucket is at offset 0
2157 clang::io::Emit32(Out, 0);
2158 BucketOffset = Generator.Emit(Out, Trait);
2161 // Create a blob abbreviation
2162 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2163 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2166 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2167 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2169 // Write the method pool
2171 Record.push_back(METHOD_POOL);
2172 Record.push_back(BucketOffset);
2173 Record.push_back(NumTableEntries);
2174 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2176 // Create a blob abbreviation for the selector table offsets.
2177 Abbrev = new BitCodeAbbrev();
2178 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2180 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2181 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2183 // Write the selector offsets table.
2185 Record.push_back(SELECTOR_OFFSETS);
2186 Record.push_back(SelectorOffsets.size());
2187 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2188 data(SelectorOffsets));
2192 /// \brief Write the selectors referenced in @selector expression into AST file.
2193 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2194 using namespace llvm;
2195 if (SemaRef.ReferencedSelectors.empty())
2200 // Note: this writes out all references even for a dependent AST. But it is
2201 // very tricky to fix, and given that @selector shouldn't really appear in
2202 // headers, probably not worth it. It's not a correctness issue.
2203 for (DenseMap<Selector, SourceLocation>::iterator S =
2204 SemaRef.ReferencedSelectors.begin(),
2205 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2206 Selector Sel = (*S).first;
2207 SourceLocation Loc = (*S).second;
2208 AddSelectorRef(Sel, Record);
2209 AddSourceLocation(Loc, Record);
2211 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2214 //===----------------------------------------------------------------------===//
2215 // Identifier Table Serialization
2216 //===----------------------------------------------------------------------===//
2219 class ASTIdentifierTableTrait {
2223 /// \brief Determines whether this is an "interesting" identifier
2224 /// that needs a full IdentifierInfo structure written into the hash
2226 static bool isInterestingIdentifier(const IdentifierInfo *II) {
2227 return II->isPoisoned() ||
2228 II->isExtensionToken() ||
2229 II->hasMacroDefinition() ||
2230 II->getObjCOrBuiltinID() ||
2231 II->getFETokenInfo<void>();
2235 typedef const IdentifierInfo* key_type;
2236 typedef key_type key_type_ref;
2238 typedef IdentID data_type;
2239 typedef data_type data_type_ref;
2241 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
2242 : Writer(Writer), PP(PP) { }
2244 static unsigned ComputeHash(const IdentifierInfo* II) {
2245 return llvm::HashString(II->getName());
2248 std::pair<unsigned,unsigned>
2249 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
2251 unsigned KeyLen = II->getLength() + 1;
2252 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2253 if (isInterestingIdentifier(II)) {
2254 DataLen += 2; // 2 bytes for builtin ID, flags
2255 if (II->hasMacroDefinition() &&
2256 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
2258 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
2259 DEnd = IdentifierResolver::end();
2261 DataLen += sizeof(DeclID);
2263 clang::io::Emit16(Out, DataLen);
2264 // We emit the key length after the data length so that every
2265 // string is preceded by a 16-bit length. This matches the PTH
2266 // format for storing identifiers.
2267 clang::io::Emit16(Out, KeyLen);
2268 return std::make_pair(KeyLen, DataLen);
2271 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
2273 // Record the location of the key data. This is used when generating
2274 // the mapping from persistent IDs to strings.
2275 Writer.SetIdentifierOffset(II, Out.tell());
2276 Out.write(II->getNameStart(), KeyLen);
2279 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
2280 IdentID ID, unsigned) {
2281 if (!isInterestingIdentifier(II)) {
2282 clang::io::Emit32(Out, ID << 1);
2286 clang::io::Emit32(Out, (ID << 1) | 0x01);
2288 bool hasMacroDefinition =
2289 II->hasMacroDefinition() &&
2290 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
2291 Bits = (uint32_t)II->getObjCOrBuiltinID();
2292 Bits = (Bits << 1) | unsigned(hasMacroDefinition);
2293 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2294 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2295 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2296 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2297 clang::io::Emit16(Out, Bits);
2299 if (hasMacroDefinition)
2300 clang::io::Emit32(Out, Writer.getMacroOffset(II));
2302 // Emit the declaration IDs in reverse order, because the
2303 // IdentifierResolver provides the declarations as they would be
2304 // visible (e.g., the function "stat" would come before the struct
2305 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
2306 // adds declarations to the end of the list (so we need to see the
2307 // struct "status" before the function "status").
2308 // Only emit declarations that aren't from a chained PCH, though.
2309 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
2310 IdentifierResolver::end());
2311 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2312 DEnd = Decls.rend();
2314 clang::io::Emit32(Out, Writer.getDeclID(*D));
2317 } // end anonymous namespace
2319 /// \brief Write the identifier table into the AST file.
2321 /// The identifier table consists of a blob containing string data
2322 /// (the actual identifiers themselves) and a separate "offsets" index
2323 /// that maps identifier IDs to locations within the blob.
2324 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
2325 using namespace llvm;
2327 // Create and write out the blob that contains the identifier
2330 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2331 ASTIdentifierTableTrait Trait(*this, PP);
2333 // Look for any identifiers that were named while processing the
2334 // headers, but are otherwise not needed. We add these to the hash
2335 // table to enable checking of the predefines buffer in the case
2336 // where the user adds new macro definitions when building the AST
2338 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2339 IDEnd = PP.getIdentifierTable().end();
2341 getIdentifierRef(ID->second);
2343 // Create the on-disk hash table representation. We only store offsets
2344 // for identifiers that appear here for the first time.
2345 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2346 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2347 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2348 ID != IDEnd; ++ID) {
2349 assert(ID->first && "NULL identifier in identifier table");
2350 if (!Chain || !ID->first->isFromAST())
2351 Generator.insert(ID->first, ID->second, Trait);
2354 // Create the on-disk hash table in a buffer.
2355 llvm::SmallString<4096> IdentifierTable;
2356 uint32_t BucketOffset;
2358 ASTIdentifierTableTrait Trait(*this, PP);
2359 llvm::raw_svector_ostream Out(IdentifierTable);
2360 // Make sure that no bucket is at offset 0
2361 clang::io::Emit32(Out, 0);
2362 BucketOffset = Generator.Emit(Out, Trait);
2365 // Create a blob abbreviation
2366 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2367 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2370 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2372 // Write the identifier table
2374 Record.push_back(IDENTIFIER_TABLE);
2375 Record.push_back(BucketOffset);
2376 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2379 // Write the offsets table for identifier IDs.
2380 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2381 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2384 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2387 Record.push_back(IDENTIFIER_OFFSET);
2388 Record.push_back(IdentifierOffsets.size());
2389 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2390 data(IdentifierOffsets));
2393 //===----------------------------------------------------------------------===//
2394 // DeclContext's Name Lookup Table Serialization
2395 //===----------------------------------------------------------------------===//
2398 // Trait used for the on-disk hash table used in the method pool.
2399 class ASTDeclContextNameLookupTrait {
2403 typedef DeclarationName key_type;
2404 typedef key_type key_type_ref;
2406 typedef DeclContext::lookup_result data_type;
2407 typedef const data_type& data_type_ref;
2409 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2411 unsigned ComputeHash(DeclarationName Name) {
2412 llvm::FoldingSetNodeID ID;
2413 ID.AddInteger(Name.getNameKind());
2415 switch (Name.getNameKind()) {
2416 case DeclarationName::Identifier:
2417 ID.AddString(Name.getAsIdentifierInfo()->getName());
2419 case DeclarationName::ObjCZeroArgSelector:
2420 case DeclarationName::ObjCOneArgSelector:
2421 case DeclarationName::ObjCMultiArgSelector:
2422 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2424 case DeclarationName::CXXConstructorName:
2425 case DeclarationName::CXXDestructorName:
2426 case DeclarationName::CXXConversionFunctionName:
2427 ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2429 case DeclarationName::CXXOperatorName:
2430 ID.AddInteger(Name.getCXXOverloadedOperator());
2432 case DeclarationName::CXXLiteralOperatorName:
2433 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2434 case DeclarationName::CXXUsingDirective:
2438 return ID.ComputeHash();
2441 std::pair<unsigned,unsigned>
2442 EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2443 data_type_ref Lookup) {
2444 unsigned KeyLen = 1;
2445 switch (Name.getNameKind()) {
2446 case DeclarationName::Identifier:
2447 case DeclarationName::ObjCZeroArgSelector:
2448 case DeclarationName::ObjCOneArgSelector:
2449 case DeclarationName::ObjCMultiArgSelector:
2450 case DeclarationName::CXXConstructorName:
2451 case DeclarationName::CXXDestructorName:
2452 case DeclarationName::CXXConversionFunctionName:
2453 case DeclarationName::CXXLiteralOperatorName:
2456 case DeclarationName::CXXOperatorName:
2459 case DeclarationName::CXXUsingDirective:
2462 clang::io::Emit16(Out, KeyLen);
2464 // 2 bytes for num of decls and 4 for each DeclID.
2465 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2466 clang::io::Emit16(Out, DataLen);
2468 return std::make_pair(KeyLen, DataLen);
2471 void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2472 using namespace clang::io;
2474 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2475 Emit8(Out, Name.getNameKind());
2476 switch (Name.getNameKind()) {
2477 case DeclarationName::Identifier:
2478 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2480 case DeclarationName::ObjCZeroArgSelector:
2481 case DeclarationName::ObjCOneArgSelector:
2482 case DeclarationName::ObjCMultiArgSelector:
2483 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2485 case DeclarationName::CXXConstructorName:
2486 case DeclarationName::CXXDestructorName:
2487 case DeclarationName::CXXConversionFunctionName:
2488 Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2490 case DeclarationName::CXXOperatorName:
2491 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2492 Emit8(Out, Name.getCXXOverloadedOperator());
2494 case DeclarationName::CXXLiteralOperatorName:
2495 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2497 case DeclarationName::CXXUsingDirective:
2502 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2503 data_type Lookup, unsigned DataLen) {
2504 uint64_t Start = Out.tell(); (void)Start;
2505 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2506 for (; Lookup.first != Lookup.second; ++Lookup.first)
2507 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2509 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2512 } // end anonymous namespace
2514 /// \brief Write the block containing all of the declaration IDs
2515 /// visible from the given DeclContext.
2517 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2518 /// bitstream, or 0 if no block was written.
2519 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2521 if (DC->getPrimaryContext() != DC)
2524 // Since there is no name lookup into functions or methods, don't bother to
2525 // build a visible-declarations table for these entities.
2526 if (DC->isFunctionOrMethod())
2529 // If not in C++, we perform name lookup for the translation unit via the
2530 // IdentifierInfo chains, don't bother to build a visible-declarations table.
2531 // FIXME: In C++ we need the visible declarations in order to "see" the
2532 // friend declarations, is there a way to do this without writing the table ?
2533 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2536 // Force the DeclContext to build a its name-lookup table.
2537 if (DC->hasExternalVisibleStorage())
2538 DC->MaterializeVisibleDeclsFromExternalStorage();
2540 DC->lookup(DeclarationName());
2542 // Serialize the contents of the mapping used for lookup. Note that,
2543 // although we have two very different code paths, the serialized
2544 // representation is the same for both cases: a declaration name,
2545 // followed by a size, followed by references to the visible
2546 // declarations that have that name.
2547 uint64_t Offset = Stream.GetCurrentBitNo();
2548 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2549 if (!Map || Map->empty())
2552 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2553 ASTDeclContextNameLookupTrait Trait(*this);
2555 // Create the on-disk hash table representation.
2556 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2558 DeclarationName Name = D->first;
2559 DeclContext::lookup_result Result = D->second.getLookupResult();
2560 Generator.insert(Name, Result, Trait);
2563 // Create the on-disk hash table in a buffer.
2564 llvm::SmallString<4096> LookupTable;
2565 uint32_t BucketOffset;
2567 llvm::raw_svector_ostream Out(LookupTable);
2568 // Make sure that no bucket is at offset 0
2569 clang::io::Emit32(Out, 0);
2570 BucketOffset = Generator.Emit(Out, Trait);
2573 // Write the lookup table
2575 Record.push_back(DECL_CONTEXT_VISIBLE);
2576 Record.push_back(BucketOffset);
2577 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2580 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2581 ++NumVisibleDeclContexts;
2585 /// \brief Write an UPDATE_VISIBLE block for the given context.
2587 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2588 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2589 /// (in C++) and for namespaces.
2590 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2591 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2592 if (!Map || Map->empty())
2595 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2596 ASTDeclContextNameLookupTrait Trait(*this);
2598 // Create the hash table.
2599 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2601 DeclarationName Name = D->first;
2602 DeclContext::lookup_result Result = D->second.getLookupResult();
2603 // For any name that appears in this table, the results are complete, i.e.
2604 // they overwrite results from previous PCHs. Merging is always a mess.
2605 Generator.insert(Name, Result, Trait);
2608 // Create the on-disk hash table in a buffer.
2609 llvm::SmallString<4096> LookupTable;
2610 uint32_t BucketOffset;
2612 llvm::raw_svector_ostream Out(LookupTable);
2613 // Make sure that no bucket is at offset 0
2614 clang::io::Emit32(Out, 0);
2615 BucketOffset = Generator.Emit(Out, Trait);
2618 // Write the lookup table
2620 Record.push_back(UPDATE_VISIBLE);
2621 Record.push_back(getDeclID(cast<Decl>(DC)));
2622 Record.push_back(BucketOffset);
2623 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2626 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
2627 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2629 Record.push_back(Opts.fp_contract);
2630 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2633 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
2634 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2635 if (!SemaRef.Context.getLangOptions().OpenCL)
2638 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2640 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
2641 #include "clang/Basic/OpenCLExtensions.def"
2642 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2645 //===----------------------------------------------------------------------===//
2646 // General Serialization Routines
2647 //===----------------------------------------------------------------------===//
2649 /// \brief Write a record containing the given attributes.
2650 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2651 Record.push_back(Attrs.size());
2652 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2653 const Attr * A = *i;
2654 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2655 AddSourceLocation(A->getLocation(), Record);
2657 #include "clang/Serialization/AttrPCHWrite.inc"
2662 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2663 Record.push_back(Str.size());
2664 Record.insert(Record.end(), Str.begin(), Str.end());
2667 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
2668 RecordDataImpl &Record) {
2669 Record.push_back(Version.getMajor());
2670 if (llvm::Optional<unsigned> Minor = Version.getMinor())
2671 Record.push_back(*Minor + 1);
2673 Record.push_back(0);
2674 if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
2675 Record.push_back(*Subminor + 1);
2677 Record.push_back(0);
2680 /// \brief Note that the identifier II occurs at the given offset
2681 /// within the identifier table.
2682 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2683 IdentID ID = IdentifierIDs[II];
2684 // Only store offsets new to this AST file. Other identifier names are looked
2685 // up earlier in the chain and thus don't need an offset.
2686 if (ID >= FirstIdentID)
2687 IdentifierOffsets[ID - FirstIdentID] = Offset;
2690 /// \brief Note that the selector Sel occurs at the given offset
2691 /// within the method pool/selector table.
2692 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2693 unsigned ID = SelectorIDs[Sel];
2694 assert(ID && "Unknown selector");
2695 // Don't record offsets for selectors that are also available in a different
2697 if (ID < FirstSelectorID)
2699 SelectorOffsets[ID - FirstSelectorID] = Offset;
2702 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2703 : Stream(Stream), Chain(0), SerializationListener(0),
2704 FirstDeclID(1), NextDeclID(FirstDeclID),
2705 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2706 FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2707 NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2708 CollectedStmts(&StmtsToEmit),
2709 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2710 NumVisibleDeclContexts(0),
2711 FirstCXXBaseSpecifiersID(1), NextCXXBaseSpecifiersID(1),
2712 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
2713 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
2714 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
2715 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
2716 DeclTypedefAbbrev(0),
2717 DeclVarAbbrev(0), DeclFieldAbbrev(0),
2718 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
2722 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2723 const std::string &OutputFile,
2724 const char *isysroot) {
2725 // Emit the file header.
2726 Stream.Emit((unsigned)'C', 8);
2727 Stream.Emit((unsigned)'P', 8);
2728 Stream.Emit((unsigned)'C', 8);
2729 Stream.Emit((unsigned)'H', 8);
2731 WriteBlockInfoBlock();
2734 WriteASTChain(SemaRef, StatCalls, isysroot);
2736 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile);
2739 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2740 const char *isysroot,
2741 const std::string &OutputFile) {
2742 using namespace llvm;
2744 ASTContext &Context = SemaRef.Context;
2745 Preprocessor &PP = SemaRef.PP;
2747 // The translation unit is the first declaration we'll emit.
2748 DeclIDs[Context.getTranslationUnitDecl()] = 1;
2750 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2752 // Make sure that we emit IdentifierInfos (and any attached
2753 // declarations) for builtins.
2755 IdentifierTable &Table = PP.getIdentifierTable();
2756 llvm::SmallVector<const char *, 32> BuiltinNames;
2757 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2758 Context.getLangOptions().NoBuiltin);
2759 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2760 getIdentifierRef(&Table.get(BuiltinNames[I]));
2763 // Build a record containing all of the tentative definitions in this file, in
2764 // TentativeDefinitions order. Generally, this record will be empty for
2766 RecordData TentativeDefinitions;
2767 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2768 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2771 // Build a record containing all of the file scoped decls in this file.
2772 RecordData UnusedFileScopedDecls;
2773 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2774 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2776 RecordData DelegatingCtorDecls;
2777 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i)
2778 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
2780 RecordData WeakUndeclaredIdentifiers;
2781 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2782 WeakUndeclaredIdentifiers.push_back(
2783 SemaRef.WeakUndeclaredIdentifiers.size());
2784 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2785 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2786 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2787 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2788 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2789 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2790 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2794 // Build a record containing all of the locally-scoped external
2795 // declarations in this header file. Generally, this record will be
2797 RecordData LocallyScopedExternalDecls;
2798 // FIXME: This is filling in the AST file in densemap order which is
2800 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2801 TD = SemaRef.LocallyScopedExternalDecls.begin(),
2802 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2804 AddDeclRef(TD->second, LocallyScopedExternalDecls);
2806 // Build a record containing all of the ext_vector declarations.
2807 RecordData ExtVectorDecls;
2808 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2809 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2811 // Build a record containing all of the VTable uses information.
2812 RecordData VTableUses;
2813 if (!SemaRef.VTableUses.empty()) {
2814 VTableUses.push_back(SemaRef.VTableUses.size());
2815 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2816 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2817 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2818 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2822 // Build a record containing all of dynamic classes declarations.
2823 RecordData DynamicClasses;
2824 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2825 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2827 // Build a record containing all of pending implicit instantiations.
2828 RecordData PendingInstantiations;
2829 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2830 I = SemaRef.PendingInstantiations.begin(),
2831 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2832 AddDeclRef(I->first, PendingInstantiations);
2833 AddSourceLocation(I->second, PendingInstantiations);
2835 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2836 "There are local ones at end of translation unit!");
2838 // Build a record containing some declaration references.
2839 RecordData SemaDeclRefs;
2840 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2841 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2842 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2845 RecordData CUDASpecialDeclRefs;
2846 if (Context.getcudaConfigureCallDecl()) {
2847 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
2850 // Build a record containing all of the known namespaces.
2851 RecordData KnownNamespaces;
2852 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
2853 I = SemaRef.KnownNamespaces.begin(),
2854 IEnd = SemaRef.KnownNamespaces.end();
2857 AddDeclRef(I->first, KnownNamespaces);
2860 // Write the remaining AST contents.
2862 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2863 WriteMetadata(Context, isysroot, OutputFile);
2864 WriteLanguageOptions(Context.getLangOptions());
2865 if (StatCalls && !isysroot)
2866 WriteStatCache(*StatCalls);
2867 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2868 // Write the record of special types.
2871 AddTypeRef(Context.getBuiltinVaListType(), Record);
2872 AddTypeRef(Context.getObjCIdType(), Record);
2873 AddTypeRef(Context.getObjCSelType(), Record);
2874 AddTypeRef(Context.getObjCProtoType(), Record);
2875 AddTypeRef(Context.getObjCClassType(), Record);
2876 AddTypeRef(Context.getRawCFConstantStringType(), Record);
2877 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2878 AddTypeRef(Context.getFILEType(), Record);
2879 AddTypeRef(Context.getjmp_bufType(), Record);
2880 AddTypeRef(Context.getsigjmp_bufType(), Record);
2881 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2882 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2883 AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2884 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2885 AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2886 AddTypeRef(Context.getRawNSConstantStringType(), Record);
2887 Record.push_back(Context.isInt128Installed());
2888 AddTypeRef(Context.AutoDeductTy, Record);
2889 AddTypeRef(Context.AutoRRefDeductTy, Record);
2890 Stream.EmitRecord(SPECIAL_TYPES, Record);
2892 // Keep writing types and declarations until all types and
2893 // declarations have been written.
2894 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2895 WriteDeclsBlockAbbrevs();
2896 while (!DeclTypesToEmit.empty()) {
2897 DeclOrType DOT = DeclTypesToEmit.front();
2898 DeclTypesToEmit.pop();
2900 WriteType(DOT.getType());
2902 WriteDecl(Context, DOT.getDecl());
2906 WritePreprocessor(PP);
2907 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
2908 WriteSelectors(SemaRef);
2909 WriteReferencedSelectorsPool(SemaRef);
2910 WriteIdentifierTable(PP);
2911 WriteFPPragmaOptions(SemaRef.getFPOptions());
2912 WriteOpenCLExtensions(SemaRef);
2914 WriteTypeDeclOffsets();
2915 WritePragmaDiagnosticMappings(Context.getDiagnostics());
2917 WriteCXXBaseSpecifiersOffsets();
2919 // Write the record containing external, unnamed definitions.
2920 if (!ExternalDefinitions.empty())
2921 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2923 // Write the record containing tentative definitions.
2924 if (!TentativeDefinitions.empty())
2925 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2927 // Write the record containing unused file scoped decls.
2928 if (!UnusedFileScopedDecls.empty())
2929 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2931 // Write the record containing weak undeclared identifiers.
2932 if (!WeakUndeclaredIdentifiers.empty())
2933 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2934 WeakUndeclaredIdentifiers);
2936 // Write the record containing locally-scoped external definitions.
2937 if (!LocallyScopedExternalDecls.empty())
2938 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2939 LocallyScopedExternalDecls);
2941 // Write the record containing ext_vector type names.
2942 if (!ExtVectorDecls.empty())
2943 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2945 // Write the record containing VTable uses information.
2946 if (!VTableUses.empty())
2947 Stream.EmitRecord(VTABLE_USES, VTableUses);
2949 // Write the record containing dynamic classes declarations.
2950 if (!DynamicClasses.empty())
2951 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2953 // Write the record containing pending implicit instantiations.
2954 if (!PendingInstantiations.empty())
2955 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2957 // Write the record containing declaration references of Sema.
2958 if (!SemaDeclRefs.empty())
2959 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2961 // Write the record containing CUDA-specific declaration references.
2962 if (!CUDASpecialDeclRefs.empty())
2963 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
2965 // Write the delegating constructors.
2966 if (!DelegatingCtorDecls.empty())
2967 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
2969 // Write the known namespaces.
2970 if (!KnownNamespaces.empty())
2971 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
2973 // Some simple statistics
2975 Record.push_back(NumStatements);
2976 Record.push_back(NumMacros);
2977 Record.push_back(NumLexicalDeclContexts);
2978 Record.push_back(NumVisibleDeclContexts);
2979 Stream.EmitRecord(STATISTICS, Record);
2983 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2984 const char *isysroot) {
2985 using namespace llvm;
2987 ASTContext &Context = SemaRef.Context;
2988 Preprocessor &PP = SemaRef.PP;
2991 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2992 WriteMetadata(Context, isysroot, "");
2993 if (StatCalls && !isysroot)
2994 WriteStatCache(*StatCalls);
2995 // FIXME: Source manager block should only write new stuff, which could be
2996 // done by tracking the largest ID in the chain
2997 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2999 // The special types are in the chained PCH.
3001 // We don't start with the translation unit, but with its decls that
3002 // don't come from the chained PCH.
3003 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3004 llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3005 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3006 E = TU->noload_decls_end();
3008 if ((*I)->getPCHLevel() == 0)
3009 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3010 else if ((*I)->isChangedSinceDeserialization())
3011 (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
3013 // We also need to write a lexical updates block for the TU.
3014 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3015 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3016 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3017 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3019 Record.push_back(TU_UPDATE_LEXICAL);
3020 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3021 data(NewGlobalDecls));
3022 // And a visible updates block for the DeclContexts.
3023 Abv = new llvm::BitCodeAbbrev();
3024 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3025 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3026 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3027 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3028 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3029 WriteDeclContextVisibleUpdate(TU);
3031 // Build a record containing all of the new tentative definitions in this
3032 // file, in TentativeDefinitions order.
3033 RecordData TentativeDefinitions;
3034 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
3035 if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
3036 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
3039 // Build a record containing all of the file scoped decls in this file.
3040 RecordData UnusedFileScopedDecls;
3041 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
3042 if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
3043 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
3046 // Build a record containing all of the delegating constructor decls in this
3048 RecordData DelegatingCtorDecls;
3049 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i) {
3050 if (SemaRef.DelegatingCtorDecls[i]->getPCHLevel() == 0)
3051 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
3054 // We write the entire table, overwriting the tables from the chain.
3055 RecordData WeakUndeclaredIdentifiers;
3056 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3057 WeakUndeclaredIdentifiers.push_back(
3058 SemaRef.WeakUndeclaredIdentifiers.size());
3059 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
3060 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3061 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3062 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3063 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3064 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3065 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3069 // Build a record containing all of the locally-scoped external
3070 // declarations in this header file. Generally, this record will be
3072 RecordData LocallyScopedExternalDecls;
3073 // FIXME: This is filling in the AST file in densemap order which is
3075 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3076 TD = SemaRef.LocallyScopedExternalDecls.begin(),
3077 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3078 TD != TDEnd; ++TD) {
3079 if (TD->second->getPCHLevel() == 0)
3080 AddDeclRef(TD->second, LocallyScopedExternalDecls);
3083 // Build a record containing all of the ext_vector declarations.
3084 RecordData ExtVectorDecls;
3085 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
3086 if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
3087 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
3090 // Build a record containing all of the VTable uses information.
3091 // We write everything here, because it's too hard to determine whether
3092 // a use is new to this part.
3093 RecordData VTableUses;
3094 if (!SemaRef.VTableUses.empty()) {
3095 VTableUses.push_back(SemaRef.VTableUses.size());
3096 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3097 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3098 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3099 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3103 // Build a record containing all of dynamic classes declarations.
3104 RecordData DynamicClasses;
3105 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
3106 if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
3107 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
3109 // Build a record containing all of pending implicit instantiations.
3110 RecordData PendingInstantiations;
3111 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3112 I = SemaRef.PendingInstantiations.begin(),
3113 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3114 AddDeclRef(I->first, PendingInstantiations);
3115 AddSourceLocation(I->second, PendingInstantiations);
3117 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3118 "There are local ones at end of translation unit!");
3120 // Build a record containing some declaration references.
3121 // It's not worth the effort to avoid duplication here.
3122 RecordData SemaDeclRefs;
3123 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3124 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3125 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3128 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3129 WriteDeclsBlockAbbrevs();
3130 for (DeclsToRewriteTy::iterator
3131 I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
3132 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3133 while (!DeclTypesToEmit.empty()) {
3134 DeclOrType DOT = DeclTypesToEmit.front();
3135 DeclTypesToEmit.pop();
3137 WriteType(DOT.getType());
3139 WriteDecl(Context, DOT.getDecl());
3143 WritePreprocessor(PP);
3144 WriteSelectors(SemaRef);
3145 WriteReferencedSelectorsPool(SemaRef);
3146 WriteIdentifierTable(PP);
3147 WriteFPPragmaOptions(SemaRef.getFPOptions());
3148 WriteOpenCLExtensions(SemaRef);
3150 WriteTypeDeclOffsets();
3151 // FIXME: For chained PCH only write the new mappings (we currently
3152 // write all of them again).
3153 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3155 WriteCXXBaseSpecifiersOffsets();
3157 /// Build a record containing first declarations from a chained PCH and the
3158 /// most recent declarations in this AST that they point to.
3159 RecordData FirstLatestDeclIDs;
3160 for (FirstLatestDeclMap::iterator
3161 I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
3162 assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
3163 "Expected first & second to be in different PCHs");
3164 AddDeclRef(I->first, FirstLatestDeclIDs);
3165 AddDeclRef(I->second, FirstLatestDeclIDs);
3167 if (!FirstLatestDeclIDs.empty())
3168 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3170 // Write the record containing external, unnamed definitions.
3171 if (!ExternalDefinitions.empty())
3172 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3174 // Write the record containing tentative definitions.
3175 if (!TentativeDefinitions.empty())
3176 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3178 // Write the record containing unused file scoped decls.
3179 if (!UnusedFileScopedDecls.empty())
3180 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3182 // Write the record containing weak undeclared identifiers.
3183 if (!WeakUndeclaredIdentifiers.empty())
3184 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3185 WeakUndeclaredIdentifiers);
3187 // Write the record containing locally-scoped external definitions.
3188 if (!LocallyScopedExternalDecls.empty())
3189 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3190 LocallyScopedExternalDecls);
3192 // Write the record containing ext_vector type names.
3193 if (!ExtVectorDecls.empty())
3194 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3196 // Write the record containing VTable uses information.
3197 if (!VTableUses.empty())
3198 Stream.EmitRecord(VTABLE_USES, VTableUses);
3200 // Write the record containing dynamic classes declarations.
3201 if (!DynamicClasses.empty())
3202 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3204 // Write the record containing pending implicit instantiations.
3205 if (!PendingInstantiations.empty())
3206 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3208 // Write the record containing declaration references of Sema.
3209 if (!SemaDeclRefs.empty())
3210 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3212 // Write the delegating constructors.
3213 if (!DelegatingCtorDecls.empty())
3214 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3216 // Write the updates to DeclContexts.
3217 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3218 I = UpdatedDeclContexts.begin(),
3219 E = UpdatedDeclContexts.end();
3221 WriteDeclContextVisibleUpdate(*I);
3223 WriteDeclUpdatesBlocks();
3226 Record.push_back(NumStatements);
3227 Record.push_back(NumMacros);
3228 Record.push_back(NumLexicalDeclContexts);
3229 Record.push_back(NumVisibleDeclContexts);
3230 WriteDeclReplacementsBlock();
3231 Stream.EmitRecord(STATISTICS, Record);
3235 void ASTWriter::WriteDeclUpdatesBlocks() {
3236 if (DeclUpdates.empty())
3239 RecordData OffsetsRecord;
3240 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3241 for (DeclUpdateMap::iterator
3242 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3243 const Decl *D = I->first;
3244 UpdateRecord &URec = I->second;
3246 if (DeclsToRewrite.count(D))
3247 continue; // The decl will be written completely,no need to store updates.
3249 uint64_t Offset = Stream.GetCurrentBitNo();
3250 Stream.EmitRecord(DECL_UPDATES, URec);
3252 OffsetsRecord.push_back(GetDeclRef(D));
3253 OffsetsRecord.push_back(Offset);
3256 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3259 void ASTWriter::WriteDeclReplacementsBlock() {
3260 if (ReplacedDecls.empty())
3264 for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
3265 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3266 Record.push_back(I->first);
3267 Record.push_back(I->second);
3269 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3272 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3273 Record.push_back(Loc.getRawEncoding());
3276 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3277 AddSourceLocation(Range.getBegin(), Record);
3278 AddSourceLocation(Range.getEnd(), Record);
3281 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3282 Record.push_back(Value.getBitWidth());
3283 const uint64_t *Words = Value.getRawData();
3284 Record.append(Words, Words + Value.getNumWords());
3287 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3288 Record.push_back(Value.isUnsigned());
3289 AddAPInt(Value, Record);
3292 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3293 AddAPInt(Value.bitcastToAPInt(), Record);
3296 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3297 Record.push_back(getIdentifierRef(II));
3300 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3304 IdentID &ID = IdentifierIDs[II];
3310 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
3314 MacroID &ID = MacroDefinitions[MD];
3320 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3321 Record.push_back(getSelectorRef(SelRef));
3324 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3325 if (Sel.getAsOpaquePtr() == 0) {
3329 SelectorID &SID = SelectorIDs[Sel];
3330 if (SID == 0 && Chain) {
3331 // This might trigger a ReadSelector callback, which will set the ID for
3333 Chain->LoadSelector(Sel);
3336 SID = NextSelectorID++;
3341 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3342 AddDeclRef(Temp->getDestructor(), Record);
3345 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3346 CXXBaseSpecifier const *BasesEnd,
3347 RecordDataImpl &Record) {
3348 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3349 CXXBaseSpecifiersToWrite.push_back(
3350 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3352 Record.push_back(NextCXXBaseSpecifiersID++);
3355 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3356 const TemplateArgumentLocInfo &Arg,
3357 RecordDataImpl &Record) {
3359 case TemplateArgument::Expression:
3360 AddStmt(Arg.getAsExpr());
3362 case TemplateArgument::Type:
3363 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3365 case TemplateArgument::Template:
3366 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3367 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3369 case TemplateArgument::TemplateExpansion:
3370 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3371 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3372 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3374 case TemplateArgument::Null:
3375 case TemplateArgument::Integral:
3376 case TemplateArgument::Declaration:
3377 case TemplateArgument::Pack:
3382 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3383 RecordDataImpl &Record) {
3384 AddTemplateArgument(Arg.getArgument(), Record);
3386 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3387 bool InfoHasSameExpr
3388 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3389 Record.push_back(InfoHasSameExpr);
3390 if (InfoHasSameExpr)
3391 return; // Avoid storing the same expr twice.
3393 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3397 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3398 RecordDataImpl &Record) {
3400 AddTypeRef(QualType(), Record);
3404 AddTypeLoc(TInfo->getTypeLoc(), Record);
3407 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3408 AddTypeRef(TL.getType(), Record);
3410 TypeLocWriter TLW(*this, Record);
3411 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3415 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3416 Record.push_back(GetOrCreateTypeID(T));
3419 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
3420 return MakeTypeID(T,
3421 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3424 TypeID ASTWriter::getTypeID(QualType T) const {
3425 return MakeTypeID(T,
3426 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3429 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3432 assert(!T.getLocalFastQualifiers());
3434 TypeIdx &Idx = TypeIdxs[T];
3435 if (Idx.getIndex() == 0) {
3436 // We haven't seen this type before. Assign it a new ID and put it
3437 // into the queue of types to emit.
3438 Idx = TypeIdx(NextTypeID++);
3439 DeclTypesToEmit.push(T);
3444 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3447 assert(!T.getLocalFastQualifiers());
3449 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3450 assert(I != TypeIdxs.end() && "Type not emitted!");
3454 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3455 Record.push_back(GetDeclRef(D));
3458 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3462 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3463 DeclID &ID = DeclIDs[D];
3465 // We haven't seen this declaration before. Give it a new ID and
3466 // enqueue it in the list of declarations to emit.
3468 DeclTypesToEmit.push(const_cast<Decl *>(D));
3469 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3470 // We don't add it to the replacement collection here, because we don't
3471 // have the offset yet.
3472 DeclTypesToEmit.push(const_cast<Decl *>(D));
3473 // Reset the flag, so that we don't add this decl multiple times.
3474 const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3480 DeclID ASTWriter::getDeclID(const Decl *D) {
3484 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3488 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3489 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
3490 Record.push_back(Name.getNameKind());
3491 switch (Name.getNameKind()) {
3492 case DeclarationName::Identifier:
3493 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3496 case DeclarationName::ObjCZeroArgSelector:
3497 case DeclarationName::ObjCOneArgSelector:
3498 case DeclarationName::ObjCMultiArgSelector:
3499 AddSelectorRef(Name.getObjCSelector(), Record);
3502 case DeclarationName::CXXConstructorName:
3503 case DeclarationName::CXXDestructorName:
3504 case DeclarationName::CXXConversionFunctionName:
3505 AddTypeRef(Name.getCXXNameType(), Record);
3508 case DeclarationName::CXXOperatorName:
3509 Record.push_back(Name.getCXXOverloadedOperator());
3512 case DeclarationName::CXXLiteralOperatorName:
3513 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3516 case DeclarationName::CXXUsingDirective:
3517 // No extra data to emit
3522 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3523 DeclarationName Name, RecordDataImpl &Record) {
3524 switch (Name.getNameKind()) {
3525 case DeclarationName::CXXConstructorName:
3526 case DeclarationName::CXXDestructorName:
3527 case DeclarationName::CXXConversionFunctionName:
3528 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3531 case DeclarationName::CXXOperatorName:
3533 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3536 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3540 case DeclarationName::CXXLiteralOperatorName:
3542 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3546 case DeclarationName::Identifier:
3547 case DeclarationName::ObjCZeroArgSelector:
3548 case DeclarationName::ObjCOneArgSelector:
3549 case DeclarationName::ObjCMultiArgSelector:
3550 case DeclarationName::CXXUsingDirective:
3555 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3556 RecordDataImpl &Record) {
3557 AddDeclarationName(NameInfo.getName(), Record);
3558 AddSourceLocation(NameInfo.getLoc(), Record);
3559 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3562 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3563 RecordDataImpl &Record) {
3564 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3565 Record.push_back(Info.NumTemplParamLists);
3566 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3567 AddTemplateParameterList(Info.TemplParamLists[i], Record);
3570 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3571 RecordDataImpl &Record) {
3572 // Nested name specifiers usually aren't too long. I think that 8 would
3573 // typically accommodate the vast majority.
3574 llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3576 // Push each of the NNS's onto a stack for serialization in reverse order.
3578 NestedNames.push_back(NNS);
3579 NNS = NNS->getPrefix();
3582 Record.push_back(NestedNames.size());
3583 while(!NestedNames.empty()) {
3584 NNS = NestedNames.pop_back_val();
3585 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3586 Record.push_back(Kind);
3588 case NestedNameSpecifier::Identifier:
3589 AddIdentifierRef(NNS->getAsIdentifier(), Record);
3592 case NestedNameSpecifier::Namespace:
3593 AddDeclRef(NNS->getAsNamespace(), Record);
3596 case NestedNameSpecifier::NamespaceAlias:
3597 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3600 case NestedNameSpecifier::TypeSpec:
3601 case NestedNameSpecifier::TypeSpecWithTemplate:
3602 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3603 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3606 case NestedNameSpecifier::Global:
3607 // Don't need to write an associated value.
3613 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3614 RecordDataImpl &Record) {
3615 // Nested name specifiers usually aren't too long. I think that 8 would
3616 // typically accommodate the vast majority.
3617 llvm::SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3619 // Push each of the nested-name-specifiers's onto a stack for
3620 // serialization in reverse order.
3622 NestedNames.push_back(NNS);
3623 NNS = NNS.getPrefix();
3626 Record.push_back(NestedNames.size());
3627 while(!NestedNames.empty()) {
3628 NNS = NestedNames.pop_back_val();
3629 NestedNameSpecifier::SpecifierKind Kind
3630 = NNS.getNestedNameSpecifier()->getKind();
3631 Record.push_back(Kind);
3633 case NestedNameSpecifier::Identifier:
3634 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3635 AddSourceRange(NNS.getLocalSourceRange(), Record);
3638 case NestedNameSpecifier::Namespace:
3639 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3640 AddSourceRange(NNS.getLocalSourceRange(), Record);
3643 case NestedNameSpecifier::NamespaceAlias:
3644 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3645 AddSourceRange(NNS.getLocalSourceRange(), Record);
3648 case NestedNameSpecifier::TypeSpec:
3649 case NestedNameSpecifier::TypeSpecWithTemplate:
3650 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3651 AddTypeLoc(NNS.getTypeLoc(), Record);
3652 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3655 case NestedNameSpecifier::Global:
3656 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3662 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3663 TemplateName::NameKind Kind = Name.getKind();
3664 Record.push_back(Kind);
3666 case TemplateName::Template:
3667 AddDeclRef(Name.getAsTemplateDecl(), Record);
3670 case TemplateName::OverloadedTemplate: {
3671 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3672 Record.push_back(OvT->size());
3673 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3675 AddDeclRef(*I, Record);
3679 case TemplateName::QualifiedTemplate: {
3680 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3681 AddNestedNameSpecifier(QualT->getQualifier(), Record);
3682 Record.push_back(QualT->hasTemplateKeyword());
3683 AddDeclRef(QualT->getTemplateDecl(), Record);
3687 case TemplateName::DependentTemplate: {
3688 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3689 AddNestedNameSpecifier(DepT->getQualifier(), Record);
3690 Record.push_back(DepT->isIdentifier());
3691 if (DepT->isIdentifier())
3692 AddIdentifierRef(DepT->getIdentifier(), Record);
3694 Record.push_back(DepT->getOperator());
3698 case TemplateName::SubstTemplateTemplateParm: {
3699 SubstTemplateTemplateParmStorage *subst
3700 = Name.getAsSubstTemplateTemplateParm();
3701 AddDeclRef(subst->getParameter(), Record);
3702 AddTemplateName(subst->getReplacement(), Record);
3706 case TemplateName::SubstTemplateTemplateParmPack: {
3707 SubstTemplateTemplateParmPackStorage *SubstPack
3708 = Name.getAsSubstTemplateTemplateParmPack();
3709 AddDeclRef(SubstPack->getParameterPack(), Record);
3710 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3716 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3717 RecordDataImpl &Record) {
3718 Record.push_back(Arg.getKind());
3719 switch (Arg.getKind()) {
3720 case TemplateArgument::Null:
3722 case TemplateArgument::Type:
3723 AddTypeRef(Arg.getAsType(), Record);
3725 case TemplateArgument::Declaration:
3726 AddDeclRef(Arg.getAsDecl(), Record);
3728 case TemplateArgument::Integral:
3729 AddAPSInt(*Arg.getAsIntegral(), Record);
3730 AddTypeRef(Arg.getIntegralType(), Record);
3732 case TemplateArgument::Template:
3733 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3735 case TemplateArgument::TemplateExpansion:
3736 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3737 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3738 Record.push_back(*NumExpansions + 1);
3740 Record.push_back(0);
3742 case TemplateArgument::Expression:
3743 AddStmt(Arg.getAsExpr());
3745 case TemplateArgument::Pack:
3746 Record.push_back(Arg.pack_size());
3747 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3749 AddTemplateArgument(*I, Record);
3755 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3756 RecordDataImpl &Record) {
3757 assert(TemplateParams && "No TemplateParams!");
3758 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3759 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3760 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3761 Record.push_back(TemplateParams->size());
3762 for (TemplateParameterList::const_iterator
3763 P = TemplateParams->begin(), PEnd = TemplateParams->end();
3765 AddDeclRef(*P, Record);
3768 /// \brief Emit a template argument list.
3770 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3771 RecordDataImpl &Record) {
3772 assert(TemplateArgs && "No TemplateArgs!");
3773 Record.push_back(TemplateArgs->size());
3774 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3775 AddTemplateArgument(TemplateArgs->get(i), Record);
3780 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3781 Record.push_back(Set.size());
3782 for (UnresolvedSetImpl::const_iterator
3783 I = Set.begin(), E = Set.end(); I != E; ++I) {
3784 AddDeclRef(I.getDecl(), Record);
3785 Record.push_back(I.getAccess());
3789 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3790 RecordDataImpl &Record) {
3791 Record.push_back(Base.isVirtual());
3792 Record.push_back(Base.isBaseOfClass());
3793 Record.push_back(Base.getAccessSpecifierAsWritten());
3794 Record.push_back(Base.getInheritConstructors());
3795 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3796 AddSourceRange(Base.getSourceRange(), Record);
3797 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3802 void ASTWriter::FlushCXXBaseSpecifiers() {
3804 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3807 // Record the offset of this base-specifier set.
3808 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3809 if (Index == CXXBaseSpecifiersOffsets.size())
3810 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3812 if (Index > CXXBaseSpecifiersOffsets.size())
3813 CXXBaseSpecifiersOffsets.resize(Index + 1);
3814 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3817 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3818 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3819 Record.push_back(BEnd - B);
3820 for (; B != BEnd; ++B)
3821 AddCXXBaseSpecifier(*B, Record);
3822 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3824 // Flush any expressions that were written as part of the base specifiers.
3828 CXXBaseSpecifiersToWrite.clear();
3831 void ASTWriter::AddCXXCtorInitializers(
3832 const CXXCtorInitializer * const *CtorInitializers,
3833 unsigned NumCtorInitializers,
3834 RecordDataImpl &Record) {
3835 Record.push_back(NumCtorInitializers);
3836 for (unsigned i=0; i != NumCtorInitializers; ++i) {
3837 const CXXCtorInitializer *Init = CtorInitializers[i];
3839 if (Init->isBaseInitializer()) {
3840 Record.push_back(CTOR_INITIALIZER_BASE);
3841 AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3842 Record.push_back(Init->isBaseVirtual());
3843 } else if (Init->isDelegatingInitializer()) {
3844 Record.push_back(CTOR_INITIALIZER_DELEGATING);
3845 AddDeclRef(Init->getTargetConstructor(), Record);
3846 } else if (Init->isMemberInitializer()){
3847 Record.push_back(CTOR_INITIALIZER_MEMBER);
3848 AddDeclRef(Init->getMember(), Record);
3850 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
3851 AddDeclRef(Init->getIndirectMember(), Record);
3854 AddSourceLocation(Init->getMemberLocation(), Record);
3855 AddStmt(Init->getInit());
3856 AddSourceLocation(Init->getLParenLoc(), Record);
3857 AddSourceLocation(Init->getRParenLoc(), Record);
3858 Record.push_back(Init->isWritten());
3859 if (Init->isWritten()) {
3860 Record.push_back(Init->getSourceOrder());
3862 Record.push_back(Init->getNumArrayIndices());
3863 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3864 AddDeclRef(Init->getArrayIndex(i), Record);
3869 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3870 assert(D->DefinitionData);
3871 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3872 Record.push_back(Data.UserDeclaredConstructor);
3873 Record.push_back(Data.UserDeclaredCopyConstructor);
3874 Record.push_back(Data.UserDeclaredCopyAssignment);
3875 Record.push_back(Data.UserDeclaredDestructor);
3876 Record.push_back(Data.Aggregate);
3877 Record.push_back(Data.PlainOldData);
3878 Record.push_back(Data.Empty);
3879 Record.push_back(Data.Polymorphic);
3880 Record.push_back(Data.Abstract);
3881 Record.push_back(Data.IsStandardLayout);
3882 Record.push_back(Data.HasNoNonEmptyBases);
3883 Record.push_back(Data.HasPrivateFields);
3884 Record.push_back(Data.HasProtectedFields);
3885 Record.push_back(Data.HasPublicFields);
3886 Record.push_back(Data.HasMutableFields);
3887 Record.push_back(Data.HasTrivialDefaultConstructor);
3888 Record.push_back(Data.HasConstExprNonCopyMoveConstructor);
3889 Record.push_back(Data.HasTrivialCopyConstructor);
3890 Record.push_back(Data.HasTrivialMoveConstructor);
3891 Record.push_back(Data.HasTrivialCopyAssignment);
3892 Record.push_back(Data.HasTrivialMoveAssignment);
3893 Record.push_back(Data.HasTrivialDestructor);
3894 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
3895 Record.push_back(Data.ComputedVisibleConversions);
3896 Record.push_back(Data.UserProvidedDefaultConstructor);
3897 Record.push_back(Data.DeclaredDefaultConstructor);
3898 Record.push_back(Data.DeclaredCopyConstructor);
3899 Record.push_back(Data.DeclaredCopyAssignment);
3900 Record.push_back(Data.DeclaredDestructor);
3902 Record.push_back(Data.NumBases);
3903 if (Data.NumBases > 0)
3904 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3907 // FIXME: Make VBases lazily computed when needed to avoid storing them.
3908 Record.push_back(Data.NumVBases);
3909 if (Data.NumVBases > 0)
3910 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3913 AddUnresolvedSet(Data.Conversions, Record);
3914 AddUnresolvedSet(Data.VisibleConversions, Record);
3915 // Data.Definition is the owning decl, no need to write it.
3916 AddDeclRef(Data.FirstFriend, Record);
3919 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3920 assert(Reader && "Cannot remove chain");
3921 assert(!Chain && "Cannot replace chain");
3922 assert(FirstDeclID == NextDeclID &&
3923 FirstTypeID == NextTypeID &&
3924 FirstIdentID == NextIdentID &&
3925 FirstSelectorID == NextSelectorID &&
3926 FirstMacroID == NextMacroID &&
3927 FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3928 "Setting chain after writing has started.");
3931 FirstDeclID += Chain->getTotalNumDecls();
3932 FirstTypeID += Chain->getTotalNumTypes();
3933 FirstIdentID += Chain->getTotalNumIdentifiers();
3934 FirstSelectorID += Chain->getTotalNumSelectors();
3935 FirstMacroID += Chain->getTotalNumMacroDefinitions();
3936 FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3937 NextDeclID = FirstDeclID;
3938 NextTypeID = FirstTypeID;
3939 NextIdentID = FirstIdentID;
3940 NextSelectorID = FirstSelectorID;
3941 NextMacroID = FirstMacroID;
3942 NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3945 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3946 IdentifierIDs[II] = ID;
3947 if (II->hasMacroDefinition())
3948 DeserializedMacroNames.push_back(II);
3951 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3952 // Always take the highest-numbered type index. This copes with an interesting
3953 // case for chained AST writing where we schedule writing the type and then,
3954 // later, deserialize the type from another AST. In this case, we want to
3955 // keep the higher-numbered entry so that we can properly write it out to
3957 TypeIdx &StoredIdx = TypeIdxs[T];
3958 if (Idx.getIndex() >= StoredIdx.getIndex())
3962 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3966 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3967 SelectorIDs[S] = ID;
3970 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3971 MacroDefinition *MD) {
3972 MacroDefinitions[MD] = ID;
3975 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3976 assert(D->isDefinition());
3977 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3978 // We are interested when a PCH decl is modified.
3979 if (RD->getPCHLevel() > 0) {
3980 // A forward reference was mutated into a definition. Rewrite it.
3981 // FIXME: This happens during template instantiation, should we
3982 // have created a new definition decl instead ?
3986 for (CXXRecordDecl::redecl_iterator
3987 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3988 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3992 // We are interested when a PCH decl is modified.
3993 if (Redecl->getPCHLevel() > 0) {
3994 UpdateRecord &Record = DeclUpdates[Redecl];
3995 Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3996 assert(Redecl->DefinitionData);
3997 assert(Redecl->DefinitionData->Definition == D);
3998 AddDeclRef(D, Record); // the DefinitionDecl
4003 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
4004 // TU and namespaces are handled elsewhere.
4005 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
4008 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
4009 return; // Not a source decl added to a DeclContext from PCH.
4011 AddUpdatedDeclContext(DC);
4014 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
4015 assert(D->isImplicit());
4016 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
4017 return; // Not a source member added to a class from PCH.
4018 if (!isa<CXXMethodDecl>(D))
4019 return; // We are interested in lazily declared implicit methods.
4021 // A decl coming from PCH was modified.
4022 assert(RD->isDefinition());
4023 UpdateRecord &Record = DeclUpdates[RD];
4024 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
4025 AddDeclRef(D, Record);
4028 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4029 const ClassTemplateSpecializationDecl *D) {
4030 // The specializations set is kept in the canonical template.
4031 TD = TD->getCanonicalDecl();
4032 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4033 return; // Not a source specialization added to a template from PCH.
4035 UpdateRecord &Record = DeclUpdates[TD];
4036 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4037 AddDeclRef(D, Record);
4040 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4041 const FunctionDecl *D) {
4042 // The specializations set is kept in the canonical template.
4043 TD = TD->getCanonicalDecl();
4044 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4045 return; // Not a source specialization added to a template from PCH.
4047 UpdateRecord &Record = DeclUpdates[TD];
4048 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4049 AddDeclRef(D, Record);
4052 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4053 if (D->getPCHLevel() == 0)
4054 return; // Declaration not imported from PCH.
4056 // Implicit decl from a PCH was defined.
4057 // FIXME: Should implicit definition be a separate FunctionDecl?
4061 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4062 if (D->getPCHLevel() == 0)
4065 // Since the actual instantiation is delayed, this really means that we need
4066 // to update the instantiation location.
4067 UpdateRecord &Record = DeclUpdates[D];
4068 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4070 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4073 ASTSerializationListener::~ASTSerializationListener() { }