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 "ASTCommon.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/IdentifierResolver.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLocVisitor.h"
27 #include "clang/Serialization/ASTReader.h"
28 #include "clang/Lex/HeaderSearchOptions.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Lex/HeaderSearch.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/FileSystemStatCache.h"
36 #include "clang/Basic/OnDiskHashTable.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/SourceManagerInternals.h"
39 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Basic/TargetOptions.h"
41 #include "clang/Basic/Version.h"
42 #include "clang/Basic/VersionTuple.h"
43 #include "llvm/ADT/APFloat.h"
44 #include "llvm/ADT/APInt.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Bitcode/BitstreamWriter.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
54 using namespace clang;
55 using namespace clang::serialization;
57 template <typename T, typename Allocator>
58 static StringRef data(const std::vector<T, Allocator> &v) {
59 if (v.empty()) return StringRef();
60 return StringRef(reinterpret_cast<const char*>(&v[0]),
61 sizeof(T) * v.size());
65 static StringRef data(const SmallVectorImpl<T> &v) {
66 return StringRef(reinterpret_cast<const char*>(v.data()),
67 sizeof(T) * v.size());
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
77 ASTWriter::RecordDataImpl &Record;
80 /// \brief Type code that corresponds to the record generated.
83 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
84 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
86 void VisitArrayType(const ArrayType *T);
87 void VisitFunctionType(const FunctionType *T);
88 void VisitTagType(const TagType *T);
90 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
91 #define ABSTRACT_TYPE(Class, Base)
92 #include "clang/AST/TypeNodes.def"
96 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
97 llvm_unreachable("Built-in types are never serialized");
100 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
101 Writer.AddTypeRef(T->getElementType(), Record);
105 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
106 Writer.AddTypeRef(T->getPointeeType(), Record);
110 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
111 Writer.AddTypeRef(T->getPointeeType(), Record);
112 Code = TYPE_BLOCK_POINTER;
115 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
116 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
117 Record.push_back(T->isSpelledAsLValue());
118 Code = TYPE_LVALUE_REFERENCE;
121 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
122 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
123 Code = TYPE_RVALUE_REFERENCE;
126 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
127 Writer.AddTypeRef(T->getPointeeType(), Record);
128 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
129 Code = TYPE_MEMBER_POINTER;
132 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
133 Writer.AddTypeRef(T->getElementType(), Record);
134 Record.push_back(T->getSizeModifier()); // FIXME: stable values
135 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
138 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
140 Writer.AddAPInt(T->getSize(), Record);
141 Code = TYPE_CONSTANT_ARRAY;
144 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
146 Code = TYPE_INCOMPLETE_ARRAY;
149 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
151 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
152 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
153 Writer.AddStmt(T->getSizeExpr());
154 Code = TYPE_VARIABLE_ARRAY;
157 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
158 Writer.AddTypeRef(T->getElementType(), Record);
159 Record.push_back(T->getNumElements());
160 Record.push_back(T->getVectorKind());
164 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
166 Code = TYPE_EXT_VECTOR;
169 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
170 Writer.AddTypeRef(T->getResultType(), Record);
171 FunctionType::ExtInfo C = T->getExtInfo();
172 Record.push_back(C.getNoReturn());
173 Record.push_back(C.getHasRegParm());
174 Record.push_back(C.getRegParm());
175 // FIXME: need to stabilize encoding of calling convention...
176 Record.push_back(C.getCC());
177 Record.push_back(C.getProducesResult());
180 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
181 VisitFunctionType(T);
182 Code = TYPE_FUNCTION_NO_PROTO;
185 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
186 VisitFunctionType(T);
187 Record.push_back(T->getNumArgs());
188 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
189 Writer.AddTypeRef(T->getArgType(I), Record);
190 Record.push_back(T->isVariadic());
191 Record.push_back(T->hasTrailingReturn());
192 Record.push_back(T->getTypeQuals());
193 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
194 Record.push_back(T->getExceptionSpecType());
195 if (T->getExceptionSpecType() == EST_Dynamic) {
196 Record.push_back(T->getNumExceptions());
197 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
198 Writer.AddTypeRef(T->getExceptionType(I), Record);
199 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
200 Writer.AddStmt(T->getNoexceptExpr());
201 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
202 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
203 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
204 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
205 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
207 Code = TYPE_FUNCTION_PROTO;
210 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
211 Writer.AddDeclRef(T->getDecl(), Record);
212 Code = TYPE_UNRESOLVED_USING;
215 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
216 Writer.AddDeclRef(T->getDecl(), Record);
217 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
218 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
222 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
223 Writer.AddStmt(T->getUnderlyingExpr());
224 Code = TYPE_TYPEOF_EXPR;
227 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
228 Writer.AddTypeRef(T->getUnderlyingType(), Record);
232 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
233 Writer.AddTypeRef(T->getUnderlyingType(), Record);
234 Writer.AddStmt(T->getUnderlyingExpr());
235 Code = TYPE_DECLTYPE;
238 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
239 Writer.AddTypeRef(T->getBaseType(), Record);
240 Writer.AddTypeRef(T->getUnderlyingType(), Record);
241 Record.push_back(T->getUTTKind());
242 Code = TYPE_UNARY_TRANSFORM;
245 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
246 Writer.AddTypeRef(T->getDeducedType(), Record);
250 void ASTTypeWriter::VisitTagType(const TagType *T) {
251 Record.push_back(T->isDependentType());
252 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
253 assert(!T->isBeingDefined() &&
254 "Cannot serialize in the middle of a type definition");
257 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
262 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
267 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
268 Writer.AddTypeRef(T->getModifiedType(), Record);
269 Writer.AddTypeRef(T->getEquivalentType(), Record);
270 Record.push_back(T->getAttrKind());
271 Code = TYPE_ATTRIBUTED;
275 ASTTypeWriter::VisitSubstTemplateTypeParmType(
276 const SubstTemplateTypeParmType *T) {
277 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
278 Writer.AddTypeRef(T->getReplacementType(), Record);
279 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
283 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
284 const SubstTemplateTypeParmPackType *T) {
285 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
286 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
287 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
291 ASTTypeWriter::VisitTemplateSpecializationType(
292 const TemplateSpecializationType *T) {
293 Record.push_back(T->isDependentType());
294 Writer.AddTemplateName(T->getTemplateName(), Record);
295 Record.push_back(T->getNumArgs());
296 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
297 ArgI != ArgE; ++ArgI)
298 Writer.AddTemplateArgument(*ArgI, Record);
299 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
300 T->isCanonicalUnqualified() ? QualType()
301 : T->getCanonicalTypeInternal(),
303 Code = TYPE_TEMPLATE_SPECIALIZATION;
307 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
309 Writer.AddStmt(T->getSizeExpr());
310 Writer.AddSourceRange(T->getBracketsRange(), Record);
311 Code = TYPE_DEPENDENT_SIZED_ARRAY;
315 ASTTypeWriter::VisitDependentSizedExtVectorType(
316 const DependentSizedExtVectorType *T) {
317 // FIXME: Serialize this type (C++ only)
318 llvm_unreachable("Cannot serialize dependent sized extended vector types");
322 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
323 Record.push_back(T->getDepth());
324 Record.push_back(T->getIndex());
325 Record.push_back(T->isParameterPack());
326 Writer.AddDeclRef(T->getDecl(), Record);
327 Code = TYPE_TEMPLATE_TYPE_PARM;
331 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
332 Record.push_back(T->getKeyword());
333 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
334 Writer.AddIdentifierRef(T->getIdentifier(), Record);
335 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
336 : T->getCanonicalTypeInternal(),
338 Code = TYPE_DEPENDENT_NAME;
342 ASTTypeWriter::VisitDependentTemplateSpecializationType(
343 const DependentTemplateSpecializationType *T) {
344 Record.push_back(T->getKeyword());
345 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
346 Writer.AddIdentifierRef(T->getIdentifier(), Record);
347 Record.push_back(T->getNumArgs());
348 for (DependentTemplateSpecializationType::iterator
349 I = T->begin(), E = T->end(); I != E; ++I)
350 Writer.AddTemplateArgument(*I, Record);
351 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
354 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
355 Writer.AddTypeRef(T->getPattern(), Record);
356 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
357 Record.push_back(*NumExpansions + 1);
360 Code = TYPE_PACK_EXPANSION;
363 void ASTTypeWriter::VisitParenType(const ParenType *T) {
364 Writer.AddTypeRef(T->getInnerType(), Record);
368 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
369 Record.push_back(T->getKeyword());
370 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
371 Writer.AddTypeRef(T->getNamedType(), Record);
372 Code = TYPE_ELABORATED;
375 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
376 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
377 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
378 Code = TYPE_INJECTED_CLASS_NAME;
381 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
382 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
383 Code = TYPE_OBJC_INTERFACE;
386 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
387 Writer.AddTypeRef(T->getBaseType(), Record);
388 Record.push_back(T->getNumProtocols());
389 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
390 E = T->qual_end(); I != E; ++I)
391 Writer.AddDeclRef(*I, Record);
392 Code = TYPE_OBJC_OBJECT;
396 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
397 Writer.AddTypeRef(T->getPointeeType(), Record);
398 Code = TYPE_OBJC_OBJECT_POINTER;
402 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
403 Writer.AddTypeRef(T->getValueType(), Record);
409 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
411 ASTWriter::RecordDataImpl &Record;
414 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
415 : Writer(Writer), Record(Record) { }
417 #define ABSTRACT_TYPELOC(CLASS, PARENT)
418 #define TYPELOC(CLASS, PARENT) \
419 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
420 #include "clang/AST/TypeLocNodes.def"
422 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
423 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
428 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
431 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
432 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
433 if (TL.needsExtraLocalData()) {
434 Record.push_back(TL.getWrittenTypeSpec());
435 Record.push_back(TL.getWrittenSignSpec());
436 Record.push_back(TL.getWrittenWidthSpec());
437 Record.push_back(TL.hasModeAttr());
440 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
441 Writer.AddSourceLocation(TL.getNameLoc(), Record);
443 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
444 Writer.AddSourceLocation(TL.getStarLoc(), Record);
446 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
447 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
449 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
450 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
452 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
453 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
455 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
456 Writer.AddSourceLocation(TL.getStarLoc(), Record);
457 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
459 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
460 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
461 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
462 Record.push_back(TL.getSizeExpr() ? 1 : 0);
463 if (TL.getSizeExpr())
464 Writer.AddStmt(TL.getSizeExpr());
466 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
467 VisitArrayTypeLoc(TL);
469 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
470 VisitArrayTypeLoc(TL);
472 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
473 VisitArrayTypeLoc(TL);
475 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
476 DependentSizedArrayTypeLoc TL) {
477 VisitArrayTypeLoc(TL);
479 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
480 DependentSizedExtVectorTypeLoc TL) {
481 Writer.AddSourceLocation(TL.getNameLoc(), Record);
483 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
484 Writer.AddSourceLocation(TL.getNameLoc(), Record);
486 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
487 Writer.AddSourceLocation(TL.getNameLoc(), Record);
489 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
490 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
491 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
492 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
493 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
494 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
495 Writer.AddDeclRef(TL.getArg(i), Record);
497 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
498 VisitFunctionTypeLoc(TL);
500 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
501 VisitFunctionTypeLoc(TL);
503 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
504 Writer.AddSourceLocation(TL.getNameLoc(), Record);
506 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
507 Writer.AddSourceLocation(TL.getNameLoc(), Record);
509 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
510 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
511 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
512 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
514 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
515 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
516 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
517 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
518 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
520 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
521 Writer.AddSourceLocation(TL.getNameLoc(), Record);
523 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
524 Writer.AddSourceLocation(TL.getKWLoc(), Record);
525 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
526 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
527 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
529 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
530 Writer.AddSourceLocation(TL.getNameLoc(), Record);
532 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
533 Writer.AddSourceLocation(TL.getNameLoc(), Record);
535 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
536 Writer.AddSourceLocation(TL.getNameLoc(), Record);
538 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
539 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
540 if (TL.hasAttrOperand()) {
541 SourceRange range = TL.getAttrOperandParensRange();
542 Writer.AddSourceLocation(range.getBegin(), Record);
543 Writer.AddSourceLocation(range.getEnd(), Record);
545 if (TL.hasAttrExprOperand()) {
546 Expr *operand = TL.getAttrExprOperand();
547 Record.push_back(operand ? 1 : 0);
548 if (operand) Writer.AddStmt(operand);
549 } else if (TL.hasAttrEnumOperand()) {
550 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
553 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
554 Writer.AddSourceLocation(TL.getNameLoc(), Record);
556 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
557 SubstTemplateTypeParmTypeLoc TL) {
558 Writer.AddSourceLocation(TL.getNameLoc(), Record);
560 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
561 SubstTemplateTypeParmPackTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getNameLoc(), Record);
564 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
565 TemplateSpecializationTypeLoc TL) {
566 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
567 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
568 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
569 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
570 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
571 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
572 TL.getArgLoc(i).getLocInfo(), Record);
574 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
575 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
576 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
578 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
579 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
580 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
582 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
583 Writer.AddSourceLocation(TL.getNameLoc(), Record);
585 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
586 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
587 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
588 Writer.AddSourceLocation(TL.getNameLoc(), Record);
590 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
591 DependentTemplateSpecializationTypeLoc TL) {
592 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
593 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
594 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
595 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
596 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
597 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
598 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
599 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
600 TL.getArgLoc(I).getLocInfo(), Record);
602 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
603 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
605 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
606 Writer.AddSourceLocation(TL.getNameLoc(), Record);
608 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
609 Record.push_back(TL.hasBaseTypeAsWritten());
610 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
611 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
612 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
613 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
615 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
616 Writer.AddSourceLocation(TL.getStarLoc(), Record);
618 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
619 Writer.AddSourceLocation(TL.getKWLoc(), Record);
620 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
621 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
624 //===----------------------------------------------------------------------===//
625 // ASTWriter Implementation
626 //===----------------------------------------------------------------------===//
628 static void EmitBlockID(unsigned ID, const char *Name,
629 llvm::BitstreamWriter &Stream,
630 ASTWriter::RecordDataImpl &Record) {
632 Record.push_back(ID);
633 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
635 // Emit the block name if present.
636 if (Name == 0 || Name[0] == 0) return;
639 Record.push_back(*Name++);
640 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
643 static void EmitRecordID(unsigned ID, const char *Name,
644 llvm::BitstreamWriter &Stream,
645 ASTWriter::RecordDataImpl &Record) {
647 Record.push_back(ID);
649 Record.push_back(*Name++);
650 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
653 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
654 ASTWriter::RecordDataImpl &Record) {
655 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
657 RECORD(STMT_NULL_PTR);
659 RECORD(STMT_COMPOUND);
661 RECORD(STMT_DEFAULT);
663 RECORD(STMT_ATTRIBUTED);
670 RECORD(STMT_INDIRECT_GOTO);
671 RECORD(STMT_CONTINUE);
677 RECORD(EXPR_PREDEFINED);
678 RECORD(EXPR_DECL_REF);
679 RECORD(EXPR_INTEGER_LITERAL);
680 RECORD(EXPR_FLOATING_LITERAL);
681 RECORD(EXPR_IMAGINARY_LITERAL);
682 RECORD(EXPR_STRING_LITERAL);
683 RECORD(EXPR_CHARACTER_LITERAL);
685 RECORD(EXPR_UNARY_OPERATOR);
686 RECORD(EXPR_SIZEOF_ALIGN_OF);
687 RECORD(EXPR_ARRAY_SUBSCRIPT);
690 RECORD(EXPR_BINARY_OPERATOR);
691 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
692 RECORD(EXPR_CONDITIONAL_OPERATOR);
693 RECORD(EXPR_IMPLICIT_CAST);
694 RECORD(EXPR_CSTYLE_CAST);
695 RECORD(EXPR_COMPOUND_LITERAL);
696 RECORD(EXPR_EXT_VECTOR_ELEMENT);
697 RECORD(EXPR_INIT_LIST);
698 RECORD(EXPR_DESIGNATED_INIT);
699 RECORD(EXPR_IMPLICIT_VALUE_INIT);
701 RECORD(EXPR_ADDR_LABEL);
704 RECORD(EXPR_GNU_NULL);
705 RECORD(EXPR_SHUFFLE_VECTOR);
707 RECORD(EXPR_GENERIC_SELECTION);
708 RECORD(EXPR_OBJC_STRING_LITERAL);
709 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
710 RECORD(EXPR_OBJC_ARRAY_LITERAL);
711 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
712 RECORD(EXPR_OBJC_ENCODE);
713 RECORD(EXPR_OBJC_SELECTOR_EXPR);
714 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
715 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
716 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
717 RECORD(EXPR_OBJC_KVC_REF_EXPR);
718 RECORD(EXPR_OBJC_MESSAGE_EXPR);
719 RECORD(STMT_OBJC_FOR_COLLECTION);
720 RECORD(STMT_OBJC_CATCH);
721 RECORD(STMT_OBJC_FINALLY);
722 RECORD(STMT_OBJC_AT_TRY);
723 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
724 RECORD(STMT_OBJC_AT_THROW);
725 RECORD(EXPR_OBJC_BOOL_LITERAL);
726 RECORD(EXPR_CXX_OPERATOR_CALL);
727 RECORD(EXPR_CXX_CONSTRUCT);
728 RECORD(EXPR_CXX_STATIC_CAST);
729 RECORD(EXPR_CXX_DYNAMIC_CAST);
730 RECORD(EXPR_CXX_REINTERPRET_CAST);
731 RECORD(EXPR_CXX_CONST_CAST);
732 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
733 RECORD(EXPR_USER_DEFINED_LITERAL);
734 RECORD(EXPR_CXX_BOOL_LITERAL);
735 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
736 RECORD(EXPR_CXX_TYPEID_EXPR);
737 RECORD(EXPR_CXX_TYPEID_TYPE);
738 RECORD(EXPR_CXX_UUIDOF_EXPR);
739 RECORD(EXPR_CXX_UUIDOF_TYPE);
740 RECORD(EXPR_CXX_THIS);
741 RECORD(EXPR_CXX_THROW);
742 RECORD(EXPR_CXX_DEFAULT_ARG);
743 RECORD(EXPR_CXX_BIND_TEMPORARY);
744 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
745 RECORD(EXPR_CXX_NEW);
746 RECORD(EXPR_CXX_DELETE);
747 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
748 RECORD(EXPR_EXPR_WITH_CLEANUPS);
749 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
750 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
751 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
752 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
753 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
754 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
755 RECORD(EXPR_CXX_NOEXCEPT);
756 RECORD(EXPR_OPAQUE_VALUE);
757 RECORD(EXPR_BINARY_TYPE_TRAIT);
758 RECORD(EXPR_PACK_EXPANSION);
759 RECORD(EXPR_SIZEOF_PACK);
760 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
761 RECORD(EXPR_CUDA_KERNEL_CALL);
765 void ASTWriter::WriteBlockInfoBlock() {
767 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
769 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
770 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
773 BLOCK(CONTROL_BLOCK);
776 RECORD(LANGUAGE_OPTIONS);
777 RECORD(TARGET_OPTIONS);
778 RECORD(ORIGINAL_FILE);
779 RECORD(ORIGINAL_PCH_DIR);
780 RECORD(INPUT_FILE_OFFSETS);
781 RECORD(DIAGNOSTIC_OPTIONS);
782 RECORD(FILE_SYSTEM_OPTIONS);
783 RECORD(HEADER_SEARCH_OPTIONS);
784 RECORD(PREPROCESSOR_OPTIONS);
786 BLOCK(INPUT_FILES_BLOCK);
789 // AST Top-Level Block.
793 RECORD(IDENTIFIER_OFFSET);
794 RECORD(IDENTIFIER_TABLE);
795 RECORD(EXTERNAL_DEFINITIONS);
796 RECORD(SPECIAL_TYPES);
798 RECORD(TENTATIVE_DEFINITIONS);
799 RECORD(UNUSED_FILESCOPED_DECLS);
800 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
801 RECORD(SELECTOR_OFFSETS);
803 RECORD(PP_COUNTER_VALUE);
804 RECORD(SOURCE_LOCATION_OFFSETS);
805 RECORD(SOURCE_LOCATION_PRELOADS);
806 RECORD(EXT_VECTOR_DECLS);
807 RECORD(PPD_ENTITIES_OFFSETS);
808 RECORD(REFERENCED_SELECTOR_POOL);
809 RECORD(TU_UPDATE_LEXICAL);
810 RECORD(LOCAL_REDECLARATIONS_MAP);
811 RECORD(SEMA_DECL_REFS);
812 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
813 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
814 RECORD(DECL_REPLACEMENTS);
815 RECORD(UPDATE_VISIBLE);
816 RECORD(DECL_UPDATE_OFFSETS);
817 RECORD(DECL_UPDATES);
818 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
819 RECORD(DIAG_PRAGMA_MAPPINGS);
820 RECORD(CUDA_SPECIAL_DECL_REFS);
821 RECORD(HEADER_SEARCH_TABLE);
822 RECORD(FP_PRAGMA_OPTIONS);
823 RECORD(OPENCL_EXTENSIONS);
824 RECORD(DELEGATING_CTORS);
825 RECORD(KNOWN_NAMESPACES);
826 RECORD(MODULE_OFFSET_MAP);
827 RECORD(SOURCE_MANAGER_LINE_TABLE);
828 RECORD(OBJC_CATEGORIES_MAP);
829 RECORD(FILE_SORTED_DECLS);
830 RECORD(IMPORTED_MODULES);
831 RECORD(MERGED_DECLARATIONS);
832 RECORD(LOCAL_REDECLARATIONS);
833 RECORD(OBJC_CATEGORIES);
834 RECORD(MACRO_OFFSET);
835 RECORD(MACRO_UPDATES);
837 // SourceManager Block.
838 BLOCK(SOURCE_MANAGER_BLOCK);
839 RECORD(SM_SLOC_FILE_ENTRY);
840 RECORD(SM_SLOC_BUFFER_ENTRY);
841 RECORD(SM_SLOC_BUFFER_BLOB);
842 RECORD(SM_SLOC_EXPANSION_ENTRY);
844 // Preprocessor Block.
845 BLOCK(PREPROCESSOR_BLOCK);
846 RECORD(PP_MACRO_OBJECT_LIKE);
847 RECORD(PP_MACRO_FUNCTION_LIKE);
850 // Decls and Types block.
851 BLOCK(DECLTYPES_BLOCK);
852 RECORD(TYPE_EXT_QUAL);
853 RECORD(TYPE_COMPLEX);
854 RECORD(TYPE_POINTER);
855 RECORD(TYPE_BLOCK_POINTER);
856 RECORD(TYPE_LVALUE_REFERENCE);
857 RECORD(TYPE_RVALUE_REFERENCE);
858 RECORD(TYPE_MEMBER_POINTER);
859 RECORD(TYPE_CONSTANT_ARRAY);
860 RECORD(TYPE_INCOMPLETE_ARRAY);
861 RECORD(TYPE_VARIABLE_ARRAY);
863 RECORD(TYPE_EXT_VECTOR);
864 RECORD(TYPE_FUNCTION_PROTO);
865 RECORD(TYPE_FUNCTION_NO_PROTO);
866 RECORD(TYPE_TYPEDEF);
867 RECORD(TYPE_TYPEOF_EXPR);
871 RECORD(TYPE_OBJC_INTERFACE);
872 RECORD(TYPE_OBJC_OBJECT);
873 RECORD(TYPE_OBJC_OBJECT_POINTER);
874 RECORD(TYPE_DECLTYPE);
875 RECORD(TYPE_ELABORATED);
876 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
877 RECORD(TYPE_UNRESOLVED_USING);
878 RECORD(TYPE_INJECTED_CLASS_NAME);
879 RECORD(TYPE_OBJC_OBJECT);
880 RECORD(TYPE_TEMPLATE_TYPE_PARM);
881 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
882 RECORD(TYPE_DEPENDENT_NAME);
883 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
884 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
886 RECORD(TYPE_PACK_EXPANSION);
887 RECORD(TYPE_ATTRIBUTED);
888 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
890 RECORD(DECL_TYPEDEF);
893 RECORD(DECL_ENUM_CONSTANT);
894 RECORD(DECL_FUNCTION);
895 RECORD(DECL_OBJC_METHOD);
896 RECORD(DECL_OBJC_INTERFACE);
897 RECORD(DECL_OBJC_PROTOCOL);
898 RECORD(DECL_OBJC_IVAR);
899 RECORD(DECL_OBJC_AT_DEFS_FIELD);
900 RECORD(DECL_OBJC_CATEGORY);
901 RECORD(DECL_OBJC_CATEGORY_IMPL);
902 RECORD(DECL_OBJC_IMPLEMENTATION);
903 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
904 RECORD(DECL_OBJC_PROPERTY);
905 RECORD(DECL_OBJC_PROPERTY_IMPL);
908 RECORD(DECL_IMPLICIT_PARAM);
909 RECORD(DECL_PARM_VAR);
910 RECORD(DECL_FILE_SCOPE_ASM);
912 RECORD(DECL_CONTEXT_LEXICAL);
913 RECORD(DECL_CONTEXT_VISIBLE);
914 RECORD(DECL_NAMESPACE);
915 RECORD(DECL_NAMESPACE_ALIAS);
917 RECORD(DECL_USING_SHADOW);
918 RECORD(DECL_USING_DIRECTIVE);
919 RECORD(DECL_UNRESOLVED_USING_VALUE);
920 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
921 RECORD(DECL_LINKAGE_SPEC);
922 RECORD(DECL_CXX_RECORD);
923 RECORD(DECL_CXX_METHOD);
924 RECORD(DECL_CXX_CONSTRUCTOR);
925 RECORD(DECL_CXX_DESTRUCTOR);
926 RECORD(DECL_CXX_CONVERSION);
927 RECORD(DECL_ACCESS_SPEC);
929 RECORD(DECL_FRIEND_TEMPLATE);
930 RECORD(DECL_CLASS_TEMPLATE);
931 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
932 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
933 RECORD(DECL_FUNCTION_TEMPLATE);
934 RECORD(DECL_TEMPLATE_TYPE_PARM);
935 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
936 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
937 RECORD(DECL_STATIC_ASSERT);
938 RECORD(DECL_CXX_BASE_SPECIFIERS);
939 RECORD(DECL_INDIRECTFIELD);
940 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
942 // Statements and Exprs can occur in the Decls and Types block.
943 AddStmtsExprs(Stream, Record);
945 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
946 RECORD(PPD_MACRO_EXPANSION);
947 RECORD(PPD_MACRO_DEFINITION);
948 RECORD(PPD_INCLUSION_DIRECTIVE);
955 /// \brief Adjusts the given filename to only write out the portion of the
956 /// filename that is not part of the system root directory.
958 /// \param Filename the file name to adjust.
960 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
961 /// the returned filename will be adjusted by this system root.
963 /// \returns either the original filename (if it needs no adjustment) or the
964 /// adjusted filename (which points into the @p Filename parameter).
966 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
967 assert(Filename && "No file name to adjust?");
969 if (isysroot.empty())
972 // Verify that the filename and the system root have the same prefix.
974 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
975 if (Filename[Pos] != isysroot[Pos])
976 return Filename; // Prefixes don't match.
978 // We hit the end of the filename before we hit the end of the system root.
982 // If the file name has a '/' at the current position, skip over the '/'.
983 // We distinguish sysroot-based includes from absolute includes by the
984 // absence of '/' at the beginning of sysroot-based includes.
985 if (Filename[Pos] == '/')
988 return Filename + Pos;
991 /// \brief Write the control block.
992 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
994 const std::string &OutputFile) {
995 using namespace llvm;
996 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1000 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1001 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1002 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1003 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1004 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1005 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1006 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1007 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1008 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1009 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1010 Record.push_back(METADATA);
1011 Record.push_back(VERSION_MAJOR);
1012 Record.push_back(VERSION_MINOR);
1013 Record.push_back(CLANG_VERSION_MAJOR);
1014 Record.push_back(CLANG_VERSION_MINOR);
1015 Record.push_back(!isysroot.empty());
1016 Record.push_back(ASTHasCompilerErrors);
1017 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1018 getClangFullRepositoryVersion());
1022 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1023 llvm::SmallVector<char, 128> ModulePaths;
1026 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1028 // Skip modules that weren't directly imported.
1029 if (!(*M)->isDirectlyImported())
1032 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1033 // FIXME: Write import location, once it matters.
1034 // FIXME: This writes the absolute path for AST files we depend on.
1035 const std::string &FileName = (*M)->FileName;
1036 Record.push_back(FileName.size());
1037 Record.append(FileName.begin(), FileName.end());
1039 Stream.EmitRecord(IMPORTS, Record);
1042 // Language options.
1044 const LangOptions &LangOpts = Context.getLangOpts();
1045 #define LANGOPT(Name, Bits, Default, Description) \
1046 Record.push_back(LangOpts.Name);
1047 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1048 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1049 #include "clang/Basic/LangOptions.def"
1051 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1052 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1054 Record.push_back(LangOpts.CurrentModule.size());
1055 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1056 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1060 const TargetInfo &Target = Context.getTargetInfo();
1061 const TargetOptions &TargetOpts = Target.getTargetOpts();
1062 AddString(TargetOpts.Triple, Record);
1063 AddString(TargetOpts.CPU, Record);
1064 AddString(TargetOpts.ABI, Record);
1065 AddString(TargetOpts.CXXABI, Record);
1066 AddString(TargetOpts.LinkerVersion, Record);
1067 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1068 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1069 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1071 Record.push_back(TargetOpts.Features.size());
1072 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1073 AddString(TargetOpts.Features[I], Record);
1075 Stream.EmitRecord(TARGET_OPTIONS, Record);
1077 // Diagnostic options.
1079 const DiagnosticOptions &DiagOpts
1080 = Context.getDiagnostics().getDiagnosticOptions();
1081 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1082 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1083 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1084 #include "clang/Basic/DiagnosticOptions.def"
1085 Record.push_back(DiagOpts.Warnings.size());
1086 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1087 AddString(DiagOpts.Warnings[I], Record);
1088 // Note: we don't serialize the log or serialization file names, because they
1089 // are generally transient files and will almost always be overridden.
1090 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1092 // File system options.
1094 const FileSystemOptions &FSOpts
1095 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1096 AddString(FSOpts.WorkingDir, Record);
1097 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1099 // Header search options.
1101 const HeaderSearchOptions &HSOpts
1102 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1103 AddString(HSOpts.Sysroot, Record);
1106 Record.push_back(HSOpts.UserEntries.size());
1107 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1108 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1109 AddString(Entry.Path, Record);
1110 Record.push_back(static_cast<unsigned>(Entry.Group));
1111 Record.push_back(Entry.IsUserSupplied);
1112 Record.push_back(Entry.IsFramework);
1113 Record.push_back(Entry.IgnoreSysRoot);
1114 Record.push_back(Entry.IsInternal);
1115 Record.push_back(Entry.ImplicitExternC);
1118 // System header prefixes.
1119 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1120 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1121 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1122 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1125 AddString(HSOpts.ResourceDir, Record);
1126 AddString(HSOpts.ModuleCachePath, Record);
1127 Record.push_back(HSOpts.DisableModuleHash);
1128 Record.push_back(HSOpts.UseBuiltinIncludes);
1129 Record.push_back(HSOpts.UseStandardSystemIncludes);
1130 Record.push_back(HSOpts.UseStandardCXXIncludes);
1131 Record.push_back(HSOpts.UseLibcxx);
1132 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1134 // Preprocessor options.
1136 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1138 // Macro definitions.
1139 Record.push_back(PPOpts.Macros.size());
1140 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1141 AddString(PPOpts.Macros[I].first, Record);
1142 Record.push_back(PPOpts.Macros[I].second);
1146 Record.push_back(PPOpts.Includes.size());
1147 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1148 AddString(PPOpts.Includes[I], Record);
1151 Record.push_back(PPOpts.MacroIncludes.size());
1152 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1153 AddString(PPOpts.MacroIncludes[I], Record);
1155 Record.push_back(PPOpts.UsePredefines);
1156 AddString(PPOpts.ImplicitPCHInclude, Record);
1157 AddString(PPOpts.ImplicitPTHInclude, Record);
1158 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1159 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1161 // Original file name and file ID
1162 SourceManager &SM = Context.getSourceManager();
1163 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1164 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1165 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1166 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1167 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1168 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1170 SmallString<128> MainFilePath(MainFile->getName());
1172 llvm::sys::fs::make_absolute(MainFilePath);
1174 const char *MainFileNameStr = MainFilePath.c_str();
1175 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1178 Record.push_back(ORIGINAL_FILE);
1179 Record.push_back(SM.getMainFileID().getOpaqueValue());
1180 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1183 // Original PCH directory
1184 if (!OutputFile.empty() && OutputFile != "-") {
1185 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1186 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1187 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1188 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1190 SmallString<128> OutputPath(OutputFile);
1192 llvm::sys::fs::make_absolute(OutputPath);
1193 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1196 Record.push_back(ORIGINAL_PCH_DIR);
1197 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1200 WriteInputFiles(Context.SourceMgr, isysroot);
1204 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, StringRef isysroot) {
1205 using namespace llvm;
1206 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1209 // Create input-file abbreviation.
1210 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1211 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1212 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1213 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1214 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1215 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1216 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1217 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1219 // Write out all of the input files.
1220 std::vector<uint32_t> InputFileOffsets;
1221 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1222 // Get this source location entry.
1223 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1224 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1226 // We only care about file entries that were not overridden.
1227 if (!SLoc->isFile())
1229 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1230 if (!Cache->OrigEntry)
1233 // Record this entry's offset.
1234 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1235 InputFileIDs[Cache->OrigEntry] = InputFileOffsets.size();
1238 Record.push_back(INPUT_FILE);
1239 Record.push_back(InputFileOffsets.size());
1241 // Emit size/modification time for this file.
1242 Record.push_back(Cache->OrigEntry->getSize());
1243 Record.push_back(Cache->OrigEntry->getModificationTime());
1245 // Whether this file was overridden.
1246 Record.push_back(Cache->BufferOverridden);
1248 // Turn the file name into an absolute path, if it isn't already.
1249 const char *Filename = Cache->OrigEntry->getName();
1250 SmallString<128> FilePath(Filename);
1252 // Ask the file manager to fixup the relative path for us. This will
1253 // honor the working directory.
1254 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1256 // FIXME: This call to make_absolute shouldn't be necessary, the
1257 // call to FixupRelativePath should always return an absolute path.
1258 llvm::sys::fs::make_absolute(FilePath);
1259 Filename = FilePath.c_str();
1261 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1263 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1268 // Create input file offsets abbreviation.
1269 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1270 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1271 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1272 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1273 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1275 // Write input file offsets.
1277 Record.push_back(INPUT_FILE_OFFSETS);
1278 Record.push_back(InputFileOffsets.size());
1279 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
1282 //===----------------------------------------------------------------------===//
1283 // stat cache Serialization
1284 //===----------------------------------------------------------------------===//
1287 // Trait used for the on-disk hash table of stat cache results.
1288 class ASTStatCacheTrait {
1290 typedef const char * key_type;
1291 typedef key_type key_type_ref;
1293 typedef struct stat data_type;
1294 typedef const data_type &data_type_ref;
1296 static unsigned ComputeHash(const char *path) {
1297 return llvm::HashString(path);
1300 std::pair<unsigned,unsigned>
1301 EmitKeyDataLength(raw_ostream& Out, const char *path,
1302 data_type_ref Data) {
1303 unsigned StrLen = strlen(path);
1304 clang::io::Emit16(Out, StrLen);
1305 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1306 clang::io::Emit8(Out, DataLen);
1307 return std::make_pair(StrLen + 1, DataLen);
1310 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1311 Out.write(path, KeyLen);
1314 void EmitData(raw_ostream &Out, key_type_ref,
1315 data_type_ref Data, unsigned DataLen) {
1316 using namespace clang::io;
1317 uint64_t Start = Out.tell(); (void)Start;
1319 Emit32(Out, (uint32_t) Data.st_ino);
1320 Emit32(Out, (uint32_t) Data.st_dev);
1321 Emit16(Out, (uint16_t) Data.st_mode);
1322 Emit64(Out, (uint64_t) Data.st_mtime);
1323 Emit64(Out, (uint64_t) Data.st_size);
1325 assert(Out.tell() - Start == DataLen && "Wrong data length");
1328 } // end anonymous namespace
1330 //===----------------------------------------------------------------------===//
1331 // Source Manager Serialization
1332 //===----------------------------------------------------------------------===//
1334 /// \brief Create an abbreviation for the SLocEntry that refers to a
1336 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1337 using namespace llvm;
1338 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1339 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1340 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1341 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1344 // FileEntry fields.
1345 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1346 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1347 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1348 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1349 return Stream.EmitAbbrev(Abbrev);
1352 /// \brief Create an abbreviation for the SLocEntry that refers to a
1354 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1355 using namespace llvm;
1356 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1357 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1359 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1360 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1361 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1362 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1363 return Stream.EmitAbbrev(Abbrev);
1366 /// \brief Create an abbreviation for the SLocEntry that refers to a
1368 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1369 using namespace llvm;
1370 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1371 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1373 return Stream.EmitAbbrev(Abbrev);
1376 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1378 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1379 using namespace llvm;
1380 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1381 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1387 return Stream.EmitAbbrev(Abbrev);
1391 // Trait used for the on-disk hash table of header search information.
1392 class HeaderFileInfoTrait {
1395 // Keep track of the framework names we've used during serialization.
1396 SmallVector<char, 128> FrameworkStringData;
1397 llvm::StringMap<unsigned> FrameworkNameOffset;
1400 HeaderFileInfoTrait(ASTWriter &Writer)
1401 : Writer(Writer) { }
1403 typedef const char *key_type;
1404 typedef key_type key_type_ref;
1406 typedef HeaderFileInfo data_type;
1407 typedef const data_type &data_type_ref;
1409 static unsigned ComputeHash(const char *path) {
1410 // The hash is based only on the filename portion of the key, so that the
1411 // reader can match based on filenames when symlinking or excess path
1412 // elements ("foo/../", "../") change the form of the name. However,
1413 // complete path is still the key.
1414 return llvm::HashString(llvm::sys::path::filename(path));
1417 std::pair<unsigned,unsigned>
1418 EmitKeyDataLength(raw_ostream& Out, const char *path,
1419 data_type_ref Data) {
1420 unsigned StrLen = strlen(path);
1421 clang::io::Emit16(Out, StrLen);
1422 unsigned DataLen = 1 + 2 + 4 + 4;
1423 clang::io::Emit8(Out, DataLen);
1424 return std::make_pair(StrLen + 1, DataLen);
1427 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1428 Out.write(path, KeyLen);
1431 void EmitData(raw_ostream &Out, key_type_ref,
1432 data_type_ref Data, unsigned DataLen) {
1433 using namespace clang::io;
1434 uint64_t Start = Out.tell(); (void)Start;
1436 unsigned char Flags = (Data.isImport << 5)
1437 | (Data.isPragmaOnce << 4)
1438 | (Data.DirInfo << 2)
1439 | (Data.Resolved << 1)
1440 | Data.IndexHeaderMapHeader;
1441 Emit8(Out, (uint8_t)Flags);
1442 Emit16(Out, (uint16_t) Data.NumIncludes);
1444 if (!Data.ControllingMacro)
1445 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1447 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1449 unsigned Offset = 0;
1450 if (!Data.Framework.empty()) {
1451 // If this header refers into a framework, save the framework name.
1452 llvm::StringMap<unsigned>::iterator Pos
1453 = FrameworkNameOffset.find(Data.Framework);
1454 if (Pos == FrameworkNameOffset.end()) {
1455 Offset = FrameworkStringData.size() + 1;
1456 FrameworkStringData.append(Data.Framework.begin(),
1457 Data.Framework.end());
1458 FrameworkStringData.push_back(0);
1460 FrameworkNameOffset[Data.Framework] = Offset;
1462 Offset = Pos->second;
1464 Emit32(Out, Offset);
1466 assert(Out.tell() - Start == DataLen && "Wrong data length");
1469 const char *strings_begin() const { return FrameworkStringData.begin(); }
1470 const char *strings_end() const { return FrameworkStringData.end(); }
1472 } // end anonymous namespace
1474 /// \brief Write the header search block for the list of files that
1476 /// \param HS The header search structure to save.
1477 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1478 SmallVector<const FileEntry *, 16> FilesByUID;
1479 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1481 if (FilesByUID.size() > HS.header_file_size())
1482 FilesByUID.resize(HS.header_file_size());
1484 HeaderFileInfoTrait GeneratorTrait(*this);
1485 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1486 SmallVector<const char *, 4> SavedStrings;
1487 unsigned NumHeaderSearchEntries = 0;
1488 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1489 const FileEntry *File = FilesByUID[UID];
1493 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1494 // from the external source if it was not provided already.
1495 const HeaderFileInfo &HFI = HS.getFileInfo(File);
1496 if (HFI.External && Chain)
1499 // Turn the file name into an absolute path, if it isn't already.
1500 const char *Filename = File->getName();
1501 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1503 // If we performed any translation on the file name at all, we need to
1504 // save this string, since the generator will refer to it later.
1505 if (Filename != File->getName()) {
1506 Filename = strdup(Filename);
1507 SavedStrings.push_back(Filename);
1510 Generator.insert(Filename, HFI, GeneratorTrait);
1511 ++NumHeaderSearchEntries;
1514 // Create the on-disk hash table in a buffer.
1515 SmallString<4096> TableData;
1516 uint32_t BucketOffset;
1518 llvm::raw_svector_ostream Out(TableData);
1519 // Make sure that no bucket is at offset 0
1520 clang::io::Emit32(Out, 0);
1521 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1524 // Create a blob abbreviation
1525 using namespace llvm;
1526 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1527 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1532 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1534 // Write the header search table
1536 Record.push_back(HEADER_SEARCH_TABLE);
1537 Record.push_back(BucketOffset);
1538 Record.push_back(NumHeaderSearchEntries);
1539 Record.push_back(TableData.size());
1540 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1541 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1543 // Free all of the strings we had to duplicate.
1544 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1545 free((void*)SavedStrings[I]);
1548 /// \brief Writes the block containing the serialized form of the
1551 /// TODO: We should probably use an on-disk hash table (stored in a
1552 /// blob), indexed based on the file name, so that we only create
1553 /// entries for files that we actually need. In the common case (no
1554 /// errors), we probably won't have to create file entries for any of
1555 /// the files in the AST.
1556 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1557 const Preprocessor &PP,
1558 StringRef isysroot) {
1561 // Enter the source manager block.
1562 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1564 // Abbreviations for the various kinds of source-location entries.
1565 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1566 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1567 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1568 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1570 // Write out the source location entry table. We skip the first
1571 // entry, which is always the same dummy entry.
1572 std::vector<uint32_t> SLocEntryOffsets;
1573 RecordData PreloadSLocs;
1574 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1575 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1577 // Get this source location entry.
1578 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1579 FileID FID = FileID::get(I);
1580 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1582 // Record the offset of this source-location entry.
1583 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1585 // Figure out which record code to use.
1587 if (SLoc->isFile()) {
1588 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1589 if (Cache->OrigEntry) {
1590 Code = SM_SLOC_FILE_ENTRY;
1592 Code = SM_SLOC_BUFFER_ENTRY;
1594 Code = SM_SLOC_EXPANSION_ENTRY;
1596 Record.push_back(Code);
1598 // Starting offset of this entry within this module, so skip the dummy.
1599 Record.push_back(SLoc->getOffset() - 2);
1600 if (SLoc->isFile()) {
1601 const SrcMgr::FileInfo &File = SLoc->getFile();
1602 Record.push_back(File.getIncludeLoc().getRawEncoding());
1603 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1604 Record.push_back(File.hasLineDirectives());
1606 const SrcMgr::ContentCache *Content = File.getContentCache();
1607 if (Content->OrigEntry) {
1608 assert(Content->OrigEntry == Content->ContentsEntry &&
1609 "Writing to AST an overridden file is not supported");
1611 // The source location entry is a file. Emit input file ID.
1612 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1613 Record.push_back(InputFileIDs[Content->OrigEntry]);
1615 Record.push_back(File.NumCreatedFIDs);
1617 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1618 if (FDI != FileDeclIDs.end()) {
1619 Record.push_back(FDI->second->FirstDeclIndex);
1620 Record.push_back(FDI->second->DeclIDs.size());
1622 Record.push_back(0);
1623 Record.push_back(0);
1626 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1628 if (Content->BufferOverridden) {
1630 Record.push_back(SM_SLOC_BUFFER_BLOB);
1631 const llvm::MemoryBuffer *Buffer
1632 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1633 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1634 StringRef(Buffer->getBufferStart(),
1635 Buffer->getBufferSize() + 1));
1638 // The source location entry is a buffer. The blob associated
1639 // with this entry contains the contents of the buffer.
1641 // We add one to the size so that we capture the trailing NULL
1642 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1643 // the reader side).
1644 const llvm::MemoryBuffer *Buffer
1645 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1646 const char *Name = Buffer->getBufferIdentifier();
1647 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1648 StringRef(Name, strlen(Name) + 1));
1650 Record.push_back(SM_SLOC_BUFFER_BLOB);
1651 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1652 StringRef(Buffer->getBufferStart(),
1653 Buffer->getBufferSize() + 1));
1655 if (strcmp(Name, "<built-in>") == 0) {
1656 PreloadSLocs.push_back(SLocEntryOffsets.size());
1660 // The source location entry is a macro expansion.
1661 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1662 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1663 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1664 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1665 : Expansion.getExpansionLocEnd().getRawEncoding());
1667 // Compute the token length for this macro expansion.
1668 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1670 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1671 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1672 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1678 if (SLocEntryOffsets.empty())
1681 // Write the source-location offsets table into the AST block. This
1682 // table is used for lazily loading source-location information.
1683 using namespace llvm;
1684 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1685 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1689 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1692 Record.push_back(SOURCE_LOCATION_OFFSETS);
1693 Record.push_back(SLocEntryOffsets.size());
1694 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1695 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1697 // Write the source location entry preloads array, telling the AST
1698 // reader which source locations entries it should load eagerly.
1699 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1701 // Write the line table. It depends on remapping working, so it must come
1702 // after the source location offsets.
1703 if (SourceMgr.hasLineTable()) {
1704 LineTableInfo &LineTable = SourceMgr.getLineTable();
1707 // Emit the file names
1708 Record.push_back(LineTable.getNumFilenames());
1709 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1710 // Emit the file name
1711 const char *Filename = LineTable.getFilename(I);
1712 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1713 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1714 Record.push_back(FilenameLen);
1716 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1719 // Emit the line entries
1720 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1722 // Only emit entries for local files.
1723 if (L->first.ID < 0)
1727 Record.push_back(L->first.ID);
1729 // Emit the line entries
1730 Record.push_back(L->second.size());
1731 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1732 LEEnd = L->second.end();
1733 LE != LEEnd; ++LE) {
1734 Record.push_back(LE->FileOffset);
1735 Record.push_back(LE->LineNo);
1736 Record.push_back(LE->FilenameID);
1737 Record.push_back((unsigned)LE->FileKind);
1738 Record.push_back(LE->IncludeOffset);
1741 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1745 //===----------------------------------------------------------------------===//
1746 // Preprocessor Serialization
1747 //===----------------------------------------------------------------------===//
1749 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1750 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1751 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1752 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1753 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1754 return X.first->getName().compare(Y.first->getName());
1757 /// \brief Writes the block containing the serialized form of the
1760 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1761 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1763 WritePreprocessorDetail(*PPRec);
1767 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1768 if (PP.getCounterValue() != 0) {
1769 Record.push_back(PP.getCounterValue());
1770 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1774 // Enter the preprocessor block.
1775 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1777 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1778 // FIXME: use diagnostics subsystem for localization etc.
1779 if (PP.SawDateOrTime())
1780 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1783 // Loop over all the macro definitions that are live at the end of the file,
1784 // emitting each to the PP section.
1786 // Construct the list of macro definitions that need to be serialized.
1787 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1789 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1790 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1791 E = PP.macro_end(Chain == 0);
1793 if (!IsModule || I->second->isPublic()) {
1794 MacroDefinitionsSeen.insert(I->first);
1795 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1799 // Sort the set of macro definitions that need to be serialized by the
1800 // name of the macro, to provide a stable ordering.
1801 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1802 &compareMacroDefinitions);
1804 /// \brief Offsets of each of the macros into the bitstream, indexed by
1805 /// the local macro ID
1807 /// For each identifier that is associated with a macro, this map
1808 /// provides the offset into the bitstream where that macro is
1810 std::vector<uint32_t> MacroOffsets;
1812 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1813 const IdentifierInfo *Name = MacrosToEmit[I].first;
1815 for (MacroInfo *MI = MacrosToEmit[I].second; MI;
1816 MI = MI->getPreviousDefinition()) {
1817 MacroID ID = getMacroRef(MI);
1821 // Skip macros from a AST file if we're chaining.
1822 if (Chain && MI->isFromAST() && !MI->hasChangedAfterLoad())
1825 if (ID < FirstMacroID) {
1826 // This will have been dealt with via an update record.
1827 assert(MacroUpdates.count(MI) > 0 && "Missing macro update");
1831 // Record the local offset of this macro.
1832 unsigned Index = ID - FirstMacroID;
1833 if (Index == MacroOffsets.size())
1834 MacroOffsets.push_back(Stream.GetCurrentBitNo());
1836 if (Index > MacroOffsets.size())
1837 MacroOffsets.resize(Index + 1);
1839 MacroOffsets[Index] = Stream.GetCurrentBitNo();
1842 AddIdentifierRef(Name, Record);
1843 addMacroRef(MI, Record);
1844 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
1845 AddSourceLocation(MI->getDefinitionLoc(), Record);
1846 AddSourceLocation(MI->getUndefLoc(), Record);
1847 Record.push_back(MI->isUsed());
1848 Record.push_back(MI->isPublic());
1849 AddSourceLocation(MI->getVisibilityLocation(), Record);
1851 if (MI->isObjectLike()) {
1852 Code = PP_MACRO_OBJECT_LIKE;
1854 Code = PP_MACRO_FUNCTION_LIKE;
1856 Record.push_back(MI->isC99Varargs());
1857 Record.push_back(MI->isGNUVarargs());
1858 Record.push_back(MI->getNumArgs());
1859 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1861 AddIdentifierRef(*I, Record);
1864 // If we have a detailed preprocessing record, record the macro definition
1865 // ID that corresponds to this macro.
1867 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
1869 Stream.EmitRecord(Code, Record);
1872 // Emit the tokens array.
1873 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1874 // Note that we know that the preprocessor does not have any annotation
1875 // tokens in it because they are created by the parser, and thus can't
1876 // be in a macro definition.
1877 const Token &Tok = MI->getReplacementToken(TokNo);
1879 Record.push_back(Tok.getLocation().getRawEncoding());
1880 Record.push_back(Tok.getLength());
1882 // FIXME: When reading literal tokens, reconstruct the literal pointer
1884 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1885 // FIXME: Should translate token kind to a stable encoding.
1886 Record.push_back(Tok.getKind());
1887 // FIXME: Should translate token flags to a stable encoding.
1888 Record.push_back(Tok.getFlags());
1890 Stream.EmitRecord(PP_TOKEN, Record);
1898 // Write the offsets table for macro IDs.
1899 using namespace llvm;
1900 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1901 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
1902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
1903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
1904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1906 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1908 Record.push_back(MACRO_OFFSET);
1909 Record.push_back(MacroOffsets.size());
1910 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
1911 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
1912 data(MacroOffsets));
1915 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1916 if (PPRec.local_begin() == PPRec.local_end())
1919 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
1921 // Enter the preprocessor block.
1922 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1924 // If the preprocessor has a preprocessing record, emit it.
1925 unsigned NumPreprocessingRecords = 0;
1926 using namespace llvm;
1928 // Set up the abbreviation for
1929 unsigned InclusionAbbrev = 0;
1931 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1932 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1933 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1934 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1935 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1936 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
1937 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1938 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1941 unsigned FirstPreprocessorEntityID
1942 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
1943 + NUM_PREDEF_PP_ENTITY_IDS;
1944 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
1946 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
1947 EEnd = PPRec.local_end();
1949 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
1952 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
1953 Stream.GetCurrentBitNo()));
1955 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1956 // Record this macro definition's ID.
1957 MacroDefinitions[MD] = NextPreprocessorEntityID;
1959 AddIdentifierRef(MD->getName(), Record);
1960 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1964 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
1965 Record.push_back(ME->isBuiltinMacro());
1966 if (ME->isBuiltinMacro())
1967 AddIdentifierRef(ME->getName(), Record);
1969 Record.push_back(MacroDefinitions[ME->getDefinition()]);
1970 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
1974 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1975 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1976 Record.push_back(ID->getFileName().size());
1977 Record.push_back(ID->wasInQuotes());
1978 Record.push_back(static_cast<unsigned>(ID->getKind()));
1979 Record.push_back(ID->importedModule());
1980 SmallString<64> Buffer;
1981 Buffer += ID->getFileName();
1982 // Check that the FileEntry is not null because it was not resolved and
1983 // we create a PCH even with compiler errors.
1985 Buffer += ID->getFile()->getName();
1986 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1990 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1994 // Write the offsets table for the preprocessing record.
1995 if (NumPreprocessingRecords > 0) {
1996 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
1998 // Write the offsets table for identifier IDs.
1999 using namespace llvm;
2000 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2001 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2002 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2003 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2004 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2007 Record.push_back(PPD_ENTITIES_OFFSETS);
2008 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2009 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2010 data(PreprocessedEntityOffsets));
2014 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2015 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2016 if (Known != SubmoduleIDs.end())
2017 return Known->second;
2019 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2022 /// \brief Compute the number of modules within the given tree (including the
2024 static unsigned getNumberOfModules(Module *Mod) {
2025 unsigned ChildModules = 0;
2026 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2027 SubEnd = Mod->submodule_end();
2028 Sub != SubEnd; ++Sub)
2029 ChildModules += getNumberOfModules(*Sub);
2031 return ChildModules + 1;
2034 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2035 // Determine the dependencies of our module and each of it's submodules.
2036 // FIXME: This feels like it belongs somewhere else, but there are no
2037 // other consumers of this information.
2038 SourceManager &SrcMgr = PP->getSourceManager();
2039 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2040 for (ASTContext::import_iterator I = Context->local_import_begin(),
2041 IEnd = Context->local_import_end();
2043 if (Module *ImportedFrom
2044 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2046 ImportedFrom->Imports.push_back(I->getImportedModule());
2050 // Enter the submodule description block.
2051 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2053 // Write the abbreviations needed for the submodules block.
2054 using namespace llvm;
2055 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2056 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2057 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2058 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2059 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2060 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2061 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2062 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2063 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2064 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2065 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2066 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2068 Abbrev = new BitCodeAbbrev();
2069 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2070 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2071 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2073 Abbrev = new BitCodeAbbrev();
2074 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2075 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2076 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2078 Abbrev = new BitCodeAbbrev();
2079 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2080 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2081 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2083 Abbrev = new BitCodeAbbrev();
2084 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2086 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2088 Abbrev = new BitCodeAbbrev();
2089 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2090 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2091 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2093 Abbrev = new BitCodeAbbrev();
2094 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2095 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2096 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2098 // Write the submodule metadata block.
2100 Record.push_back(getNumberOfModules(WritingModule));
2101 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2102 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2104 // Write all of the submodules.
2105 std::queue<Module *> Q;
2106 Q.push(WritingModule);
2107 while (!Q.empty()) {
2108 Module *Mod = Q.front();
2110 unsigned ID = getSubmoduleID(Mod);
2112 // Emit the definition of the block.
2114 Record.push_back(SUBMODULE_DEFINITION);
2115 Record.push_back(ID);
2117 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2118 Record.push_back(SubmoduleIDs[Mod->Parent]);
2120 Record.push_back(0);
2122 Record.push_back(Mod->IsFramework);
2123 Record.push_back(Mod->IsExplicit);
2124 Record.push_back(Mod->IsSystem);
2125 Record.push_back(Mod->InferSubmodules);
2126 Record.push_back(Mod->InferExplicitSubmodules);
2127 Record.push_back(Mod->InferExportWildcard);
2128 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2130 // Emit the requirements.
2131 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
2133 Record.push_back(SUBMODULE_REQUIRES);
2134 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2135 Mod->Requires[I].data(),
2136 Mod->Requires[I].size());
2139 // Emit the umbrella header, if there is one.
2140 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
2142 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2143 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2144 UmbrellaHeader->getName());
2145 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2147 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2148 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2149 UmbrellaDir->getName());
2152 // Emit the headers.
2153 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
2155 Record.push_back(SUBMODULE_HEADER);
2156 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2157 Mod->Headers[I]->getName());
2159 // Emit the excluded headers.
2160 for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2162 Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2163 Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2164 Mod->ExcludedHeaders[I]->getName());
2166 for (unsigned I = 0, N = Mod->TopHeaders.size(); I != N; ++I) {
2168 Record.push_back(SUBMODULE_TOPHEADER);
2169 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
2170 Mod->TopHeaders[I]->getName());
2173 // Emit the imports.
2174 if (!Mod->Imports.empty()) {
2176 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2177 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2178 assert(ImportedID && "Unknown submodule!");
2179 Record.push_back(ImportedID);
2181 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2184 // Emit the exports.
2185 if (!Mod->Exports.empty()) {
2187 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2188 if (Module *Exported = Mod->Exports[I].getPointer()) {
2189 unsigned ExportedID = SubmoduleIDs[Exported];
2190 assert(ExportedID > 0 && "Unknown submodule ID?");
2191 Record.push_back(ExportedID);
2193 Record.push_back(0);
2196 Record.push_back(Mod->Exports[I].getInt());
2198 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2201 // Queue up the submodules of this module.
2202 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2203 SubEnd = Mod->submodule_end();
2204 Sub != SubEnd; ++Sub)
2210 assert((NextSubmoduleID - FirstSubmoduleID
2211 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2214 serialization::SubmoduleID
2215 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2216 if (Loc.isInvalid() || !WritingModule)
2217 return 0; // No submodule
2219 // Find the module that owns this location.
2220 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2222 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2226 // Check whether this submodule is part of our own module.
2227 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2230 return getSubmoduleID(OwningMod);
2233 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) {
2234 // FIXME: Make it work properly with modules.
2235 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2237 unsigned CurrID = 0;
2238 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2240 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2241 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2243 const DiagnosticsEngine::DiagStatePoint &point = *I;
2244 if (point.Loc.isInvalid())
2247 Record.push_back(point.Loc.getRawEncoding());
2248 unsigned &DiagStateID = DiagStateIDMap[point.State];
2249 Record.push_back(DiagStateID);
2251 if (DiagStateID == 0) {
2252 DiagStateID = ++CurrID;
2253 for (DiagnosticsEngine::DiagState::const_iterator
2254 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2255 if (I->second.isPragma()) {
2256 Record.push_back(I->first);
2257 Record.push_back(I->second.getMapping());
2260 Record.push_back(-1); // mark the end of the diag/map pairs for this
2265 if (!Record.empty())
2266 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2269 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2270 if (CXXBaseSpecifiersOffsets.empty())
2275 // Create a blob abbreviation for the C++ base specifiers offsets.
2276 using namespace llvm;
2278 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2279 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2280 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2281 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2282 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2284 // Write the base specifier offsets table.
2286 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2287 Record.push_back(CXXBaseSpecifiersOffsets.size());
2288 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2289 data(CXXBaseSpecifiersOffsets));
2292 //===----------------------------------------------------------------------===//
2293 // Type Serialization
2294 //===----------------------------------------------------------------------===//
2296 /// \brief Write the representation of a type to the AST stream.
2297 void ASTWriter::WriteType(QualType T) {
2298 TypeIdx &Idx = TypeIdxs[T];
2299 if (Idx.getIndex() == 0) // we haven't seen this type before.
2300 Idx = TypeIdx(NextTypeID++);
2302 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2304 // Record the offset for this type.
2305 unsigned Index = Idx.getIndex() - FirstTypeID;
2306 if (TypeOffsets.size() == Index)
2307 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2308 else if (TypeOffsets.size() < Index) {
2309 TypeOffsets.resize(Index + 1);
2310 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2315 // Emit the type's representation.
2316 ASTTypeWriter W(*this, Record);
2318 if (T.hasLocalNonFastQualifiers()) {
2319 Qualifiers Qs = T.getLocalQualifiers();
2320 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2321 Record.push_back(Qs.getAsOpaqueValue());
2322 W.Code = TYPE_EXT_QUAL;
2324 switch (T->getTypeClass()) {
2325 // For all of the concrete, non-dependent types, call the
2326 // appropriate visitor function.
2327 #define TYPE(Class, Base) \
2328 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2329 #define ABSTRACT_TYPE(Class, Base)
2330 #include "clang/AST/TypeNodes.def"
2334 // Emit the serialized record.
2335 Stream.EmitRecord(W.Code, Record);
2337 // Flush any expressions that were written as part of this type.
2341 //===----------------------------------------------------------------------===//
2342 // Declaration Serialization
2343 //===----------------------------------------------------------------------===//
2345 /// \brief Write the block containing all of the declaration IDs
2346 /// lexically declared within the given DeclContext.
2348 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2349 /// bistream, or 0 if no block was written.
2350 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2352 if (DC->decls_empty())
2355 uint64_t Offset = Stream.GetCurrentBitNo();
2357 Record.push_back(DECL_CONTEXT_LEXICAL);
2358 SmallVector<KindDeclIDPair, 64> Decls;
2359 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2361 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2363 ++NumLexicalDeclContexts;
2364 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2368 void ASTWriter::WriteTypeDeclOffsets() {
2369 using namespace llvm;
2372 // Write the type offsets array
2373 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2374 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2375 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2376 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2377 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2378 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2380 Record.push_back(TYPE_OFFSET);
2381 Record.push_back(TypeOffsets.size());
2382 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2383 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2385 // Write the declaration offsets array
2386 Abbrev = new BitCodeAbbrev();
2387 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2388 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2390 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2391 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2393 Record.push_back(DECL_OFFSET);
2394 Record.push_back(DeclOffsets.size());
2395 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2396 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2399 void ASTWriter::WriteFileDeclIDsMap() {
2400 using namespace llvm;
2403 // Join the vectors of DeclIDs from all files.
2404 SmallVector<DeclID, 256> FileSortedIDs;
2405 for (FileDeclIDsTy::iterator
2406 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2407 DeclIDInFileInfo &Info = *FI->second;
2408 Info.FirstDeclIndex = FileSortedIDs.size();
2409 for (LocDeclIDsTy::iterator
2410 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2411 FileSortedIDs.push_back(DI->second);
2414 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2415 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2416 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2417 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2418 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2419 Record.push_back(FILE_SORTED_DECLS);
2420 Record.push_back(FileSortedIDs.size());
2421 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2424 void ASTWriter::WriteComments() {
2425 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2426 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2428 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2429 E = RawComments.end();
2432 AddSourceRange((*I)->getSourceRange(), Record);
2433 Record.push_back((*I)->getKind());
2434 Record.push_back((*I)->isTrailingComment());
2435 Record.push_back((*I)->isAlmostTrailingComment());
2436 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2441 //===----------------------------------------------------------------------===//
2442 // Global Method Pool and Selector Serialization
2443 //===----------------------------------------------------------------------===//
2446 // Trait used for the on-disk hash table used in the method pool.
2447 class ASTMethodPoolTrait {
2451 typedef Selector key_type;
2452 typedef key_type key_type_ref;
2456 ObjCMethodList Instance, Factory;
2458 typedef const data_type& data_type_ref;
2460 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2462 static unsigned ComputeHash(Selector Sel) {
2463 return serialization::ComputeHash(Sel);
2466 std::pair<unsigned,unsigned>
2467 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2468 data_type_ref Methods) {
2469 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2470 clang::io::Emit16(Out, KeyLen);
2471 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2472 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2473 Method = Method->Next)
2476 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2477 Method = Method->Next)
2480 clang::io::Emit16(Out, DataLen);
2481 return std::make_pair(KeyLen, DataLen);
2484 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2485 uint64_t Start = Out.tell();
2486 assert((Start >> 32) == 0 && "Selector key offset too large");
2487 Writer.SetSelectorOffset(Sel, Start);
2488 unsigned N = Sel.getNumArgs();
2489 clang::io::Emit16(Out, N);
2492 for (unsigned I = 0; I != N; ++I)
2493 clang::io::Emit32(Out,
2494 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2497 void EmitData(raw_ostream& Out, key_type_ref,
2498 data_type_ref Methods, unsigned DataLen) {
2499 uint64_t Start = Out.tell(); (void)Start;
2500 clang::io::Emit32(Out, Methods.ID);
2501 unsigned NumInstanceMethods = 0;
2502 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2503 Method = Method->Next)
2505 ++NumInstanceMethods;
2507 unsigned NumFactoryMethods = 0;
2508 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2509 Method = Method->Next)
2511 ++NumFactoryMethods;
2513 clang::io::Emit16(Out, NumInstanceMethods);
2514 clang::io::Emit16(Out, NumFactoryMethods);
2515 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2516 Method = Method->Next)
2518 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2519 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2520 Method = Method->Next)
2522 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2524 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2527 } // end anonymous namespace
2529 /// \brief Write ObjC data: selectors and the method pool.
2531 /// The method pool contains both instance and factory methods, stored
2532 /// in an on-disk hash table indexed by the selector. The hash table also
2533 /// contains an empty entry for every other selector known to Sema.
2534 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2535 using namespace llvm;
2537 // Do we have to do anything at all?
2538 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2540 unsigned NumTableEntries = 0;
2541 // Create and write out the blob that contains selectors and the method pool.
2543 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2544 ASTMethodPoolTrait Trait(*this);
2546 // Create the on-disk hash table representation. We walk through every
2547 // selector we've seen and look it up in the method pool.
2548 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2549 for (llvm::DenseMap<Selector, SelectorID>::iterator
2550 I = SelectorIDs.begin(), E = SelectorIDs.end();
2552 Selector S = I->first;
2553 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2554 ASTMethodPoolTrait::data_type Data = {
2559 if (F != SemaRef.MethodPool.end()) {
2560 Data.Instance = F->second.first;
2561 Data.Factory = F->second.second;
2563 // Only write this selector if it's not in an existing AST or something
2565 if (Chain && I->second < FirstSelectorID) {
2566 // Selector already exists. Did it change?
2567 bool changed = false;
2568 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2570 if (!M->Method->isFromASTFile())
2573 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2575 if (!M->Method->isFromASTFile())
2580 } else if (Data.Instance.Method || Data.Factory.Method) {
2581 // A new method pool entry.
2584 Generator.insert(S, Data, Trait);
2587 // Create the on-disk hash table in a buffer.
2588 SmallString<4096> MethodPool;
2589 uint32_t BucketOffset;
2591 ASTMethodPoolTrait Trait(*this);
2592 llvm::raw_svector_ostream Out(MethodPool);
2593 // Make sure that no bucket is at offset 0
2594 clang::io::Emit32(Out, 0);
2595 BucketOffset = Generator.Emit(Out, Trait);
2598 // Create a blob abbreviation
2599 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2600 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2602 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2603 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2604 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2606 // Write the method pool
2608 Record.push_back(METHOD_POOL);
2609 Record.push_back(BucketOffset);
2610 Record.push_back(NumTableEntries);
2611 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2613 // Create a blob abbreviation for the selector table offsets.
2614 Abbrev = new BitCodeAbbrev();
2615 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2617 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2618 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2619 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2621 // Write the selector offsets table.
2623 Record.push_back(SELECTOR_OFFSETS);
2624 Record.push_back(SelectorOffsets.size());
2625 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2626 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2627 data(SelectorOffsets));
2631 /// \brief Write the selectors referenced in @selector expression into AST file.
2632 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2633 using namespace llvm;
2634 if (SemaRef.ReferencedSelectors.empty())
2639 // Note: this writes out all references even for a dependent AST. But it is
2640 // very tricky to fix, and given that @selector shouldn't really appear in
2641 // headers, probably not worth it. It's not a correctness issue.
2642 for (DenseMap<Selector, SourceLocation>::iterator S =
2643 SemaRef.ReferencedSelectors.begin(),
2644 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2645 Selector Sel = (*S).first;
2646 SourceLocation Loc = (*S).second;
2647 AddSelectorRef(Sel, Record);
2648 AddSourceLocation(Loc, Record);
2650 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2653 //===----------------------------------------------------------------------===//
2654 // Identifier Table Serialization
2655 //===----------------------------------------------------------------------===//
2658 class ASTIdentifierTableTrait {
2661 IdentifierResolver &IdResolver;
2664 /// \brief Determines whether this is an "interesting" identifier
2665 /// that needs a full IdentifierInfo structure written into the hash
2667 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) {
2668 if (II->isPoisoned() ||
2669 II->isExtensionToken() ||
2670 II->getObjCOrBuiltinID() ||
2671 II->hasRevertedTokenIDToIdentifier() ||
2672 II->getFETokenInfo<void>())
2675 return hadMacroDefinition(II, Macro);
2678 bool hadMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) {
2679 if (!II->hadMacroDefinition())
2682 if (Macro || (Macro = PP.getMacroInfoHistory(II)))
2683 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
2689 typedef IdentifierInfo* key_type;
2690 typedef key_type key_type_ref;
2692 typedef IdentID data_type;
2693 typedef data_type data_type_ref;
2695 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
2696 IdentifierResolver &IdResolver, bool IsModule)
2697 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
2699 static unsigned ComputeHash(const IdentifierInfo* II) {
2700 return llvm::HashString(II->getName());
2703 std::pair<unsigned,unsigned>
2704 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
2705 unsigned KeyLen = II->getLength() + 1;
2706 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2707 MacroInfo *Macro = 0;
2708 if (isInterestingIdentifier(II, Macro)) {
2709 DataLen += 2; // 2 bytes for builtin ID
2710 DataLen += 2; // 2 bytes for flags
2711 if (hadMacroDefinition(II, Macro)) {
2712 for (MacroInfo *M = Macro; M; M = M->getPreviousDefinition()) {
2713 if (Writer.getMacroRef(M) != 0)
2720 for (IdentifierResolver::iterator D = IdResolver.begin(II),
2721 DEnd = IdResolver.end();
2723 DataLen += sizeof(DeclID);
2725 clang::io::Emit16(Out, DataLen);
2726 // We emit the key length after the data length so that every
2727 // string is preceded by a 16-bit length. This matches the PTH
2728 // format for storing identifiers.
2729 clang::io::Emit16(Out, KeyLen);
2730 return std::make_pair(KeyLen, DataLen);
2733 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
2735 // Record the location of the key data. This is used when generating
2736 // the mapping from persistent IDs to strings.
2737 Writer.SetIdentifierOffset(II, Out.tell());
2738 Out.write(II->getNameStart(), KeyLen);
2741 void EmitData(raw_ostream& Out, IdentifierInfo* II,
2742 IdentID ID, unsigned) {
2743 MacroInfo *Macro = 0;
2744 if (!isInterestingIdentifier(II, Macro)) {
2745 clang::io::Emit32(Out, ID << 1);
2749 clang::io::Emit32(Out, (ID << 1) | 0x01);
2750 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
2751 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
2752 clang::io::Emit16(Out, Bits);
2754 bool HadMacroDefinition = hadMacroDefinition(II, Macro);
2755 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
2756 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2757 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2758 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2759 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2760 clang::io::Emit16(Out, Bits);
2762 if (HadMacroDefinition) {
2763 // Write all of the macro IDs associated with this identifier.
2764 for (MacroInfo *M = Macro; M; M = M->getPreviousDefinition()) {
2765 if (MacroID ID = Writer.getMacroRef(M))
2766 clang::io::Emit32(Out, ID);
2769 clang::io::Emit32(Out, 0);
2772 // Emit the declaration IDs in reverse order, because the
2773 // IdentifierResolver provides the declarations as they would be
2774 // visible (e.g., the function "stat" would come before the struct
2775 // "stat"), but the ASTReader adds declarations to the end of the list
2776 // (so we need to see the struct "status" before the function "status").
2777 // Only emit declarations that aren't from a chained PCH, though.
2778 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
2780 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2781 DEnd = Decls.rend();
2783 clang::io::Emit32(Out, Writer.getDeclID(*D));
2786 } // end anonymous namespace
2788 /// \brief Write the identifier table into the AST file.
2790 /// The identifier table consists of a blob containing string data
2791 /// (the actual identifiers themselves) and a separate "offsets" index
2792 /// that maps identifier IDs to locations within the blob.
2793 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
2794 IdentifierResolver &IdResolver,
2796 using namespace llvm;
2798 // Create and write out the blob that contains the identifier
2801 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2802 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2804 // Look for any identifiers that were named while processing the
2805 // headers, but are otherwise not needed. We add these to the hash
2806 // table to enable checking of the predefines buffer in the case
2807 // where the user adds new macro definitions when building the AST
2809 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2810 IDEnd = PP.getIdentifierTable().end();
2812 getIdentifierRef(ID->second);
2814 // Create the on-disk hash table representation. We only store offsets
2815 // for identifiers that appear here for the first time.
2816 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2817 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2818 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2819 ID != IDEnd; ++ID) {
2820 assert(ID->first && "NULL identifier in identifier table");
2821 if (!Chain || !ID->first->isFromAST() ||
2822 ID->first->hasChangedSinceDeserialization())
2823 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
2827 // Create the on-disk hash table in a buffer.
2828 SmallString<4096> IdentifierTable;
2829 uint32_t BucketOffset;
2831 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2832 llvm::raw_svector_ostream Out(IdentifierTable);
2833 // Make sure that no bucket is at offset 0
2834 clang::io::Emit32(Out, 0);
2835 BucketOffset = Generator.Emit(Out, Trait);
2838 // Create a blob abbreviation
2839 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2840 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2843 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2845 // Write the identifier table
2847 Record.push_back(IDENTIFIER_TABLE);
2848 Record.push_back(BucketOffset);
2849 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2852 // Write the offsets table for identifier IDs.
2853 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2854 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2856 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2858 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2861 Record.push_back(IDENTIFIER_OFFSET);
2862 Record.push_back(IdentifierOffsets.size());
2863 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
2864 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2865 data(IdentifierOffsets));
2868 //===----------------------------------------------------------------------===//
2869 // DeclContext's Name Lookup Table Serialization
2870 //===----------------------------------------------------------------------===//
2873 // Trait used for the on-disk hash table used in the method pool.
2874 class ASTDeclContextNameLookupTrait {
2878 typedef DeclarationName key_type;
2879 typedef key_type key_type_ref;
2881 typedef DeclContext::lookup_result data_type;
2882 typedef const data_type& data_type_ref;
2884 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2886 unsigned ComputeHash(DeclarationName Name) {
2887 llvm::FoldingSetNodeID ID;
2888 ID.AddInteger(Name.getNameKind());
2890 switch (Name.getNameKind()) {
2891 case DeclarationName::Identifier:
2892 ID.AddString(Name.getAsIdentifierInfo()->getName());
2894 case DeclarationName::ObjCZeroArgSelector:
2895 case DeclarationName::ObjCOneArgSelector:
2896 case DeclarationName::ObjCMultiArgSelector:
2897 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2899 case DeclarationName::CXXConstructorName:
2900 case DeclarationName::CXXDestructorName:
2901 case DeclarationName::CXXConversionFunctionName:
2903 case DeclarationName::CXXOperatorName:
2904 ID.AddInteger(Name.getCXXOverloadedOperator());
2906 case DeclarationName::CXXLiteralOperatorName:
2907 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2908 case DeclarationName::CXXUsingDirective:
2912 return ID.ComputeHash();
2915 std::pair<unsigned,unsigned>
2916 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
2917 data_type_ref Lookup) {
2918 unsigned KeyLen = 1;
2919 switch (Name.getNameKind()) {
2920 case DeclarationName::Identifier:
2921 case DeclarationName::ObjCZeroArgSelector:
2922 case DeclarationName::ObjCOneArgSelector:
2923 case DeclarationName::ObjCMultiArgSelector:
2924 case DeclarationName::CXXLiteralOperatorName:
2927 case DeclarationName::CXXOperatorName:
2930 case DeclarationName::CXXConstructorName:
2931 case DeclarationName::CXXDestructorName:
2932 case DeclarationName::CXXConversionFunctionName:
2933 case DeclarationName::CXXUsingDirective:
2936 clang::io::Emit16(Out, KeyLen);
2938 // 2 bytes for num of decls and 4 for each DeclID.
2939 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2940 clang::io::Emit16(Out, DataLen);
2942 return std::make_pair(KeyLen, DataLen);
2945 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
2946 using namespace clang::io;
2948 Emit8(Out, Name.getNameKind());
2949 switch (Name.getNameKind()) {
2950 case DeclarationName::Identifier:
2951 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2953 case DeclarationName::ObjCZeroArgSelector:
2954 case DeclarationName::ObjCOneArgSelector:
2955 case DeclarationName::ObjCMultiArgSelector:
2956 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2958 case DeclarationName::CXXOperatorName:
2959 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
2960 "Invalid operator?");
2961 Emit8(Out, Name.getCXXOverloadedOperator());
2963 case DeclarationName::CXXLiteralOperatorName:
2964 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2966 case DeclarationName::CXXConstructorName:
2967 case DeclarationName::CXXDestructorName:
2968 case DeclarationName::CXXConversionFunctionName:
2969 case DeclarationName::CXXUsingDirective:
2973 llvm_unreachable("Invalid name kind?");
2976 void EmitData(raw_ostream& Out, key_type_ref,
2977 data_type Lookup, unsigned DataLen) {
2978 uint64_t Start = Out.tell(); (void)Start;
2979 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2980 for (; Lookup.first != Lookup.second; ++Lookup.first)
2981 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2983 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2986 } // end anonymous namespace
2988 /// \brief Write the block containing all of the declaration IDs
2989 /// visible from the given DeclContext.
2991 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2992 /// bitstream, or 0 if no block was written.
2993 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2995 if (DC->getPrimaryContext() != DC)
2998 // Since there is no name lookup into functions or methods, don't bother to
2999 // build a visible-declarations table for these entities.
3000 if (DC->isFunctionOrMethod())
3003 // If not in C++, we perform name lookup for the translation unit via the
3004 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3005 // FIXME: In C++ we need the visible declarations in order to "see" the
3006 // friend declarations, is there a way to do this without writing the table ?
3007 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3010 // Serialize the contents of the mapping used for lookup. Note that,
3011 // although we have two very different code paths, the serialized
3012 // representation is the same for both cases: a declaration name,
3013 // followed by a size, followed by references to the visible
3014 // declarations that have that name.
3015 uint64_t Offset = Stream.GetCurrentBitNo();
3016 StoredDeclsMap *Map = DC->buildLookup();
3017 if (!Map || Map->empty())
3020 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3021 ASTDeclContextNameLookupTrait Trait(*this);
3023 // Create the on-disk hash table representation.
3024 DeclarationName ConversionName;
3025 llvm::SmallVector<NamedDecl *, 4> ConversionDecls;
3026 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3028 DeclarationName Name = D->first;
3029 DeclContext::lookup_result Result = D->second.getLookupResult();
3030 if (Result.first != Result.second) {
3031 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3032 // Hash all conversion function names to the same name. The actual
3033 // type information in conversion function name is not used in the
3034 // key (since such type information is not stable across different
3035 // modules), so the intended effect is to coalesce all of the conversion
3036 // functions under a single key.
3037 if (!ConversionName)
3038 ConversionName = Name;
3039 ConversionDecls.append(Result.first, Result.second);
3043 Generator.insert(Name, Result, Trait);
3047 // Add the conversion functions
3048 if (!ConversionDecls.empty()) {
3049 Generator.insert(ConversionName,
3050 DeclContext::lookup_result(ConversionDecls.begin(),
3051 ConversionDecls.end()),
3055 // Create the on-disk hash table in a buffer.
3056 SmallString<4096> LookupTable;
3057 uint32_t BucketOffset;
3059 llvm::raw_svector_ostream Out(LookupTable);
3060 // Make sure that no bucket is at offset 0
3061 clang::io::Emit32(Out, 0);
3062 BucketOffset = Generator.Emit(Out, Trait);
3065 // Write the lookup table
3067 Record.push_back(DECL_CONTEXT_VISIBLE);
3068 Record.push_back(BucketOffset);
3069 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3072 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
3073 ++NumVisibleDeclContexts;
3077 /// \brief Write an UPDATE_VISIBLE block for the given context.
3079 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3080 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3081 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3082 /// enumeration members (in C++11).
3083 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3084 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
3085 if (!Map || Map->empty())
3088 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3089 ASTDeclContextNameLookupTrait Trait(*this);
3091 // Create the hash table.
3092 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3094 DeclarationName Name = D->first;
3095 DeclContext::lookup_result Result = D->second.getLookupResult();
3096 // For any name that appears in this table, the results are complete, i.e.
3097 // they overwrite results from previous PCHs. Merging is always a mess.
3098 if (Result.first != Result.second)
3099 Generator.insert(Name, Result, Trait);
3102 // Create the on-disk hash table in a buffer.
3103 SmallString<4096> LookupTable;
3104 uint32_t BucketOffset;
3106 llvm::raw_svector_ostream Out(LookupTable);
3107 // Make sure that no bucket is at offset 0
3108 clang::io::Emit32(Out, 0);
3109 BucketOffset = Generator.Emit(Out, Trait);
3112 // Write the lookup table
3114 Record.push_back(UPDATE_VISIBLE);
3115 Record.push_back(getDeclID(cast<Decl>(DC)));
3116 Record.push_back(BucketOffset);
3117 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3120 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3121 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3123 Record.push_back(Opts.fp_contract);
3124 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3127 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3128 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3129 if (!SemaRef.Context.getLangOpts().OpenCL)
3132 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3134 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3135 #include "clang/Basic/OpenCLExtensions.def"
3136 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3139 void ASTWriter::WriteRedeclarations() {
3140 RecordData LocalRedeclChains;
3141 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3143 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3144 Decl *First = Redeclarations[I];
3145 assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
3147 Decl *MostRecent = First->getMostRecentDecl();
3149 // If we only have a single declaration, there is no point in storing
3150 // a redeclaration chain.
3151 if (First == MostRecent)
3154 unsigned Offset = LocalRedeclChains.size();
3156 LocalRedeclChains.push_back(0); // Placeholder for the size.
3158 // Collect the set of local redeclarations of this declaration.
3159 for (Decl *Prev = MostRecent; Prev != First;
3160 Prev = Prev->getPreviousDecl()) {
3161 if (!Prev->isFromASTFile()) {
3162 AddDeclRef(Prev, LocalRedeclChains);
3166 LocalRedeclChains[Offset] = Size;
3168 // Reverse the set of local redeclarations, so that we store them in
3169 // order (since we found them in reverse order).
3170 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3172 // Add the mapping from the first ID to the set of local declarations.
3173 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3174 LocalRedeclsMap.push_back(Info);
3176 assert(N == Redeclarations.size() &&
3177 "Deserialized a declaration we shouldn't have");
3180 if (LocalRedeclChains.empty())
3183 // Sort the local redeclarations map by the first declaration ID,
3184 // since the reader will be performing binary searches on this information.
3185 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3187 // Emit the local redeclarations map.
3188 using namespace llvm;
3189 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3190 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3192 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3193 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3196 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3197 Record.push_back(LocalRedeclsMap.size());
3198 Stream.EmitRecordWithBlob(AbbrevID, Record,
3199 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3200 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3202 // Emit the redeclaration chains.
3203 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3206 void ASTWriter::WriteObjCCategories() {
3207 llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3208 RecordData Categories;
3210 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3212 unsigned StartIndex = Categories.size();
3214 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3216 // Allocate space for the size.
3217 Categories.push_back(0);
3219 // Add the categories.
3220 for (ObjCCategoryDecl *Cat = Class->getCategoryList();
3221 Cat; Cat = Cat->getNextClassCategory(), ++Size) {
3222 assert(getDeclID(Cat) != 0 && "Bogus category");
3223 AddDeclRef(Cat, Categories);
3227 Categories[StartIndex] = Size;
3229 // Record this interface -> category map.
3230 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3231 CategoriesMap.push_back(CatInfo);
3234 // Sort the categories map by the definition ID, since the reader will be
3235 // performing binary searches on this information.
3236 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3238 // Emit the categories map.
3239 using namespace llvm;
3240 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3241 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3243 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3244 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3247 Record.push_back(OBJC_CATEGORIES_MAP);
3248 Record.push_back(CategoriesMap.size());
3249 Stream.EmitRecordWithBlob(AbbrevID, Record,
3250 reinterpret_cast<char*>(CategoriesMap.data()),
3251 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3253 // Emit the category lists.
3254 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3257 void ASTWriter::WriteMergedDecls() {
3258 if (!Chain || Chain->MergedDecls.empty())
3262 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3263 IEnd = Chain->MergedDecls.end();
3265 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3266 : getDeclID(I->first);
3267 assert(CanonID && "Merged declaration not known?");
3269 Record.push_back(CanonID);
3270 Record.push_back(I->second.size());
3271 Record.append(I->second.begin(), I->second.end());
3273 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3276 //===----------------------------------------------------------------------===//
3277 // General Serialization Routines
3278 //===----------------------------------------------------------------------===//
3280 /// \brief Write a record containing the given attributes.
3281 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3282 RecordDataImpl &Record) {
3283 Record.push_back(Attrs.size());
3284 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3285 e = Attrs.end(); i != e; ++i){
3287 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3288 AddSourceRange(A->getRange(), Record);
3290 #include "clang/Serialization/AttrPCHWrite.inc"
3295 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3296 Record.push_back(Str.size());
3297 Record.insert(Record.end(), Str.begin(), Str.end());
3300 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3301 RecordDataImpl &Record) {
3302 Record.push_back(Version.getMajor());
3303 if (llvm::Optional<unsigned> Minor = Version.getMinor())
3304 Record.push_back(*Minor + 1);
3306 Record.push_back(0);
3307 if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
3308 Record.push_back(*Subminor + 1);
3310 Record.push_back(0);
3313 /// \brief Note that the identifier II occurs at the given offset
3314 /// within the identifier table.
3315 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3316 IdentID ID = IdentifierIDs[II];
3317 // Only store offsets new to this AST file. Other identifier names are looked
3318 // up earlier in the chain and thus don't need an offset.
3319 if (ID >= FirstIdentID)
3320 IdentifierOffsets[ID - FirstIdentID] = Offset;
3323 /// \brief Note that the selector Sel occurs at the given offset
3324 /// within the method pool/selector table.
3325 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3326 unsigned ID = SelectorIDs[Sel];
3327 assert(ID && "Unknown selector");
3328 // Don't record offsets for selectors that are also available in a different
3330 if (ID < FirstSelectorID)
3332 SelectorOffsets[ID - FirstSelectorID] = Offset;
3335 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3336 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
3337 WritingAST(false), DoneWritingDeclsAndTypes(false),
3338 ASTHasCompilerErrors(false),
3339 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3340 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3341 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3342 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3343 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3344 NextSubmoduleID(FirstSubmoduleID),
3345 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3346 CollectedStmts(&StmtsToEmit),
3347 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
3348 NumVisibleDeclContexts(0),
3349 NextCXXBaseSpecifiersID(1),
3350 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
3351 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3352 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3353 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
3354 DeclTypedefAbbrev(0),
3355 DeclVarAbbrev(0), DeclFieldAbbrev(0),
3356 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
3360 ASTWriter::~ASTWriter() {
3361 for (FileDeclIDsTy::iterator
3362 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
3366 void ASTWriter::WriteAST(Sema &SemaRef,
3367 const std::string &OutputFile,
3368 Module *WritingModule, StringRef isysroot,
3372 ASTHasCompilerErrors = hasErrors;
3374 // Emit the file header.
3375 Stream.Emit((unsigned)'C', 8);
3376 Stream.Emit((unsigned)'P', 8);
3377 Stream.Emit((unsigned)'C', 8);
3378 Stream.Emit((unsigned)'H', 8);
3380 WriteBlockInfoBlock();
3382 Context = &SemaRef.Context;
3384 this->WritingModule = WritingModule;
3385 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
3388 this->WritingModule = 0;
3393 template<typename Vector>
3394 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
3395 ASTWriter::RecordData &Record) {
3396 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
3398 Writer.AddDeclRef(*I, Record);
3402 void ASTWriter::WriteASTCore(Sema &SemaRef,
3404 const std::string &OutputFile,
3405 Module *WritingModule) {
3406 using namespace llvm;
3408 // Make sure that the AST reader knows to finalize itself.
3410 Chain->finalizeForWriting();
3412 ASTContext &Context = SemaRef.Context;
3413 Preprocessor &PP = SemaRef.PP;
3415 // Set up predefined declaration IDs.
3416 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
3417 if (Context.ObjCIdDecl)
3418 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
3419 if (Context.ObjCSelDecl)
3420 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
3421 if (Context.ObjCClassDecl)
3422 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
3423 if (Context.ObjCProtocolClassDecl)
3424 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
3425 if (Context.Int128Decl)
3426 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3427 if (Context.UInt128Decl)
3428 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
3429 if (Context.ObjCInstanceTypeDecl)
3430 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
3431 if (Context.BuiltinVaListDecl)
3432 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
3435 // Make sure that we emit IdentifierInfos (and any attached
3436 // declarations) for builtins. We don't need to do this when we're
3437 // emitting chained PCH files, because all of the builtins will be
3438 // in the original PCH file.
3439 // FIXME: Modules won't like this at all.
3440 IdentifierTable &Table = PP.getIdentifierTable();
3441 SmallVector<const char *, 32> BuiltinNames;
3442 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
3443 Context.getLangOpts().NoBuiltin);
3444 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3445 getIdentifierRef(&Table.get(BuiltinNames[I]));
3448 // If there are any out-of-date identifiers, bring them up to date.
3449 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
3450 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3451 IDEnd = PP.getIdentifierTable().end();
3453 if (ID->second->isOutOfDate())
3454 ExtSource->updateOutOfDateIdentifier(*ID->second);
3457 // Build a record containing all of the tentative definitions in this file, in
3458 // TentativeDefinitions order. Generally, this record will be empty for
3460 RecordData TentativeDefinitions;
3461 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
3463 // Build a record containing all of the file scoped decls in this file.
3464 RecordData UnusedFileScopedDecls;
3465 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3466 UnusedFileScopedDecls);
3468 // Build a record containing all of the delegating constructors we still need
3470 RecordData DelegatingCtorDecls;
3471 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
3473 // Write the set of weak, undeclared identifiers. We always write the
3474 // entire table, since later PCH files in a PCH chain are only interested in
3475 // the results at the end of the chain.
3476 RecordData WeakUndeclaredIdentifiers;
3477 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3478 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
3479 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3480 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3481 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3482 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3483 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3484 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3488 // Build a record containing all of the locally-scoped external
3489 // declarations in this header file. Generally, this record will be
3491 RecordData LocallyScopedExternalDecls;
3492 // FIXME: This is filling in the AST file in densemap order which is
3494 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3495 TD = SemaRef.LocallyScopedExternalDecls.begin(),
3496 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3497 TD != TDEnd; ++TD) {
3498 if (!TD->second->isFromASTFile())
3499 AddDeclRef(TD->second, LocallyScopedExternalDecls);
3502 // Build a record containing all of the ext_vector declarations.
3503 RecordData ExtVectorDecls;
3504 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
3506 // Build a record containing all of the VTable uses information.
3507 RecordData VTableUses;
3508 if (!SemaRef.VTableUses.empty()) {
3509 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3510 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3511 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3512 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3516 // Build a record containing all of dynamic classes declarations.
3517 RecordData DynamicClasses;
3518 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
3520 // Build a record containing all of pending implicit instantiations.
3521 RecordData PendingInstantiations;
3522 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3523 I = SemaRef.PendingInstantiations.begin(),
3524 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3525 AddDeclRef(I->first, PendingInstantiations);
3526 AddSourceLocation(I->second, PendingInstantiations);
3528 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3529 "There are local ones at end of translation unit!");
3531 // Build a record containing some declaration references.
3532 RecordData SemaDeclRefs;
3533 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3534 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3535 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3538 RecordData CUDASpecialDeclRefs;
3539 if (Context.getcudaConfigureCallDecl()) {
3540 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3543 // Build a record containing all of the known namespaces.
3544 RecordData KnownNamespaces;
3545 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3546 I = SemaRef.KnownNamespaces.begin(),
3547 IEnd = SemaRef.KnownNamespaces.end();
3550 AddDeclRef(I->first, KnownNamespaces);
3553 // Write the control block
3554 WriteControlBlock(PP, Context, isysroot, OutputFile);
3556 // Write the remaining AST contents.
3558 Stream.EnterSubblock(AST_BLOCK_ID, 5);
3560 // Create a lexical update block containing all of the declarations in the
3561 // translation unit that do not come from other AST files.
3562 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3563 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3564 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3565 E = TU->noload_decls_end();
3567 if (!(*I)->isFromASTFile())
3568 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3571 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3572 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3573 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3574 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3576 Record.push_back(TU_UPDATE_LEXICAL);
3577 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3578 data(NewGlobalDecls));
3580 // And a visible updates block for the translation unit.
3581 Abv = new llvm::BitCodeAbbrev();
3582 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3583 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3584 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3585 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3586 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3587 WriteDeclContextVisibleUpdate(TU);
3589 // If the translation unit has an anonymous namespace, and we don't already
3590 // have an update block for it, write it as an update block.
3591 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
3592 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
3593 if (Record.empty()) {
3594 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
3595 Record.push_back(reinterpret_cast<uint64_t>(NS));
3599 // Make sure visible decls, added to DeclContexts previously loaded from
3600 // an AST file, are registered for serialization.
3601 for (SmallVector<const Decl *, 16>::iterator
3602 I = UpdatingVisibleDecls.begin(),
3603 E = UpdatingVisibleDecls.end(); I != E; ++I) {
3607 // Resolve any declaration pointers within the declaration updates block.
3608 ResolveDeclUpdatesBlocks();
3610 // Form the record of special types.
3611 RecordData SpecialTypes;
3612 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
3613 AddTypeRef(Context.getFILEType(), SpecialTypes);
3614 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
3615 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
3616 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
3617 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
3618 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
3619 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
3621 // Keep writing types and declarations until all types and
3622 // declarations have been written.
3623 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3624 WriteDeclsBlockAbbrevs();
3625 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
3626 E = DeclsToRewrite.end();
3628 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3629 while (!DeclTypesToEmit.empty()) {
3630 DeclOrType DOT = DeclTypesToEmit.front();
3631 DeclTypesToEmit.pop();
3633 WriteType(DOT.getType());
3635 WriteDecl(Context, DOT.getDecl());
3639 DoneWritingDeclsAndTypes = true;
3641 WriteFileDeclIDsMap();
3642 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
3646 // Write the mapping information describing our module dependencies and how
3647 // each of those modules were mapped into our own offset/ID space, so that
3648 // the reader can build the appropriate mapping to its own offset/ID space.
3649 // The map consists solely of a blob with the following format:
3650 // *(module-name-len:i16 module-name:len*i8
3651 // source-location-offset:i32
3652 // identifier-id:i32
3653 // preprocessed-entity-id:i32
3654 // macro-definition-id:i32
3657 // declaration-id:i32
3658 // c++-base-specifiers-id:i32
3661 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3662 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
3663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3664 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
3665 SmallString<2048> Buffer;
3667 llvm::raw_svector_ostream Out(Buffer);
3668 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
3669 MEnd = Chain->ModuleMgr.end();
3671 StringRef FileName = (*M)->FileName;
3672 io::Emit16(Out, FileName.size());
3673 Out.write(FileName.data(), FileName.size());
3674 io::Emit32(Out, (*M)->SLocEntryBaseOffset);
3675 io::Emit32(Out, (*M)->BaseIdentifierID);
3676 io::Emit32(Out, (*M)->BaseMacroID);
3677 io::Emit32(Out, (*M)->BasePreprocessedEntityID);
3678 io::Emit32(Out, (*M)->BaseSubmoduleID);
3679 io::Emit32(Out, (*M)->BaseSelectorID);
3680 io::Emit32(Out, (*M)->BaseDeclID);
3681 io::Emit32(Out, (*M)->BaseTypeIndex);
3685 Record.push_back(MODULE_OFFSET_MAP);
3686 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
3687 Buffer.data(), Buffer.size());
3689 WritePreprocessor(PP, WritingModule != 0);
3690 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
3691 WriteSelectors(SemaRef);
3692 WriteReferencedSelectorsPool(SemaRef);
3693 WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0);
3694 WriteFPPragmaOptions(SemaRef.getFPOptions());
3695 WriteOpenCLExtensions(SemaRef);
3697 WriteTypeDeclOffsets();
3698 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3700 WriteCXXBaseSpecifiersOffsets();
3702 // If we're emitting a module, write out the submodule information.
3704 WriteSubmodules(WritingModule);
3706 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
3708 // Write the record containing external, unnamed definitions.
3709 if (!ExternalDefinitions.empty())
3710 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3712 // Write the record containing tentative definitions.
3713 if (!TentativeDefinitions.empty())
3714 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3716 // Write the record containing unused file scoped decls.
3717 if (!UnusedFileScopedDecls.empty())
3718 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3720 // Write the record containing weak undeclared identifiers.
3721 if (!WeakUndeclaredIdentifiers.empty())
3722 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3723 WeakUndeclaredIdentifiers);
3725 // Write the record containing locally-scoped external definitions.
3726 if (!LocallyScopedExternalDecls.empty())
3727 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3728 LocallyScopedExternalDecls);
3730 // Write the record containing ext_vector type names.
3731 if (!ExtVectorDecls.empty())
3732 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3734 // Write the record containing VTable uses information.
3735 if (!VTableUses.empty())
3736 Stream.EmitRecord(VTABLE_USES, VTableUses);
3738 // Write the record containing dynamic classes declarations.
3739 if (!DynamicClasses.empty())
3740 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3742 // Write the record containing pending implicit instantiations.
3743 if (!PendingInstantiations.empty())
3744 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3746 // Write the record containing declaration references of Sema.
3747 if (!SemaDeclRefs.empty())
3748 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3750 // Write the record containing CUDA-specific declaration references.
3751 if (!CUDASpecialDeclRefs.empty())
3752 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
3754 // Write the delegating constructors.
3755 if (!DelegatingCtorDecls.empty())
3756 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3758 // Write the known namespaces.
3759 if (!KnownNamespaces.empty())
3760 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
3762 // Write the visible updates to DeclContexts.
3763 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3764 I = UpdatedDeclContexts.begin(),
3765 E = UpdatedDeclContexts.end();
3767 WriteDeclContextVisibleUpdate(*I);
3769 if (!WritingModule) {
3770 // Write the submodules that were imported, if any.
3771 RecordData ImportedModules;
3772 for (ASTContext::import_iterator I = Context.local_import_begin(),
3773 IEnd = Context.local_import_end();
3775 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
3776 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
3778 if (!ImportedModules.empty()) {
3780 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
3782 // Unique module IDs.
3783 ImportedModules.erase(std::unique(ImportedModules.begin(),
3784 ImportedModules.end()),
3785 ImportedModules.end());
3787 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
3791 WriteMacroUpdates();
3792 WriteDeclUpdatesBlocks();
3793 WriteDeclReplacementsBlock();
3795 WriteRedeclarations();
3796 WriteObjCCategories();
3798 // Some simple statistics
3800 Record.push_back(NumStatements);
3801 Record.push_back(NumMacros);
3802 Record.push_back(NumLexicalDeclContexts);
3803 Record.push_back(NumVisibleDeclContexts);
3804 Stream.EmitRecord(STATISTICS, Record);
3808 void ASTWriter::WriteMacroUpdates() {
3809 if (MacroUpdates.empty())
3813 for (MacroUpdatesMap::iterator I = MacroUpdates.begin(),
3814 E = MacroUpdates.end();
3816 addMacroRef(I->first, Record);
3817 AddSourceLocation(I->second.UndefLoc, Record);
3818 Record.push_back(inferSubmoduleIDFromLocation(I->second.UndefLoc));
3820 Stream.EmitRecord(MACRO_UPDATES, Record);
3823 /// \brief Go through the declaration update blocks and resolve declaration
3824 /// pointers into declaration IDs.
3825 void ASTWriter::ResolveDeclUpdatesBlocks() {
3826 for (DeclUpdateMap::iterator
3827 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3828 const Decl *D = I->first;
3829 UpdateRecord &URec = I->second;
3832 continue; // The decl will be written completely
3834 unsigned Idx = 0, N = URec.size();
3836 switch ((DeclUpdateKind)URec[Idx++]) {
3837 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
3838 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3839 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
3840 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
3844 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3852 void ASTWriter::WriteDeclUpdatesBlocks() {
3853 if (DeclUpdates.empty())
3856 RecordData OffsetsRecord;
3857 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3858 for (DeclUpdateMap::iterator
3859 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3860 const Decl *D = I->first;
3861 UpdateRecord &URec = I->second;
3864 continue; // The decl will be written completely,no need to store updates.
3866 uint64_t Offset = Stream.GetCurrentBitNo();
3867 Stream.EmitRecord(DECL_UPDATES, URec);
3869 OffsetsRecord.push_back(GetDeclRef(D));
3870 OffsetsRecord.push_back(Offset);
3873 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3876 void ASTWriter::WriteDeclReplacementsBlock() {
3877 if (ReplacedDecls.empty())
3881 for (SmallVector<ReplacedDeclInfo, 16>::iterator
3882 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3883 Record.push_back(I->ID);
3884 Record.push_back(I->Offset);
3885 Record.push_back(I->Loc);
3887 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3890 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3891 Record.push_back(Loc.getRawEncoding());
3894 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3895 AddSourceLocation(Range.getBegin(), Record);
3896 AddSourceLocation(Range.getEnd(), Record);
3899 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3900 Record.push_back(Value.getBitWidth());
3901 const uint64_t *Words = Value.getRawData();
3902 Record.append(Words, Words + Value.getNumWords());
3905 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3906 Record.push_back(Value.isUnsigned());
3907 AddAPInt(Value, Record);
3910 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3911 AddAPInt(Value.bitcastToAPInt(), Record);
3914 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3915 Record.push_back(getIdentifierRef(II));
3918 void ASTWriter::addMacroRef(MacroInfo *MI, RecordDataImpl &Record) {
3919 Record.push_back(getMacroRef(MI));
3922 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3926 IdentID &ID = IdentifierIDs[II];
3932 MacroID ASTWriter::getMacroRef(MacroInfo *MI) {
3933 // Don't emit builtin macros like __LINE__ to the AST file unless they
3934 // have been redefined by the header (in which case they are not
3936 if (MI == 0 || MI->isBuiltinMacro())
3939 MacroID &ID = MacroIDs[MI];
3945 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3946 Record.push_back(getSelectorRef(SelRef));
3949 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3950 if (Sel.getAsOpaquePtr() == 0) {
3954 SelectorID &SID = SelectorIDs[Sel];
3955 if (SID == 0 && Chain) {
3956 // This might trigger a ReadSelector callback, which will set the ID for
3958 Chain->LoadSelector(Sel);
3961 SID = NextSelectorID++;
3966 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3967 AddDeclRef(Temp->getDestructor(), Record);
3970 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3971 CXXBaseSpecifier const *BasesEnd,
3972 RecordDataImpl &Record) {
3973 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3974 CXXBaseSpecifiersToWrite.push_back(
3975 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3977 Record.push_back(NextCXXBaseSpecifiersID++);
3980 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3981 const TemplateArgumentLocInfo &Arg,
3982 RecordDataImpl &Record) {
3984 case TemplateArgument::Expression:
3985 AddStmt(Arg.getAsExpr());
3987 case TemplateArgument::Type:
3988 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3990 case TemplateArgument::Template:
3991 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3992 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3994 case TemplateArgument::TemplateExpansion:
3995 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3996 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3997 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3999 case TemplateArgument::Null:
4000 case TemplateArgument::Integral:
4001 case TemplateArgument::Declaration:
4002 case TemplateArgument::NullPtr:
4003 case TemplateArgument::Pack:
4004 // FIXME: Is this right?
4009 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4010 RecordDataImpl &Record) {
4011 AddTemplateArgument(Arg.getArgument(), Record);
4013 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4014 bool InfoHasSameExpr
4015 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4016 Record.push_back(InfoHasSameExpr);
4017 if (InfoHasSameExpr)
4018 return; // Avoid storing the same expr twice.
4020 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4024 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4025 RecordDataImpl &Record) {
4027 AddTypeRef(QualType(), Record);
4031 AddTypeLoc(TInfo->getTypeLoc(), Record);
4034 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4035 AddTypeRef(TL.getType(), Record);
4037 TypeLocWriter TLW(*this, Record);
4038 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4042 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4043 Record.push_back(GetOrCreateTypeID(T));
4046 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4047 return MakeTypeID(*Context, T,
4048 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4051 TypeID ASTWriter::getTypeID(QualType T) const {
4052 return MakeTypeID(*Context, T,
4053 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4056 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4059 assert(!T.getLocalFastQualifiers());
4061 TypeIdx &Idx = TypeIdxs[T];
4062 if (Idx.getIndex() == 0) {
4063 if (DoneWritingDeclsAndTypes) {
4064 assert(0 && "New type seen after serializing all the types to emit!");
4068 // We haven't seen this type before. Assign it a new ID and put it
4069 // into the queue of types to emit.
4070 Idx = TypeIdx(NextTypeID++);
4071 DeclTypesToEmit.push(T);
4076 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4079 assert(!T.getLocalFastQualifiers());
4081 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4082 assert(I != TypeIdxs.end() && "Type not emitted!");
4086 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4087 Record.push_back(GetDeclRef(D));
4090 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4091 assert(WritingAST && "Cannot request a declaration ID before AST writing");
4097 // If D comes from an AST file, its declaration ID is already known and
4099 if (D->isFromASTFile())
4100 return D->getGlobalID();
4102 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4103 DeclID &ID = DeclIDs[D];
4105 if (DoneWritingDeclsAndTypes) {
4106 assert(0 && "New decl seen after serializing all the decls to emit!");
4110 // We haven't seen this declaration before. Give it a new ID and
4111 // enqueue it in the list of declarations to emit.
4113 DeclTypesToEmit.push(const_cast<Decl *>(D));
4119 DeclID ASTWriter::getDeclID(const Decl *D) {
4123 // If D comes from an AST file, its declaration ID is already known and
4125 if (D->isFromASTFile())
4126 return D->getGlobalID();
4128 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4132 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
4133 std::pair<unsigned, serialization::DeclID> R) {
4134 return L.first < R.first;
4137 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
4141 SourceLocation Loc = D->getLocation();
4142 if (Loc.isInvalid())
4145 // We only keep track of the file-level declarations of each file.
4146 if (!D->getLexicalDeclContext()->isFileContext())
4148 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4149 // a function/objc method, should not have TU as lexical context.
4150 if (isa<ParmVarDecl>(D))
4153 SourceManager &SM = Context->getSourceManager();
4154 SourceLocation FileLoc = SM.getFileLoc(Loc);
4155 assert(SM.isLocalSourceLocation(FileLoc));
4158 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
4159 if (FID.isInvalid())
4161 assert(SM.getSLocEntry(FID).isFile());
4163 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
4165 Info = new DeclIDInFileInfo();
4167 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
4168 LocDeclIDsTy &Decls = Info->DeclIDs;
4170 if (Decls.empty() || Decls.back().first <= Offset) {
4171 Decls.push_back(LocDecl);
4175 LocDeclIDsTy::iterator
4176 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
4178 Decls.insert(I, LocDecl);
4181 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
4182 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
4183 Record.push_back(Name.getNameKind());
4184 switch (Name.getNameKind()) {
4185 case DeclarationName::Identifier:
4186 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4189 case DeclarationName::ObjCZeroArgSelector:
4190 case DeclarationName::ObjCOneArgSelector:
4191 case DeclarationName::ObjCMultiArgSelector:
4192 AddSelectorRef(Name.getObjCSelector(), Record);
4195 case DeclarationName::CXXConstructorName:
4196 case DeclarationName::CXXDestructorName:
4197 case DeclarationName::CXXConversionFunctionName:
4198 AddTypeRef(Name.getCXXNameType(), Record);
4201 case DeclarationName::CXXOperatorName:
4202 Record.push_back(Name.getCXXOverloadedOperator());
4205 case DeclarationName::CXXLiteralOperatorName:
4206 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4209 case DeclarationName::CXXUsingDirective:
4210 // No extra data to emit
4215 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
4216 DeclarationName Name, RecordDataImpl &Record) {
4217 switch (Name.getNameKind()) {
4218 case DeclarationName::CXXConstructorName:
4219 case DeclarationName::CXXDestructorName:
4220 case DeclarationName::CXXConversionFunctionName:
4221 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
4224 case DeclarationName::CXXOperatorName:
4226 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4229 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4233 case DeclarationName::CXXLiteralOperatorName:
4235 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
4239 case DeclarationName::Identifier:
4240 case DeclarationName::ObjCZeroArgSelector:
4241 case DeclarationName::ObjCOneArgSelector:
4242 case DeclarationName::ObjCMultiArgSelector:
4243 case DeclarationName::CXXUsingDirective:
4248 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4249 RecordDataImpl &Record) {
4250 AddDeclarationName(NameInfo.getName(), Record);
4251 AddSourceLocation(NameInfo.getLoc(), Record);
4252 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
4255 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
4256 RecordDataImpl &Record) {
4257 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
4258 Record.push_back(Info.NumTemplParamLists);
4259 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
4260 AddTemplateParameterList(Info.TemplParamLists[i], Record);
4263 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
4264 RecordDataImpl &Record) {
4265 // Nested name specifiers usually aren't too long. I think that 8 would
4266 // typically accommodate the vast majority.
4267 SmallVector<NestedNameSpecifier *, 8> NestedNames;
4269 // Push each of the NNS's onto a stack for serialization in reverse order.
4271 NestedNames.push_back(NNS);
4272 NNS = NNS->getPrefix();
4275 Record.push_back(NestedNames.size());
4276 while(!NestedNames.empty()) {
4277 NNS = NestedNames.pop_back_val();
4278 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
4279 Record.push_back(Kind);
4281 case NestedNameSpecifier::Identifier:
4282 AddIdentifierRef(NNS->getAsIdentifier(), Record);
4285 case NestedNameSpecifier::Namespace:
4286 AddDeclRef(NNS->getAsNamespace(), Record);
4289 case NestedNameSpecifier::NamespaceAlias:
4290 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
4293 case NestedNameSpecifier::TypeSpec:
4294 case NestedNameSpecifier::TypeSpecWithTemplate:
4295 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
4296 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4299 case NestedNameSpecifier::Global:
4300 // Don't need to write an associated value.
4306 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4307 RecordDataImpl &Record) {
4308 // Nested name specifiers usually aren't too long. I think that 8 would
4309 // typically accommodate the vast majority.
4310 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
4312 // Push each of the nested-name-specifiers's onto a stack for
4313 // serialization in reverse order.
4315 NestedNames.push_back(NNS);
4316 NNS = NNS.getPrefix();
4319 Record.push_back(NestedNames.size());
4320 while(!NestedNames.empty()) {
4321 NNS = NestedNames.pop_back_val();
4322 NestedNameSpecifier::SpecifierKind Kind
4323 = NNS.getNestedNameSpecifier()->getKind();
4324 Record.push_back(Kind);
4326 case NestedNameSpecifier::Identifier:
4327 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
4328 AddSourceRange(NNS.getLocalSourceRange(), Record);
4331 case NestedNameSpecifier::Namespace:
4332 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
4333 AddSourceRange(NNS.getLocalSourceRange(), Record);
4336 case NestedNameSpecifier::NamespaceAlias:
4337 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
4338 AddSourceRange(NNS.getLocalSourceRange(), Record);
4341 case NestedNameSpecifier::TypeSpec:
4342 case NestedNameSpecifier::TypeSpecWithTemplate:
4343 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4344 AddTypeLoc(NNS.getTypeLoc(), Record);
4345 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4348 case NestedNameSpecifier::Global:
4349 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4355 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
4356 TemplateName::NameKind Kind = Name.getKind();
4357 Record.push_back(Kind);
4359 case TemplateName::Template:
4360 AddDeclRef(Name.getAsTemplateDecl(), Record);
4363 case TemplateName::OverloadedTemplate: {
4364 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
4365 Record.push_back(OvT->size());
4366 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
4368 AddDeclRef(*I, Record);
4372 case TemplateName::QualifiedTemplate: {
4373 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
4374 AddNestedNameSpecifier(QualT->getQualifier(), Record);
4375 Record.push_back(QualT->hasTemplateKeyword());
4376 AddDeclRef(QualT->getTemplateDecl(), Record);
4380 case TemplateName::DependentTemplate: {
4381 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
4382 AddNestedNameSpecifier(DepT->getQualifier(), Record);
4383 Record.push_back(DepT->isIdentifier());
4384 if (DepT->isIdentifier())
4385 AddIdentifierRef(DepT->getIdentifier(), Record);
4387 Record.push_back(DepT->getOperator());
4391 case TemplateName::SubstTemplateTemplateParm: {
4392 SubstTemplateTemplateParmStorage *subst
4393 = Name.getAsSubstTemplateTemplateParm();
4394 AddDeclRef(subst->getParameter(), Record);
4395 AddTemplateName(subst->getReplacement(), Record);
4399 case TemplateName::SubstTemplateTemplateParmPack: {
4400 SubstTemplateTemplateParmPackStorage *SubstPack
4401 = Name.getAsSubstTemplateTemplateParmPack();
4402 AddDeclRef(SubstPack->getParameterPack(), Record);
4403 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
4409 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
4410 RecordDataImpl &Record) {
4411 Record.push_back(Arg.getKind());
4412 switch (Arg.getKind()) {
4413 case TemplateArgument::Null:
4415 case TemplateArgument::Type:
4416 AddTypeRef(Arg.getAsType(), Record);
4418 case TemplateArgument::Declaration:
4419 AddDeclRef(Arg.getAsDecl(), Record);
4420 Record.push_back(Arg.isDeclForReferenceParam());
4422 case TemplateArgument::NullPtr:
4423 AddTypeRef(Arg.getNullPtrType(), Record);
4425 case TemplateArgument::Integral:
4426 AddAPSInt(Arg.getAsIntegral(), Record);
4427 AddTypeRef(Arg.getIntegralType(), Record);
4429 case TemplateArgument::Template:
4430 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4432 case TemplateArgument::TemplateExpansion:
4433 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4434 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
4435 Record.push_back(*NumExpansions + 1);
4437 Record.push_back(0);
4439 case TemplateArgument::Expression:
4440 AddStmt(Arg.getAsExpr());
4442 case TemplateArgument::Pack:
4443 Record.push_back(Arg.pack_size());
4444 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
4446 AddTemplateArgument(*I, Record);
4452 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
4453 RecordDataImpl &Record) {
4454 assert(TemplateParams && "No TemplateParams!");
4455 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4456 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4457 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4458 Record.push_back(TemplateParams->size());
4459 for (TemplateParameterList::const_iterator
4460 P = TemplateParams->begin(), PEnd = TemplateParams->end();
4462 AddDeclRef(*P, Record);
4465 /// \brief Emit a template argument list.
4467 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
4468 RecordDataImpl &Record) {
4469 assert(TemplateArgs && "No TemplateArgs!");
4470 Record.push_back(TemplateArgs->size());
4471 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
4472 AddTemplateArgument(TemplateArgs->get(i), Record);
4477 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
4478 Record.push_back(Set.size());
4479 for (UnresolvedSetImpl::const_iterator
4480 I = Set.begin(), E = Set.end(); I != E; ++I) {
4481 AddDeclRef(I.getDecl(), Record);
4482 Record.push_back(I.getAccess());
4486 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
4487 RecordDataImpl &Record) {
4488 Record.push_back(Base.isVirtual());
4489 Record.push_back(Base.isBaseOfClass());
4490 Record.push_back(Base.getAccessSpecifierAsWritten());
4491 Record.push_back(Base.getInheritConstructors());
4492 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
4493 AddSourceRange(Base.getSourceRange(), Record);
4494 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
4499 void ASTWriter::FlushCXXBaseSpecifiers() {
4501 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
4504 // Record the offset of this base-specifier set.
4505 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
4506 if (Index == CXXBaseSpecifiersOffsets.size())
4507 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
4509 if (Index > CXXBaseSpecifiersOffsets.size())
4510 CXXBaseSpecifiersOffsets.resize(Index + 1);
4511 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
4514 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
4515 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
4516 Record.push_back(BEnd - B);
4517 for (; B != BEnd; ++B)
4518 AddCXXBaseSpecifier(*B, Record);
4519 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
4521 // Flush any expressions that were written as part of the base specifiers.
4525 CXXBaseSpecifiersToWrite.clear();
4528 void ASTWriter::AddCXXCtorInitializers(
4529 const CXXCtorInitializer * const *CtorInitializers,
4530 unsigned NumCtorInitializers,
4531 RecordDataImpl &Record) {
4532 Record.push_back(NumCtorInitializers);
4533 for (unsigned i=0; i != NumCtorInitializers; ++i) {
4534 const CXXCtorInitializer *Init = CtorInitializers[i];
4536 if (Init->isBaseInitializer()) {
4537 Record.push_back(CTOR_INITIALIZER_BASE);
4538 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4539 Record.push_back(Init->isBaseVirtual());
4540 } else if (Init->isDelegatingInitializer()) {
4541 Record.push_back(CTOR_INITIALIZER_DELEGATING);
4542 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4543 } else if (Init->isMemberInitializer()){
4544 Record.push_back(CTOR_INITIALIZER_MEMBER);
4545 AddDeclRef(Init->getMember(), Record);
4547 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
4548 AddDeclRef(Init->getIndirectMember(), Record);
4551 AddSourceLocation(Init->getMemberLocation(), Record);
4552 AddStmt(Init->getInit());
4553 AddSourceLocation(Init->getLParenLoc(), Record);
4554 AddSourceLocation(Init->getRParenLoc(), Record);
4555 Record.push_back(Init->isWritten());
4556 if (Init->isWritten()) {
4557 Record.push_back(Init->getSourceOrder());
4559 Record.push_back(Init->getNumArrayIndices());
4560 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
4561 AddDeclRef(Init->getArrayIndex(i), Record);
4566 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
4567 assert(D->DefinitionData);
4568 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
4569 Record.push_back(Data.IsLambda);
4570 Record.push_back(Data.UserDeclaredConstructor);
4571 Record.push_back(Data.UserDeclaredCopyConstructor);
4572 Record.push_back(Data.UserDeclaredMoveConstructor);
4573 Record.push_back(Data.UserDeclaredCopyAssignment);
4574 Record.push_back(Data.UserDeclaredMoveAssignment);
4575 Record.push_back(Data.UserDeclaredDestructor);
4576 Record.push_back(Data.Aggregate);
4577 Record.push_back(Data.PlainOldData);
4578 Record.push_back(Data.Empty);
4579 Record.push_back(Data.Polymorphic);
4580 Record.push_back(Data.Abstract);
4581 Record.push_back(Data.IsStandardLayout);
4582 Record.push_back(Data.HasNoNonEmptyBases);
4583 Record.push_back(Data.HasPrivateFields);
4584 Record.push_back(Data.HasProtectedFields);
4585 Record.push_back(Data.HasPublicFields);
4586 Record.push_back(Data.HasMutableFields);
4587 Record.push_back(Data.HasOnlyCMembers);
4588 Record.push_back(Data.HasInClassInitializer);
4589 Record.push_back(Data.HasTrivialDefaultConstructor);
4590 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
4591 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
4592 Record.push_back(Data.HasConstexprDefaultConstructor);
4593 Record.push_back(Data.HasTrivialCopyConstructor);
4594 Record.push_back(Data.HasTrivialMoveConstructor);
4595 Record.push_back(Data.HasTrivialCopyAssignment);
4596 Record.push_back(Data.HasTrivialMoveAssignment);
4597 Record.push_back(Data.HasTrivialDestructor);
4598 Record.push_back(Data.HasIrrelevantDestructor);
4599 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
4600 Record.push_back(Data.ComputedVisibleConversions);
4601 Record.push_back(Data.UserProvidedDefaultConstructor);
4602 Record.push_back(Data.DeclaredDefaultConstructor);
4603 Record.push_back(Data.DeclaredCopyConstructor);
4604 Record.push_back(Data.DeclaredMoveConstructor);
4605 Record.push_back(Data.DeclaredCopyAssignment);
4606 Record.push_back(Data.DeclaredMoveAssignment);
4607 Record.push_back(Data.DeclaredDestructor);
4608 Record.push_back(Data.FailedImplicitMoveConstructor);
4609 Record.push_back(Data.FailedImplicitMoveAssignment);
4610 // IsLambda bit is already saved.
4612 Record.push_back(Data.NumBases);
4613 if (Data.NumBases > 0)
4614 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
4617 // FIXME: Make VBases lazily computed when needed to avoid storing them.
4618 Record.push_back(Data.NumVBases);
4619 if (Data.NumVBases > 0)
4620 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
4623 AddUnresolvedSet(Data.Conversions, Record);
4624 AddUnresolvedSet(Data.VisibleConversions, Record);
4625 // Data.Definition is the owning decl, no need to write it.
4626 AddDeclRef(Data.FirstFriend, Record);
4628 // Add lambda-specific data.
4629 if (Data.IsLambda) {
4630 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
4631 Record.push_back(Lambda.Dependent);
4632 Record.push_back(Lambda.NumCaptures);
4633 Record.push_back(Lambda.NumExplicitCaptures);
4634 Record.push_back(Lambda.ManglingNumber);
4635 AddDeclRef(Lambda.ContextDecl, Record);
4636 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
4637 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
4638 LambdaExpr::Capture &Capture = Lambda.Captures[I];
4639 AddSourceLocation(Capture.getLocation(), Record);
4640 Record.push_back(Capture.isImplicit());
4641 Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
4642 VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0;
4643 AddDeclRef(Var, Record);
4644 AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
4651 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
4652 assert(Reader && "Cannot remove chain");
4653 assert((!Chain || Chain == Reader) && "Cannot replace chain");
4654 assert(FirstDeclID == NextDeclID &&
4655 FirstTypeID == NextTypeID &&
4656 FirstIdentID == NextIdentID &&
4657 FirstMacroID == NextMacroID &&
4658 FirstSubmoduleID == NextSubmoduleID &&
4659 FirstSelectorID == NextSelectorID &&
4660 "Setting chain after writing has started.");
4664 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
4665 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
4666 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
4667 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
4668 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
4669 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
4670 NextDeclID = FirstDeclID;
4671 NextTypeID = FirstTypeID;
4672 NextIdentID = FirstIdentID;
4673 NextMacroID = FirstMacroID;
4674 NextSelectorID = FirstSelectorID;
4675 NextSubmoduleID = FirstSubmoduleID;
4678 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
4679 IdentifierIDs[II] = ID;
4682 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
4686 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
4687 // Always take the highest-numbered type index. This copes with an interesting
4688 // case for chained AST writing where we schedule writing the type and then,
4689 // later, deserialize the type from another AST. In this case, we want to
4690 // keep the higher-numbered entry so that we can properly write it out to
4692 TypeIdx &StoredIdx = TypeIdxs[T];
4693 if (Idx.getIndex() >= StoredIdx.getIndex())
4697 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
4698 SelectorIDs[S] = ID;
4701 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
4702 MacroDefinition *MD) {
4703 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
4704 MacroDefinitions[MD] = ID;
4707 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
4708 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
4709 SubmoduleIDs[Mod] = ID;
4712 void ASTWriter::UndefinedMacro(MacroInfo *MI) {
4713 MacroUpdates[MI].UndefLoc = MI->getUndefLoc();
4716 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
4717 assert(D->isCompleteDefinition());
4718 assert(!WritingAST && "Already writing the AST!");
4719 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
4720 // We are interested when a PCH decl is modified.
4721 if (RD->isFromASTFile()) {
4722 // A forward reference was mutated into a definition. Rewrite it.
4723 // FIXME: This happens during template instantiation, should we
4724 // have created a new definition decl instead ?
4730 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
4731 assert(!WritingAST && "Already writing the AST!");
4733 // TU and namespaces are handled elsewhere.
4734 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
4737 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
4738 return; // Not a source decl added to a DeclContext from PCH.
4740 AddUpdatedDeclContext(DC);
4741 UpdatingVisibleDecls.push_back(D);
4744 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
4745 assert(!WritingAST && "Already writing the AST!");
4746 assert(D->isImplicit());
4747 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
4748 return; // Not a source member added to a class from PCH.
4749 if (!isa<CXXMethodDecl>(D))
4750 return; // We are interested in lazily declared implicit methods.
4752 // A decl coming from PCH was modified.
4753 assert(RD->isCompleteDefinition());
4754 UpdateRecord &Record = DeclUpdates[RD];
4755 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
4756 Record.push_back(reinterpret_cast<uint64_t>(D));
4759 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4760 const ClassTemplateSpecializationDecl *D) {
4761 // The specializations set is kept in the canonical template.
4762 assert(!WritingAST && "Already writing the AST!");
4763 TD = TD->getCanonicalDecl();
4764 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4765 return; // Not a source specialization added to a template from PCH.
4767 UpdateRecord &Record = DeclUpdates[TD];
4768 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4769 Record.push_back(reinterpret_cast<uint64_t>(D));
4772 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4773 const FunctionDecl *D) {
4774 // The specializations set is kept in the canonical template.
4775 assert(!WritingAST && "Already writing the AST!");
4776 TD = TD->getCanonicalDecl();
4777 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4778 return; // Not a source specialization added to a template from PCH.
4780 UpdateRecord &Record = DeclUpdates[TD];
4781 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4782 Record.push_back(reinterpret_cast<uint64_t>(D));
4785 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4786 assert(!WritingAST && "Already writing the AST!");
4787 if (!D->isFromASTFile())
4788 return; // Declaration not imported from PCH.
4790 // Implicit decl from a PCH was defined.
4791 // FIXME: Should implicit definition be a separate FunctionDecl?
4795 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4796 assert(!WritingAST && "Already writing the AST!");
4797 if (!D->isFromASTFile())
4800 // Since the actual instantiation is delayed, this really means that we need
4801 // to update the instantiation location.
4802 UpdateRecord &Record = DeclUpdates[D];
4803 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4805 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4808 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
4809 const ObjCInterfaceDecl *IFD) {
4810 assert(!WritingAST && "Already writing the AST!");
4811 if (!IFD->isFromASTFile())
4812 return; // Declaration not imported from PCH.
4814 assert(IFD->getDefinition() && "Category on a class without a definition?");
4815 ObjCClassesWithCategories.insert(
4816 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
4820 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
4821 const ObjCPropertyDecl *OrigProp,
4822 const ObjCCategoryDecl *ClassExt) {
4823 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
4827 assert(!WritingAST && "Already writing the AST!");
4828 if (!D->isFromASTFile())
4829 return; // Declaration not imported from PCH.