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/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclContextInternals.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclLookups.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/FileSystemStatCache.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/SourceManagerInternals.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/TargetOptions.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/MacroInfo.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/PreprocessorOptions.h"
41 #include "clang/Sema/IdentifierResolver.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Serialization/ASTReader.h"
44 #include "llvm/ADT/APFloat.h"
45 #include "llvm/ADT/APInt.h"
46 #include "llvm/ADT/Hashing.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Bitcode/BitstreamWriter.h"
49 #include "llvm/Support/EndianStream.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/OnDiskHashTable.h"
53 #include "llvm/Support/Path.h"
58 using namespace clang;
59 using namespace clang::serialization;
61 template <typename T, typename Allocator>
62 static StringRef data(const std::vector<T, Allocator> &v) {
63 if (v.empty()) return StringRef();
64 return StringRef(reinterpret_cast<const char*>(&v[0]),
65 sizeof(T) * v.size());
69 static StringRef data(const SmallVectorImpl<T> &v) {
70 return StringRef(reinterpret_cast<const char*>(v.data()),
71 sizeof(T) * v.size());
74 //===----------------------------------------------------------------------===//
76 //===----------------------------------------------------------------------===//
81 ASTWriter::RecordDataImpl &Record;
84 /// \brief Type code that corresponds to the record generated.
86 /// \brief Abbreviation to use for the record, if any.
89 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
90 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
92 void VisitArrayType(const ArrayType *T);
93 void VisitFunctionType(const FunctionType *T);
94 void VisitTagType(const TagType *T);
96 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
97 #define ABSTRACT_TYPE(Class, Base)
98 #include "clang/AST/TypeNodes.def"
102 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
103 llvm_unreachable("Built-in types are never serialized");
106 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
107 Writer.AddTypeRef(T->getElementType(), Record);
111 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
112 Writer.AddTypeRef(T->getPointeeType(), Record);
116 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
117 Writer.AddTypeRef(T->getOriginalType(), Record);
121 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
122 Writer.AddTypeRef(T->getOriginalType(), Record);
123 Writer.AddTypeRef(T->getAdjustedType(), Record);
124 Code = TYPE_ADJUSTED;
127 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
128 Writer.AddTypeRef(T->getPointeeType(), Record);
129 Code = TYPE_BLOCK_POINTER;
132 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
133 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
134 Record.push_back(T->isSpelledAsLValue());
135 Code = TYPE_LVALUE_REFERENCE;
138 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
139 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
140 Code = TYPE_RVALUE_REFERENCE;
143 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
144 Writer.AddTypeRef(T->getPointeeType(), Record);
145 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
146 Code = TYPE_MEMBER_POINTER;
149 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
150 Writer.AddTypeRef(T->getElementType(), Record);
151 Record.push_back(T->getSizeModifier()); // FIXME: stable values
152 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
155 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
157 Writer.AddAPInt(T->getSize(), Record);
158 Code = TYPE_CONSTANT_ARRAY;
161 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
163 Code = TYPE_INCOMPLETE_ARRAY;
166 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
168 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
169 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
170 Writer.AddStmt(T->getSizeExpr());
171 Code = TYPE_VARIABLE_ARRAY;
174 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
175 Writer.AddTypeRef(T->getElementType(), Record);
176 Record.push_back(T->getNumElements());
177 Record.push_back(T->getVectorKind());
181 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
183 Code = TYPE_EXT_VECTOR;
186 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
187 Writer.AddTypeRef(T->getReturnType(), Record);
188 FunctionType::ExtInfo C = T->getExtInfo();
189 Record.push_back(C.getNoReturn());
190 Record.push_back(C.getHasRegParm());
191 Record.push_back(C.getRegParm());
192 // FIXME: need to stabilize encoding of calling convention...
193 Record.push_back(C.getCC());
194 Record.push_back(C.getProducesResult());
196 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
200 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
201 VisitFunctionType(T);
202 Code = TYPE_FUNCTION_NO_PROTO;
205 static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
206 ASTWriter::RecordDataImpl &Record) {
207 Record.push_back(T->getExceptionSpecType());
208 if (T->getExceptionSpecType() == EST_Dynamic) {
209 Record.push_back(T->getNumExceptions());
210 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
211 Writer.AddTypeRef(T->getExceptionType(I), Record);
212 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
213 Writer.AddStmt(T->getNoexceptExpr());
214 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
215 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
216 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
217 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
218 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
222 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
223 VisitFunctionType(T);
225 Record.push_back(T->isVariadic());
226 Record.push_back(T->hasTrailingReturn());
227 Record.push_back(T->getTypeQuals());
228 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
229 addExceptionSpec(Writer, T, Record);
231 Record.push_back(T->getNumParams());
232 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
233 Writer.AddTypeRef(T->getParamType(I), Record);
235 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
236 T->getRefQualifier() || T->getExceptionSpecType() != EST_None)
239 Code = TYPE_FUNCTION_PROTO;
242 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
243 Writer.AddDeclRef(T->getDecl(), Record);
244 Code = TYPE_UNRESOLVED_USING;
247 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
248 Writer.AddDeclRef(T->getDecl(), Record);
249 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
250 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
254 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
255 Writer.AddStmt(T->getUnderlyingExpr());
256 Code = TYPE_TYPEOF_EXPR;
259 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
260 Writer.AddTypeRef(T->getUnderlyingType(), Record);
264 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
265 Writer.AddTypeRef(T->getUnderlyingType(), Record);
266 Writer.AddStmt(T->getUnderlyingExpr());
267 Code = TYPE_DECLTYPE;
270 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
271 Writer.AddTypeRef(T->getBaseType(), Record);
272 Writer.AddTypeRef(T->getUnderlyingType(), Record);
273 Record.push_back(T->getUTTKind());
274 Code = TYPE_UNARY_TRANSFORM;
277 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
278 Writer.AddTypeRef(T->getDeducedType(), Record);
279 Record.push_back(T->isDecltypeAuto());
280 if (T->getDeducedType().isNull())
281 Record.push_back(T->isDependentType());
285 void ASTTypeWriter::VisitTagType(const TagType *T) {
286 Record.push_back(T->isDependentType());
287 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
288 assert(!T->isBeingDefined() &&
289 "Cannot serialize in the middle of a type definition");
292 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
297 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
302 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
303 Writer.AddTypeRef(T->getModifiedType(), Record);
304 Writer.AddTypeRef(T->getEquivalentType(), Record);
305 Record.push_back(T->getAttrKind());
306 Code = TYPE_ATTRIBUTED;
310 ASTTypeWriter::VisitSubstTemplateTypeParmType(
311 const SubstTemplateTypeParmType *T) {
312 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
313 Writer.AddTypeRef(T->getReplacementType(), Record);
314 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
318 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
319 const SubstTemplateTypeParmPackType *T) {
320 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
321 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
322 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
326 ASTTypeWriter::VisitTemplateSpecializationType(
327 const TemplateSpecializationType *T) {
328 Record.push_back(T->isDependentType());
329 Writer.AddTemplateName(T->getTemplateName(), Record);
330 Record.push_back(T->getNumArgs());
331 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
332 ArgI != ArgE; ++ArgI)
333 Writer.AddTemplateArgument(*ArgI, Record);
334 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
335 T->isCanonicalUnqualified() ? QualType()
336 : T->getCanonicalTypeInternal(),
338 Code = TYPE_TEMPLATE_SPECIALIZATION;
342 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
344 Writer.AddStmt(T->getSizeExpr());
345 Writer.AddSourceRange(T->getBracketsRange(), Record);
346 Code = TYPE_DEPENDENT_SIZED_ARRAY;
350 ASTTypeWriter::VisitDependentSizedExtVectorType(
351 const DependentSizedExtVectorType *T) {
352 // FIXME: Serialize this type (C++ only)
353 llvm_unreachable("Cannot serialize dependent sized extended vector types");
357 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
358 Record.push_back(T->getDepth());
359 Record.push_back(T->getIndex());
360 Record.push_back(T->isParameterPack());
361 Writer.AddDeclRef(T->getDecl(), Record);
362 Code = TYPE_TEMPLATE_TYPE_PARM;
366 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
367 Record.push_back(T->getKeyword());
368 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
369 Writer.AddIdentifierRef(T->getIdentifier(), Record);
370 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
371 : T->getCanonicalTypeInternal(),
373 Code = TYPE_DEPENDENT_NAME;
377 ASTTypeWriter::VisitDependentTemplateSpecializationType(
378 const DependentTemplateSpecializationType *T) {
379 Record.push_back(T->getKeyword());
380 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
381 Writer.AddIdentifierRef(T->getIdentifier(), Record);
382 Record.push_back(T->getNumArgs());
383 for (DependentTemplateSpecializationType::iterator
384 I = T->begin(), E = T->end(); I != E; ++I)
385 Writer.AddTemplateArgument(*I, Record);
386 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
389 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
390 Writer.AddTypeRef(T->getPattern(), Record);
391 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
392 Record.push_back(*NumExpansions + 1);
395 Code = TYPE_PACK_EXPANSION;
398 void ASTTypeWriter::VisitParenType(const ParenType *T) {
399 Writer.AddTypeRef(T->getInnerType(), Record);
403 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
404 Record.push_back(T->getKeyword());
405 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
406 Writer.AddTypeRef(T->getNamedType(), Record);
407 Code = TYPE_ELABORATED;
410 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
411 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
412 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
413 Code = TYPE_INJECTED_CLASS_NAME;
416 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
417 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
418 Code = TYPE_OBJC_INTERFACE;
421 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
422 Writer.AddTypeRef(T->getBaseType(), Record);
423 Record.push_back(T->getNumProtocols());
424 for (const auto *I : T->quals())
425 Writer.AddDeclRef(I, Record);
426 Code = TYPE_OBJC_OBJECT;
430 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
431 Writer.AddTypeRef(T->getPointeeType(), Record);
432 Code = TYPE_OBJC_OBJECT_POINTER;
436 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
437 Writer.AddTypeRef(T->getValueType(), Record);
443 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
445 ASTWriter::RecordDataImpl &Record;
448 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
449 : Writer(Writer), Record(Record) { }
451 #define ABSTRACT_TYPELOC(CLASS, PARENT)
452 #define TYPELOC(CLASS, PARENT) \
453 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
454 #include "clang/AST/TypeLocNodes.def"
456 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
457 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
462 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
465 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
466 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
467 if (TL.needsExtraLocalData()) {
468 Record.push_back(TL.getWrittenTypeSpec());
469 Record.push_back(TL.getWrittenSignSpec());
470 Record.push_back(TL.getWrittenWidthSpec());
471 Record.push_back(TL.hasModeAttr());
474 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
475 Writer.AddSourceLocation(TL.getNameLoc(), Record);
477 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
478 Writer.AddSourceLocation(TL.getStarLoc(), Record);
480 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
483 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
486 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
487 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
489 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
490 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
492 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
493 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
495 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
496 Writer.AddSourceLocation(TL.getStarLoc(), Record);
497 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
499 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
500 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
501 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
502 Record.push_back(TL.getSizeExpr() ? 1 : 0);
503 if (TL.getSizeExpr())
504 Writer.AddStmt(TL.getSizeExpr());
506 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
507 VisitArrayTypeLoc(TL);
509 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
510 VisitArrayTypeLoc(TL);
512 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
513 VisitArrayTypeLoc(TL);
515 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
516 DependentSizedArrayTypeLoc TL) {
517 VisitArrayTypeLoc(TL);
519 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
520 DependentSizedExtVectorTypeLoc TL) {
521 Writer.AddSourceLocation(TL.getNameLoc(), Record);
523 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
524 Writer.AddSourceLocation(TL.getNameLoc(), Record);
526 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
527 Writer.AddSourceLocation(TL.getNameLoc(), Record);
529 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
530 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
531 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
532 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
533 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
534 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
535 Writer.AddDeclRef(TL.getParam(i), Record);
537 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
538 VisitFunctionTypeLoc(TL);
540 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
541 VisitFunctionTypeLoc(TL);
543 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
544 Writer.AddSourceLocation(TL.getNameLoc(), Record);
546 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
547 Writer.AddSourceLocation(TL.getNameLoc(), Record);
549 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
550 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
551 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
552 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
554 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
555 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
556 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
557 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
558 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
560 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
561 Writer.AddSourceLocation(TL.getNameLoc(), Record);
563 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
564 Writer.AddSourceLocation(TL.getKWLoc(), Record);
565 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
566 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
567 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
569 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
570 Writer.AddSourceLocation(TL.getNameLoc(), Record);
572 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
573 Writer.AddSourceLocation(TL.getNameLoc(), Record);
575 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
576 Writer.AddSourceLocation(TL.getNameLoc(), Record);
578 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
579 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
580 if (TL.hasAttrOperand()) {
581 SourceRange range = TL.getAttrOperandParensRange();
582 Writer.AddSourceLocation(range.getBegin(), Record);
583 Writer.AddSourceLocation(range.getEnd(), Record);
585 if (TL.hasAttrExprOperand()) {
586 Expr *operand = TL.getAttrExprOperand();
587 Record.push_back(operand ? 1 : 0);
588 if (operand) Writer.AddStmt(operand);
589 } else if (TL.hasAttrEnumOperand()) {
590 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
593 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
594 Writer.AddSourceLocation(TL.getNameLoc(), Record);
596 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
597 SubstTemplateTypeParmTypeLoc TL) {
598 Writer.AddSourceLocation(TL.getNameLoc(), Record);
600 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
601 SubstTemplateTypeParmPackTypeLoc TL) {
602 Writer.AddSourceLocation(TL.getNameLoc(), Record);
604 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
605 TemplateSpecializationTypeLoc TL) {
606 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
607 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
608 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
609 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
610 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
611 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
612 TL.getArgLoc(i).getLocInfo(), Record);
614 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
615 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
616 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
618 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
619 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
620 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
622 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
623 Writer.AddSourceLocation(TL.getNameLoc(), Record);
625 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
626 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
627 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
628 Writer.AddSourceLocation(TL.getNameLoc(), Record);
630 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
631 DependentTemplateSpecializationTypeLoc TL) {
632 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
633 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
634 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
635 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
636 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
637 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
638 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
639 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
640 TL.getArgLoc(I).getLocInfo(), Record);
642 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
643 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
645 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
646 Writer.AddSourceLocation(TL.getNameLoc(), Record);
648 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
649 Record.push_back(TL.hasBaseTypeAsWritten());
650 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
651 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
652 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
653 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
655 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
656 Writer.AddSourceLocation(TL.getStarLoc(), Record);
658 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
659 Writer.AddSourceLocation(TL.getKWLoc(), Record);
660 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
661 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
664 void ASTWriter::WriteTypeAbbrevs() {
665 using namespace llvm;
669 // Abbreviation for TYPE_EXT_QUAL
670 Abv = new BitCodeAbbrev();
671 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
672 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
673 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
674 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
676 // Abbreviation for TYPE_FUNCTION_PROTO
677 Abv = new BitCodeAbbrev();
678 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
680 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
681 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
682 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
683 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
684 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
685 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
687 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
688 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
689 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
690 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
691 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
692 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
693 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
694 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
695 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
698 //===----------------------------------------------------------------------===//
699 // ASTWriter Implementation
700 //===----------------------------------------------------------------------===//
702 static void EmitBlockID(unsigned ID, const char *Name,
703 llvm::BitstreamWriter &Stream,
704 ASTWriter::RecordDataImpl &Record) {
706 Record.push_back(ID);
707 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
709 // Emit the block name if present.
710 if (!Name || Name[0] == 0)
714 Record.push_back(*Name++);
715 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
718 static void EmitRecordID(unsigned ID, const char *Name,
719 llvm::BitstreamWriter &Stream,
720 ASTWriter::RecordDataImpl &Record) {
722 Record.push_back(ID);
724 Record.push_back(*Name++);
725 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
728 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
729 ASTWriter::RecordDataImpl &Record) {
730 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
732 RECORD(STMT_NULL_PTR);
733 RECORD(STMT_REF_PTR);
735 RECORD(STMT_COMPOUND);
737 RECORD(STMT_DEFAULT);
739 RECORD(STMT_ATTRIBUTED);
746 RECORD(STMT_INDIRECT_GOTO);
747 RECORD(STMT_CONTINUE);
753 RECORD(EXPR_PREDEFINED);
754 RECORD(EXPR_DECL_REF);
755 RECORD(EXPR_INTEGER_LITERAL);
756 RECORD(EXPR_FLOATING_LITERAL);
757 RECORD(EXPR_IMAGINARY_LITERAL);
758 RECORD(EXPR_STRING_LITERAL);
759 RECORD(EXPR_CHARACTER_LITERAL);
761 RECORD(EXPR_PAREN_LIST);
762 RECORD(EXPR_UNARY_OPERATOR);
763 RECORD(EXPR_SIZEOF_ALIGN_OF);
764 RECORD(EXPR_ARRAY_SUBSCRIPT);
767 RECORD(EXPR_BINARY_OPERATOR);
768 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
769 RECORD(EXPR_CONDITIONAL_OPERATOR);
770 RECORD(EXPR_IMPLICIT_CAST);
771 RECORD(EXPR_CSTYLE_CAST);
772 RECORD(EXPR_COMPOUND_LITERAL);
773 RECORD(EXPR_EXT_VECTOR_ELEMENT);
774 RECORD(EXPR_INIT_LIST);
775 RECORD(EXPR_DESIGNATED_INIT);
776 RECORD(EXPR_IMPLICIT_VALUE_INIT);
778 RECORD(EXPR_ADDR_LABEL);
781 RECORD(EXPR_GNU_NULL);
782 RECORD(EXPR_SHUFFLE_VECTOR);
784 RECORD(EXPR_GENERIC_SELECTION);
785 RECORD(EXPR_OBJC_STRING_LITERAL);
786 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
787 RECORD(EXPR_OBJC_ARRAY_LITERAL);
788 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
789 RECORD(EXPR_OBJC_ENCODE);
790 RECORD(EXPR_OBJC_SELECTOR_EXPR);
791 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
792 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
793 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
794 RECORD(EXPR_OBJC_KVC_REF_EXPR);
795 RECORD(EXPR_OBJC_MESSAGE_EXPR);
796 RECORD(STMT_OBJC_FOR_COLLECTION);
797 RECORD(STMT_OBJC_CATCH);
798 RECORD(STMT_OBJC_FINALLY);
799 RECORD(STMT_OBJC_AT_TRY);
800 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
801 RECORD(STMT_OBJC_AT_THROW);
802 RECORD(EXPR_OBJC_BOOL_LITERAL);
803 RECORD(STMT_CXX_CATCH);
804 RECORD(STMT_CXX_TRY);
805 RECORD(STMT_CXX_FOR_RANGE);
806 RECORD(EXPR_CXX_OPERATOR_CALL);
807 RECORD(EXPR_CXX_MEMBER_CALL);
808 RECORD(EXPR_CXX_CONSTRUCT);
809 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
810 RECORD(EXPR_CXX_STATIC_CAST);
811 RECORD(EXPR_CXX_DYNAMIC_CAST);
812 RECORD(EXPR_CXX_REINTERPRET_CAST);
813 RECORD(EXPR_CXX_CONST_CAST);
814 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
815 RECORD(EXPR_USER_DEFINED_LITERAL);
816 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
817 RECORD(EXPR_CXX_BOOL_LITERAL);
818 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
819 RECORD(EXPR_CXX_TYPEID_EXPR);
820 RECORD(EXPR_CXX_TYPEID_TYPE);
821 RECORD(EXPR_CXX_THIS);
822 RECORD(EXPR_CXX_THROW);
823 RECORD(EXPR_CXX_DEFAULT_ARG);
824 RECORD(EXPR_CXX_DEFAULT_INIT);
825 RECORD(EXPR_CXX_BIND_TEMPORARY);
826 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
827 RECORD(EXPR_CXX_NEW);
828 RECORD(EXPR_CXX_DELETE);
829 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
830 RECORD(EXPR_EXPR_WITH_CLEANUPS);
831 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
832 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
833 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
834 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
835 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
836 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
837 RECORD(EXPR_CXX_NOEXCEPT);
838 RECORD(EXPR_OPAQUE_VALUE);
839 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
840 RECORD(EXPR_TYPE_TRAIT);
841 RECORD(EXPR_ARRAY_TYPE_TRAIT);
842 RECORD(EXPR_PACK_EXPANSION);
843 RECORD(EXPR_SIZEOF_PACK);
844 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
845 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
846 RECORD(EXPR_FUNCTION_PARM_PACK);
847 RECORD(EXPR_MATERIALIZE_TEMPORARY);
848 RECORD(EXPR_CUDA_KERNEL_CALL);
849 RECORD(EXPR_CXX_UUIDOF_EXPR);
850 RECORD(EXPR_CXX_UUIDOF_TYPE);
855 void ASTWriter::WriteBlockInfoBlock() {
857 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
859 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
860 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
863 BLOCK(CONTROL_BLOCK);
866 RECORD(MODULE_MAP_FILE);
868 RECORD(LANGUAGE_OPTIONS);
869 RECORD(TARGET_OPTIONS);
870 RECORD(ORIGINAL_FILE);
871 RECORD(ORIGINAL_PCH_DIR);
872 RECORD(ORIGINAL_FILE_ID);
873 RECORD(INPUT_FILE_OFFSETS);
874 RECORD(DIAGNOSTIC_OPTIONS);
875 RECORD(FILE_SYSTEM_OPTIONS);
876 RECORD(HEADER_SEARCH_OPTIONS);
877 RECORD(PREPROCESSOR_OPTIONS);
879 BLOCK(INPUT_FILES_BLOCK);
882 // AST Top-Level Block.
886 RECORD(IDENTIFIER_OFFSET);
887 RECORD(IDENTIFIER_TABLE);
888 RECORD(EAGERLY_DESERIALIZED_DECLS);
889 RECORD(SPECIAL_TYPES);
891 RECORD(TENTATIVE_DEFINITIONS);
892 RECORD(UNUSED_FILESCOPED_DECLS);
893 RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS);
894 RECORD(SELECTOR_OFFSETS);
896 RECORD(PP_COUNTER_VALUE);
897 RECORD(SOURCE_LOCATION_OFFSETS);
898 RECORD(SOURCE_LOCATION_PRELOADS);
899 RECORD(EXT_VECTOR_DECLS);
900 RECORD(PPD_ENTITIES_OFFSETS);
901 RECORD(REFERENCED_SELECTOR_POOL);
902 RECORD(TU_UPDATE_LEXICAL);
903 RECORD(LOCAL_REDECLARATIONS_MAP);
904 RECORD(SEMA_DECL_REFS);
905 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
906 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
907 RECORD(DECL_REPLACEMENTS);
908 RECORD(UPDATE_VISIBLE);
909 RECORD(DECL_UPDATE_OFFSETS);
910 RECORD(DECL_UPDATES);
911 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
912 RECORD(DIAG_PRAGMA_MAPPINGS);
913 RECORD(CUDA_SPECIAL_DECL_REFS);
914 RECORD(HEADER_SEARCH_TABLE);
915 RECORD(FP_PRAGMA_OPTIONS);
916 RECORD(OPENCL_EXTENSIONS);
917 RECORD(DELEGATING_CTORS);
918 RECORD(KNOWN_NAMESPACES);
919 RECORD(UNDEFINED_BUT_USED);
920 RECORD(MODULE_OFFSET_MAP);
921 RECORD(SOURCE_MANAGER_LINE_TABLE);
922 RECORD(OBJC_CATEGORIES_MAP);
923 RECORD(FILE_SORTED_DECLS);
924 RECORD(IMPORTED_MODULES);
925 RECORD(MERGED_DECLARATIONS);
926 RECORD(LOCAL_REDECLARATIONS);
927 RECORD(OBJC_CATEGORIES);
928 RECORD(MACRO_OFFSET);
930 RECORD(LATE_PARSED_TEMPLATE);
931 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
933 // SourceManager Block.
934 BLOCK(SOURCE_MANAGER_BLOCK);
935 RECORD(SM_SLOC_FILE_ENTRY);
936 RECORD(SM_SLOC_BUFFER_ENTRY);
937 RECORD(SM_SLOC_BUFFER_BLOB);
938 RECORD(SM_SLOC_EXPANSION_ENTRY);
940 // Preprocessor Block.
941 BLOCK(PREPROCESSOR_BLOCK);
942 RECORD(PP_MACRO_OBJECT_LIKE);
943 RECORD(PP_MACRO_FUNCTION_LIKE);
946 // Decls and Types block.
947 BLOCK(DECLTYPES_BLOCK);
948 RECORD(TYPE_EXT_QUAL);
949 RECORD(TYPE_COMPLEX);
950 RECORD(TYPE_POINTER);
951 RECORD(TYPE_BLOCK_POINTER);
952 RECORD(TYPE_LVALUE_REFERENCE);
953 RECORD(TYPE_RVALUE_REFERENCE);
954 RECORD(TYPE_MEMBER_POINTER);
955 RECORD(TYPE_CONSTANT_ARRAY);
956 RECORD(TYPE_INCOMPLETE_ARRAY);
957 RECORD(TYPE_VARIABLE_ARRAY);
959 RECORD(TYPE_EXT_VECTOR);
960 RECORD(TYPE_FUNCTION_NO_PROTO);
961 RECORD(TYPE_FUNCTION_PROTO);
962 RECORD(TYPE_TYPEDEF);
963 RECORD(TYPE_TYPEOF_EXPR);
967 RECORD(TYPE_OBJC_INTERFACE);
968 RECORD(TYPE_OBJC_OBJECT_POINTER);
969 RECORD(TYPE_DECLTYPE);
970 RECORD(TYPE_ELABORATED);
971 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
972 RECORD(TYPE_UNRESOLVED_USING);
973 RECORD(TYPE_INJECTED_CLASS_NAME);
974 RECORD(TYPE_OBJC_OBJECT);
975 RECORD(TYPE_TEMPLATE_TYPE_PARM);
976 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
977 RECORD(TYPE_DEPENDENT_NAME);
978 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
979 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
981 RECORD(TYPE_PACK_EXPANSION);
982 RECORD(TYPE_ATTRIBUTED);
983 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
985 RECORD(TYPE_UNARY_TRANSFORM);
987 RECORD(TYPE_DECAYED);
988 RECORD(TYPE_ADJUSTED);
989 RECORD(DECL_TYPEDEF);
990 RECORD(DECL_TYPEALIAS);
993 RECORD(DECL_ENUM_CONSTANT);
994 RECORD(DECL_FUNCTION);
995 RECORD(DECL_OBJC_METHOD);
996 RECORD(DECL_OBJC_INTERFACE);
997 RECORD(DECL_OBJC_PROTOCOL);
998 RECORD(DECL_OBJC_IVAR);
999 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1000 RECORD(DECL_OBJC_CATEGORY);
1001 RECORD(DECL_OBJC_CATEGORY_IMPL);
1002 RECORD(DECL_OBJC_IMPLEMENTATION);
1003 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1004 RECORD(DECL_OBJC_PROPERTY);
1005 RECORD(DECL_OBJC_PROPERTY_IMPL);
1007 RECORD(DECL_MS_PROPERTY);
1009 RECORD(DECL_IMPLICIT_PARAM);
1010 RECORD(DECL_PARM_VAR);
1011 RECORD(DECL_FILE_SCOPE_ASM);
1013 RECORD(DECL_CONTEXT_LEXICAL);
1014 RECORD(DECL_CONTEXT_VISIBLE);
1015 RECORD(DECL_NAMESPACE);
1016 RECORD(DECL_NAMESPACE_ALIAS);
1018 RECORD(DECL_USING_SHADOW);
1019 RECORD(DECL_USING_DIRECTIVE);
1020 RECORD(DECL_UNRESOLVED_USING_VALUE);
1021 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1022 RECORD(DECL_LINKAGE_SPEC);
1023 RECORD(DECL_CXX_RECORD);
1024 RECORD(DECL_CXX_METHOD);
1025 RECORD(DECL_CXX_CONSTRUCTOR);
1026 RECORD(DECL_CXX_DESTRUCTOR);
1027 RECORD(DECL_CXX_CONVERSION);
1028 RECORD(DECL_ACCESS_SPEC);
1029 RECORD(DECL_FRIEND);
1030 RECORD(DECL_FRIEND_TEMPLATE);
1031 RECORD(DECL_CLASS_TEMPLATE);
1032 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1033 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1034 RECORD(DECL_VAR_TEMPLATE);
1035 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1036 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1037 RECORD(DECL_FUNCTION_TEMPLATE);
1038 RECORD(DECL_TEMPLATE_TYPE_PARM);
1039 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1040 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1041 RECORD(DECL_STATIC_ASSERT);
1042 RECORD(DECL_CXX_BASE_SPECIFIERS);
1043 RECORD(DECL_INDIRECTFIELD);
1044 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1046 // Statements and Exprs can occur in the Decls and Types block.
1047 AddStmtsExprs(Stream, Record);
1049 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1050 RECORD(PPD_MACRO_EXPANSION);
1051 RECORD(PPD_MACRO_DEFINITION);
1052 RECORD(PPD_INCLUSION_DIRECTIVE);
1059 /// \brief Adjusts the given filename to only write out the portion of the
1060 /// filename that is not part of the system root directory.
1062 /// \param Filename the file name to adjust.
1064 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
1065 /// the returned filename will be adjusted by this system root.
1067 /// \returns either the original filename (if it needs no adjustment) or the
1068 /// adjusted filename (which points into the @p Filename parameter).
1070 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
1071 assert(Filename && "No file name to adjust?");
1073 if (isysroot.empty())
1076 // Verify that the filename and the system root have the same prefix.
1078 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
1079 if (Filename[Pos] != isysroot[Pos])
1080 return Filename; // Prefixes don't match.
1082 // We hit the end of the filename before we hit the end of the system root.
1086 // If the file name has a '/' at the current position, skip over the '/'.
1087 // We distinguish sysroot-based includes from absolute includes by the
1088 // absence of '/' at the beginning of sysroot-based includes.
1089 if (Filename[Pos] == '/')
1092 return Filename + Pos;
1095 /// \brief Write the control block.
1096 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1098 const std::string &OutputFile) {
1099 using namespace llvm;
1100 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1104 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1105 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1106 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1107 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1108 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1109 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1110 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1111 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1112 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1113 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1114 Record.push_back(METADATA);
1115 Record.push_back(VERSION_MAJOR);
1116 Record.push_back(VERSION_MINOR);
1117 Record.push_back(CLANG_VERSION_MAJOR);
1118 Record.push_back(CLANG_VERSION_MINOR);
1119 Record.push_back(!isysroot.empty());
1120 Record.push_back(ASTHasCompilerErrors);
1121 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1122 getClangFullRepositoryVersion());
1125 if (WritingModule) {
1126 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1127 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1128 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1129 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1131 Record.push_back(MODULE_NAME);
1132 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1136 if (WritingModule) {
1138 auto addModMap = [&](const FileEntry *F) {
1139 SmallString<128> ModuleMap(F->getName());
1140 llvm::sys::fs::make_absolute(ModuleMap);
1141 AddString(ModuleMap.str(), Record);
1144 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1146 // Primary module map file.
1147 addModMap(Map.getModuleMapFileForUniquing(WritingModule));
1149 // Additional module map files.
1150 if (auto *AdditionalModMaps = Map.getAdditionalModuleMapFiles(WritingModule)) {
1151 Record.push_back(AdditionalModMaps->size());
1152 for (const FileEntry *F : *AdditionalModMaps)
1155 Record.push_back(0);
1158 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1163 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1166 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1168 // Skip modules that weren't directly imported.
1169 if (!(*M)->isDirectlyImported())
1172 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1173 AddSourceLocation((*M)->ImportLoc, Record);
1174 Record.push_back((*M)->File->getSize());
1175 Record.push_back((*M)->File->getModificationTime());
1176 const std::string &FileName = (*M)->FileName;
1177 Record.push_back(FileName.size());
1178 Record.append(FileName.begin(), FileName.end());
1180 Stream.EmitRecord(IMPORTS, Record);
1183 // Language options.
1185 const LangOptions &LangOpts = Context.getLangOpts();
1186 #define LANGOPT(Name, Bits, Default, Description) \
1187 Record.push_back(LangOpts.Name);
1188 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1189 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1190 #include "clang/Basic/LangOptions.def"
1191 #define SANITIZER(NAME, ID) Record.push_back(LangOpts.Sanitize.ID);
1192 #include "clang/Basic/Sanitizers.def"
1194 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1195 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1197 Record.push_back(LangOpts.CurrentModule.size());
1198 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1201 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1202 for (CommentOptions::BlockCommandNamesTy::const_iterator
1203 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1204 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1206 AddString(*I, Record);
1208 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1210 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1214 const TargetInfo &Target = Context.getTargetInfo();
1215 const TargetOptions &TargetOpts = Target.getTargetOpts();
1216 AddString(TargetOpts.Triple, Record);
1217 AddString(TargetOpts.CPU, Record);
1218 AddString(TargetOpts.ABI, Record);
1219 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1220 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1221 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1223 Record.push_back(TargetOpts.Features.size());
1224 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1225 AddString(TargetOpts.Features[I], Record);
1227 Stream.EmitRecord(TARGET_OPTIONS, Record);
1229 // Diagnostic options.
1231 const DiagnosticOptions &DiagOpts
1232 = Context.getDiagnostics().getDiagnosticOptions();
1233 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1234 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1235 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1236 #include "clang/Basic/DiagnosticOptions.def"
1237 Record.push_back(DiagOpts.Warnings.size());
1238 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1239 AddString(DiagOpts.Warnings[I], Record);
1240 Record.push_back(DiagOpts.Remarks.size());
1241 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1242 AddString(DiagOpts.Remarks[I], Record);
1243 // Note: we don't serialize the log or serialization file names, because they
1244 // are generally transient files and will almost always be overridden.
1245 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1247 // File system options.
1249 const FileSystemOptions &FSOpts
1250 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1251 AddString(FSOpts.WorkingDir, Record);
1252 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1254 // Header search options.
1256 const HeaderSearchOptions &HSOpts
1257 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1258 AddString(HSOpts.Sysroot, Record);
1261 Record.push_back(HSOpts.UserEntries.size());
1262 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1263 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1264 AddString(Entry.Path, Record);
1265 Record.push_back(static_cast<unsigned>(Entry.Group));
1266 Record.push_back(Entry.IsFramework);
1267 Record.push_back(Entry.IgnoreSysRoot);
1270 // System header prefixes.
1271 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1272 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1273 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1274 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1277 AddString(HSOpts.ResourceDir, Record);
1278 AddString(HSOpts.ModuleCachePath, Record);
1279 AddString(HSOpts.ModuleUserBuildPath, Record);
1280 Record.push_back(HSOpts.DisableModuleHash);
1281 Record.push_back(HSOpts.UseBuiltinIncludes);
1282 Record.push_back(HSOpts.UseStandardSystemIncludes);
1283 Record.push_back(HSOpts.UseStandardCXXIncludes);
1284 Record.push_back(HSOpts.UseLibcxx);
1285 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1287 // Preprocessor options.
1289 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1291 // Macro definitions.
1292 Record.push_back(PPOpts.Macros.size());
1293 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1294 AddString(PPOpts.Macros[I].first, Record);
1295 Record.push_back(PPOpts.Macros[I].second);
1299 Record.push_back(PPOpts.Includes.size());
1300 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1301 AddString(PPOpts.Includes[I], Record);
1304 Record.push_back(PPOpts.MacroIncludes.size());
1305 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1306 AddString(PPOpts.MacroIncludes[I], Record);
1308 Record.push_back(PPOpts.UsePredefines);
1309 // Detailed record is important since it is used for the module cache hash.
1310 Record.push_back(PPOpts.DetailedRecord);
1311 AddString(PPOpts.ImplicitPCHInclude, Record);
1312 AddString(PPOpts.ImplicitPTHInclude, Record);
1313 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1314 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1316 // Original file name and file ID
1317 SourceManager &SM = Context.getSourceManager();
1318 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1319 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1320 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1321 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1322 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1323 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1325 SmallString<128> MainFilePath(MainFile->getName());
1327 llvm::sys::fs::make_absolute(MainFilePath);
1329 const char *MainFileNameStr = MainFilePath.c_str();
1330 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1333 Record.push_back(ORIGINAL_FILE);
1334 Record.push_back(SM.getMainFileID().getOpaqueValue());
1335 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1339 Record.push_back(SM.getMainFileID().getOpaqueValue());
1340 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1342 // Original PCH directory
1343 if (!OutputFile.empty() && OutputFile != "-") {
1344 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1345 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1346 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1347 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1349 SmallString<128> OutputPath(OutputFile);
1351 llvm::sys::fs::make_absolute(OutputPath);
1352 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1355 Record.push_back(ORIGINAL_PCH_DIR);
1356 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1359 WriteInputFiles(Context.SourceMgr,
1360 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1362 PP.getLangOpts().Modules);
1367 /// \brief An input file.
1368 struct InputFileEntry {
1369 const FileEntry *File;
1371 bool BufferOverridden;
1375 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1376 HeaderSearchOptions &HSOpts,
1379 using namespace llvm;
1380 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1383 // Create input-file abbreviation.
1384 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1385 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1386 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1387 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1388 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1389 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1390 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1391 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1393 // Get all ContentCache objects for files, sorted by whether the file is a
1394 // system one or not. System files go at the back, users files at the front.
1395 std::deque<InputFileEntry> SortedFiles;
1396 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1397 // Get this source location entry.
1398 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1399 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1401 // We only care about file entries that were not overridden.
1402 if (!SLoc->isFile())
1404 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1405 if (!Cache->OrigEntry)
1408 InputFileEntry Entry;
1409 Entry.File = Cache->OrigEntry;
1410 Entry.IsSystemFile = Cache->IsSystemFile;
1411 Entry.BufferOverridden = Cache->BufferOverridden;
1412 if (Cache->IsSystemFile)
1413 SortedFiles.push_back(Entry);
1415 SortedFiles.push_front(Entry);
1418 unsigned UserFilesNum = 0;
1419 // Write out all of the input files.
1420 std::vector<uint32_t> InputFileOffsets;
1421 for (std::deque<InputFileEntry>::iterator
1422 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
1423 const InputFileEntry &Entry = *I;
1425 uint32_t &InputFileID = InputFileIDs[Entry.File];
1426 if (InputFileID != 0)
1427 continue; // already recorded this file.
1429 // Record this entry's offset.
1430 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1432 InputFileID = InputFileOffsets.size();
1434 if (!Entry.IsSystemFile)
1438 Record.push_back(INPUT_FILE);
1439 Record.push_back(InputFileOffsets.size());
1441 // Emit size/modification time for this file.
1442 Record.push_back(Entry.File->getSize());
1443 Record.push_back(Entry.File->getModificationTime());
1445 // Whether this file was overridden.
1446 Record.push_back(Entry.BufferOverridden);
1448 // Turn the file name into an absolute path, if it isn't already.
1449 const char *Filename = Entry.File->getName();
1450 SmallString<128> FilePath(Filename);
1452 // Ask the file manager to fixup the relative path for us. This will
1453 // honor the working directory.
1454 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1456 // FIXME: This call to make_absolute shouldn't be necessary, the
1457 // call to FixupRelativePath should always return an absolute path.
1458 llvm::sys::fs::make_absolute(FilePath);
1459 Filename = FilePath.c_str();
1461 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1463 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1468 // Create input file offsets abbreviation.
1469 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1470 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1471 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1472 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1474 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1475 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1477 // Write input file offsets.
1479 Record.push_back(INPUT_FILE_OFFSETS);
1480 Record.push_back(InputFileOffsets.size());
1481 Record.push_back(UserFilesNum);
1482 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
1485 //===----------------------------------------------------------------------===//
1486 // Source Manager Serialization
1487 //===----------------------------------------------------------------------===//
1489 /// \brief Create an abbreviation for the SLocEntry that refers to a
1491 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1492 using namespace llvm;
1493 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1494 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1496 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1499 // FileEntry fields.
1500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1501 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1502 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1504 return Stream.EmitAbbrev(Abbrev);
1507 /// \brief Create an abbreviation for the SLocEntry that refers to a
1509 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1510 using namespace llvm;
1511 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1512 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1516 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1517 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1518 return Stream.EmitAbbrev(Abbrev);
1521 /// \brief Create an abbreviation for the SLocEntry that refers to a
1523 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1524 using namespace llvm;
1525 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1526 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1528 return Stream.EmitAbbrev(Abbrev);
1531 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1533 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1534 using namespace llvm;
1535 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1536 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1537 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1538 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1539 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1540 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1541 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1542 return Stream.EmitAbbrev(Abbrev);
1546 // Trait used for the on-disk hash table of header search information.
1547 class HeaderFileInfoTrait {
1549 const HeaderSearch &HS;
1551 // Keep track of the framework names we've used during serialization.
1552 SmallVector<char, 128> FrameworkStringData;
1553 llvm::StringMap<unsigned> FrameworkNameOffset;
1556 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1557 : Writer(Writer), HS(HS) { }
1560 const FileEntry *FE;
1561 const char *Filename;
1563 typedef const key_type &key_type_ref;
1565 typedef HeaderFileInfo data_type;
1566 typedef const data_type &data_type_ref;
1567 typedef unsigned hash_value_type;
1568 typedef unsigned offset_type;
1570 static hash_value_type ComputeHash(key_type_ref key) {
1571 // The hash is based only on size/time of the file, so that the reader can
1572 // match even when symlinking or excess path elements ("foo/../", "../")
1573 // change the form of the name. However, complete path is still the key.
1574 return llvm::hash_combine(key.FE->getSize(),
1575 key.FE->getModificationTime());
1578 std::pair<unsigned,unsigned>
1579 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1580 using namespace llvm::support;
1581 endian::Writer<little> Writer(Out);
1582 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1583 Writer.write<uint16_t>(KeyLen);
1584 unsigned DataLen = 1 + 2 + 4 + 4;
1585 if (Data.isModuleHeader)
1587 Writer.write<uint8_t>(DataLen);
1588 return std::make_pair(KeyLen, DataLen);
1591 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1592 using namespace llvm::support;
1593 endian::Writer<little> LE(Out);
1594 LE.write<uint64_t>(key.FE->getSize());
1596 LE.write<uint64_t>(key.FE->getModificationTime());
1598 Out.write(key.Filename, KeyLen);
1601 void EmitData(raw_ostream &Out, key_type_ref key,
1602 data_type_ref Data, unsigned DataLen) {
1603 using namespace llvm::support;
1604 endian::Writer<little> LE(Out);
1605 uint64_t Start = Out.tell(); (void)Start;
1607 unsigned char Flags = (Data.HeaderRole << 6)
1608 | (Data.isImport << 5)
1609 | (Data.isPragmaOnce << 4)
1610 | (Data.DirInfo << 2)
1611 | (Data.Resolved << 1)
1612 | Data.IndexHeaderMapHeader;
1613 LE.write<uint8_t>(Flags);
1614 LE.write<uint16_t>(Data.NumIncludes);
1616 if (!Data.ControllingMacro)
1617 LE.write<uint32_t>(Data.ControllingMacroID);
1619 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1621 unsigned Offset = 0;
1622 if (!Data.Framework.empty()) {
1623 // If this header refers into a framework, save the framework name.
1624 llvm::StringMap<unsigned>::iterator Pos
1625 = FrameworkNameOffset.find(Data.Framework);
1626 if (Pos == FrameworkNameOffset.end()) {
1627 Offset = FrameworkStringData.size() + 1;
1628 FrameworkStringData.append(Data.Framework.begin(),
1629 Data.Framework.end());
1630 FrameworkStringData.push_back(0);
1632 FrameworkNameOffset[Data.Framework] = Offset;
1634 Offset = Pos->second;
1636 LE.write<uint32_t>(Offset);
1638 if (Data.isModuleHeader) {
1639 Module *Mod = HS.findModuleForHeader(key.FE).getModule();
1640 LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod));
1643 assert(Out.tell() - Start == DataLen && "Wrong data length");
1646 const char *strings_begin() const { return FrameworkStringData.begin(); }
1647 const char *strings_end() const { return FrameworkStringData.end(); }
1649 } // end anonymous namespace
1651 /// \brief Write the header search block for the list of files that
1653 /// \param HS The header search structure to save.
1654 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1655 SmallVector<const FileEntry *, 16> FilesByUID;
1656 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1658 if (FilesByUID.size() > HS.header_file_size())
1659 FilesByUID.resize(HS.header_file_size());
1661 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1662 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1663 SmallVector<const char *, 4> SavedStrings;
1664 unsigned NumHeaderSearchEntries = 0;
1665 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1666 const FileEntry *File = FilesByUID[UID];
1670 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1671 // from the external source if it was not provided already.
1673 if (!HS.tryGetFileInfo(File, HFI) ||
1674 (HFI.External && Chain) ||
1675 (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
1678 // Turn the file name into an absolute path, if it isn't already.
1679 const char *Filename = File->getName();
1680 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1682 // If we performed any translation on the file name at all, we need to
1683 // save this string, since the generator will refer to it later.
1684 if (Filename != File->getName()) {
1685 Filename = strdup(Filename);
1686 SavedStrings.push_back(Filename);
1689 HeaderFileInfoTrait::key_type key = { File, Filename };
1690 Generator.insert(key, HFI, GeneratorTrait);
1691 ++NumHeaderSearchEntries;
1694 // Create the on-disk hash table in a buffer.
1695 SmallString<4096> TableData;
1696 uint32_t BucketOffset;
1698 using namespace llvm::support;
1699 llvm::raw_svector_ostream Out(TableData);
1700 // Make sure that no bucket is at offset 0
1701 endian::Writer<little>(Out).write<uint32_t>(0);
1702 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1705 // Create a blob abbreviation
1706 using namespace llvm;
1707 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1708 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1713 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1715 // Write the header search table
1717 Record.push_back(HEADER_SEARCH_TABLE);
1718 Record.push_back(BucketOffset);
1719 Record.push_back(NumHeaderSearchEntries);
1720 Record.push_back(TableData.size());
1721 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1722 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1724 // Free all of the strings we had to duplicate.
1725 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1726 free(const_cast<char *>(SavedStrings[I]));
1729 /// \brief Writes the block containing the serialized form of the
1732 /// TODO: We should probably use an on-disk hash table (stored in a
1733 /// blob), indexed based on the file name, so that we only create
1734 /// entries for files that we actually need. In the common case (no
1735 /// errors), we probably won't have to create file entries for any of
1736 /// the files in the AST.
1737 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1738 const Preprocessor &PP,
1739 StringRef isysroot) {
1742 // Enter the source manager block.
1743 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1745 // Abbreviations for the various kinds of source-location entries.
1746 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1747 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1748 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1749 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1751 // Write out the source location entry table. We skip the first
1752 // entry, which is always the same dummy entry.
1753 std::vector<uint32_t> SLocEntryOffsets;
1754 RecordData PreloadSLocs;
1755 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1756 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1758 // Get this source location entry.
1759 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1760 FileID FID = FileID::get(I);
1761 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1763 // Record the offset of this source-location entry.
1764 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1766 // Figure out which record code to use.
1768 if (SLoc->isFile()) {
1769 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1770 if (Cache->OrigEntry) {
1771 Code = SM_SLOC_FILE_ENTRY;
1773 Code = SM_SLOC_BUFFER_ENTRY;
1775 Code = SM_SLOC_EXPANSION_ENTRY;
1777 Record.push_back(Code);
1779 // Starting offset of this entry within this module, so skip the dummy.
1780 Record.push_back(SLoc->getOffset() - 2);
1781 if (SLoc->isFile()) {
1782 const SrcMgr::FileInfo &File = SLoc->getFile();
1783 Record.push_back(File.getIncludeLoc().getRawEncoding());
1784 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1785 Record.push_back(File.hasLineDirectives());
1787 const SrcMgr::ContentCache *Content = File.getContentCache();
1788 if (Content->OrigEntry) {
1789 assert(Content->OrigEntry == Content->ContentsEntry &&
1790 "Writing to AST an overridden file is not supported");
1792 // The source location entry is a file. Emit input file ID.
1793 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1794 Record.push_back(InputFileIDs[Content->OrigEntry]);
1796 Record.push_back(File.NumCreatedFIDs);
1798 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1799 if (FDI != FileDeclIDs.end()) {
1800 Record.push_back(FDI->second->FirstDeclIndex);
1801 Record.push_back(FDI->second->DeclIDs.size());
1803 Record.push_back(0);
1804 Record.push_back(0);
1807 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1809 if (Content->BufferOverridden) {
1811 Record.push_back(SM_SLOC_BUFFER_BLOB);
1812 const llvm::MemoryBuffer *Buffer
1813 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1814 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1815 StringRef(Buffer->getBufferStart(),
1816 Buffer->getBufferSize() + 1));
1819 // The source location entry is a buffer. The blob associated
1820 // with this entry contains the contents of the buffer.
1822 // We add one to the size so that we capture the trailing NULL
1823 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1824 // the reader side).
1825 const llvm::MemoryBuffer *Buffer
1826 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1827 const char *Name = Buffer->getBufferIdentifier();
1828 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1829 StringRef(Name, strlen(Name) + 1));
1831 Record.push_back(SM_SLOC_BUFFER_BLOB);
1832 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1833 StringRef(Buffer->getBufferStart(),
1834 Buffer->getBufferSize() + 1));
1836 if (strcmp(Name, "<built-in>") == 0) {
1837 PreloadSLocs.push_back(SLocEntryOffsets.size());
1841 // The source location entry is a macro expansion.
1842 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1843 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1844 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1845 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1846 : Expansion.getExpansionLocEnd().getRawEncoding());
1848 // Compute the token length for this macro expansion.
1849 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1851 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1852 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1853 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1859 if (SLocEntryOffsets.empty())
1862 // Write the source-location offsets table into the AST block. This
1863 // table is used for lazily loading source-location information.
1864 using namespace llvm;
1865 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1866 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1867 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1870 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1873 Record.push_back(SOURCE_LOCATION_OFFSETS);
1874 Record.push_back(SLocEntryOffsets.size());
1875 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1876 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1878 // Write the source location entry preloads array, telling the AST
1879 // reader which source locations entries it should load eagerly.
1880 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1882 // Write the line table. It depends on remapping working, so it must come
1883 // after the source location offsets.
1884 if (SourceMgr.hasLineTable()) {
1885 LineTableInfo &LineTable = SourceMgr.getLineTable();
1888 // Emit the file names
1889 Record.push_back(LineTable.getNumFilenames());
1890 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1891 // Emit the file name
1892 const char *Filename = LineTable.getFilename(I);
1893 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1894 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1895 Record.push_back(FilenameLen);
1897 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1900 // Emit the line entries
1901 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1903 // Only emit entries for local files.
1904 if (L->first.ID < 0)
1908 Record.push_back(L->first.ID);
1910 // Emit the line entries
1911 Record.push_back(L->second.size());
1912 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1913 LEEnd = L->second.end();
1914 LE != LEEnd; ++LE) {
1915 Record.push_back(LE->FileOffset);
1916 Record.push_back(LE->LineNo);
1917 Record.push_back(LE->FilenameID);
1918 Record.push_back((unsigned)LE->FileKind);
1919 Record.push_back(LE->IncludeOffset);
1922 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1926 //===----------------------------------------------------------------------===//
1927 // Preprocessor Serialization
1928 //===----------------------------------------------------------------------===//
1931 class ASTMacroTableTrait {
1933 typedef IdentID key_type;
1934 typedef key_type key_type_ref;
1937 uint32_t MacroDirectivesOffset;
1940 typedef Data data_type;
1941 typedef const data_type &data_type_ref;
1942 typedef unsigned hash_value_type;
1943 typedef unsigned offset_type;
1945 static hash_value_type ComputeHash(IdentID IdID) {
1946 return llvm::hash_value(IdID);
1949 std::pair<unsigned,unsigned>
1950 static EmitKeyDataLength(raw_ostream& Out,
1951 key_type_ref Key, data_type_ref Data) {
1952 unsigned KeyLen = 4; // IdentID.
1953 unsigned DataLen = 4; // MacroDirectivesOffset.
1954 return std::make_pair(KeyLen, DataLen);
1957 static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
1958 using namespace llvm::support;
1959 endian::Writer<little>(Out).write<uint32_t>(Key);
1962 static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
1964 using namespace llvm::support;
1965 endian::Writer<little>(Out).write<uint32_t>(Data.MacroDirectivesOffset);
1968 } // end anonymous namespace
1970 static int compareMacroDirectives(
1971 const std::pair<const IdentifierInfo *, MacroDirective *> *X,
1972 const std::pair<const IdentifierInfo *, MacroDirective *> *Y) {
1973 return X->first->getName().compare(Y->first->getName());
1976 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1977 const Preprocessor &PP) {
1978 if (MacroInfo *MI = MD->getMacroInfo())
1979 if (MI->isBuiltinMacro())
1983 // Re-export any imported directives.
1984 if (MD->isImported())
1987 SourceLocation Loc = MD->getLocation();
1988 if (Loc.isInvalid())
1990 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1997 /// \brief Writes the block containing the serialized form of the
2000 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2001 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2003 WritePreprocessorDetail(*PPRec);
2007 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2008 if (PP.getCounterValue() != 0) {
2009 Record.push_back(PP.getCounterValue());
2010 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2014 // Enter the preprocessor block.
2015 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2017 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2018 // FIXME: use diagnostics subsystem for localization etc.
2019 if (PP.SawDateOrTime())
2020 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
2023 // Loop over all the macro directives that are live at the end of the file,
2024 // emitting each to the PP section.
2026 // Construct the list of macro directives that need to be serialized.
2027 SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2>
2029 for (Preprocessor::macro_iterator
2030 I = PP.macro_begin(/*IncludeExternalMacros=*/false),
2031 E = PP.macro_end(/*IncludeExternalMacros=*/false);
2033 MacroDirectives.push_back(std::make_pair(I->first, I->second));
2036 // Sort the set of macro definitions that need to be serialized by the
2037 // name of the macro, to provide a stable ordering.
2038 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(),
2039 &compareMacroDirectives);
2041 llvm::OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator;
2043 // Emit the macro directives as a list and associate the offset with the
2044 // identifier they belong to.
2045 for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) {
2046 const IdentifierInfo *Name = MacroDirectives[I].first;
2047 uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo();
2048 MacroDirective *MD = MacroDirectives[I].second;
2050 // If the macro or identifier need no updates, don't write the macro history
2052 // FIXME: Chain the macro history instead of re-writing it.
2053 if (MD->isFromPCH() &&
2054 Name->isFromAST() && !Name->hasChangedSinceDeserialization())
2057 // Emit the macro directives in reverse source order.
2058 for (; MD; MD = MD->getPrevious()) {
2059 if (shouldIgnoreMacro(MD, IsModule, PP))
2062 AddSourceLocation(MD->getLocation(), Record);
2063 Record.push_back(MD->getKind());
2064 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2065 MacroID InfoID = getMacroRef(DefMD->getInfo(), Name);
2066 Record.push_back(InfoID);
2067 Record.push_back(DefMD->getOwningModuleID());
2068 Record.push_back(DefMD->isAmbiguous());
2069 } else if (auto *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
2070 Record.push_back(UndefMD->getOwningModuleID());
2072 auto *VisMD = cast<VisibilityMacroDirective>(MD);
2073 Record.push_back(VisMD->isPublic());
2076 if (MD->isImported()) {
2077 auto Overrides = MD->getOverriddenModules();
2078 Record.push_back(Overrides.size());
2079 for (auto Override : Overrides)
2080 Record.push_back(Override);
2086 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2089 IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset;
2091 IdentID NameID = getIdentifierRef(Name);
2092 ASTMacroTableTrait::Data data;
2093 data.MacroDirectivesOffset = MacroDirectiveOffset;
2094 Generator.insert(NameID, data);
2097 /// \brief Offsets of each of the macros into the bitstream, indexed by
2098 /// the local macro ID
2100 /// For each identifier that is associated with a macro, this map
2101 /// provides the offset into the bitstream where that macro is
2103 std::vector<uint32_t> MacroOffsets;
2105 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2106 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2107 MacroInfo *MI = MacroInfosToEmit[I].MI;
2108 MacroID ID = MacroInfosToEmit[I].ID;
2110 if (ID < FirstMacroID) {
2111 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2115 // Record the local offset of this macro.
2116 unsigned Index = ID - FirstMacroID;
2117 if (Index == MacroOffsets.size())
2118 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2120 if (Index > MacroOffsets.size())
2121 MacroOffsets.resize(Index + 1);
2123 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2126 AddIdentifierRef(Name, Record);
2127 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2128 AddSourceLocation(MI->getDefinitionLoc(), Record);
2129 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2130 Record.push_back(MI->isUsed());
2131 Record.push_back(MI->isUsedForHeaderGuard());
2133 if (MI->isObjectLike()) {
2134 Code = PP_MACRO_OBJECT_LIKE;
2136 Code = PP_MACRO_FUNCTION_LIKE;
2138 Record.push_back(MI->isC99Varargs());
2139 Record.push_back(MI->isGNUVarargs());
2140 Record.push_back(MI->hasCommaPasting());
2141 Record.push_back(MI->getNumArgs());
2142 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
2144 AddIdentifierRef(*I, Record);
2147 // If we have a detailed preprocessing record, record the macro definition
2148 // ID that corresponds to this macro.
2150 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2152 Stream.EmitRecord(Code, Record);
2155 // Emit the tokens array.
2156 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2157 // Note that we know that the preprocessor does not have any annotation
2158 // tokens in it because they are created by the parser, and thus can't
2159 // be in a macro definition.
2160 const Token &Tok = MI->getReplacementToken(TokNo);
2161 AddToken(Tok, Record);
2162 Stream.EmitRecord(PP_TOKEN, Record);
2170 // Create the on-disk hash table in a buffer.
2171 SmallString<4096> MacroTable;
2172 uint32_t BucketOffset;
2174 using namespace llvm::support;
2175 llvm::raw_svector_ostream Out(MacroTable);
2176 // Make sure that no bucket is at offset 0
2177 endian::Writer<little>(Out).write<uint32_t>(0);
2178 BucketOffset = Generator.Emit(Out);
2181 // Write the macro table
2182 using namespace llvm;
2183 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2184 Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE));
2185 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2186 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2187 unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev);
2189 Record.push_back(MACRO_TABLE);
2190 Record.push_back(BucketOffset);
2191 Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str());
2194 // Write the offsets table for macro IDs.
2195 using namespace llvm;
2196 Abbrev = new BitCodeAbbrev();
2197 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2198 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2200 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2202 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2204 Record.push_back(MACRO_OFFSET);
2205 Record.push_back(MacroOffsets.size());
2206 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2207 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2208 data(MacroOffsets));
2211 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2212 if (PPRec.local_begin() == PPRec.local_end())
2215 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2217 // Enter the preprocessor block.
2218 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2220 // If the preprocessor has a preprocessing record, emit it.
2221 unsigned NumPreprocessingRecords = 0;
2222 using namespace llvm;
2224 // Set up the abbreviation for
2225 unsigned InclusionAbbrev = 0;
2227 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2228 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2229 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2230 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2233 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2234 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2237 unsigned FirstPreprocessorEntityID
2238 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2239 + NUM_PREDEF_PP_ENTITY_IDS;
2240 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2242 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2243 EEnd = PPRec.local_end();
2245 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2248 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2249 Stream.GetCurrentBitNo()));
2251 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
2252 // Record this macro definition's ID.
2253 MacroDefinitions[MD] = NextPreprocessorEntityID;
2255 AddIdentifierRef(MD->getName(), Record);
2256 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2260 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
2261 Record.push_back(ME->isBuiltinMacro());
2262 if (ME->isBuiltinMacro())
2263 AddIdentifierRef(ME->getName(), Record);
2265 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2266 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2270 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2271 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2272 Record.push_back(ID->getFileName().size());
2273 Record.push_back(ID->wasInQuotes());
2274 Record.push_back(static_cast<unsigned>(ID->getKind()));
2275 Record.push_back(ID->importedModule());
2276 SmallString<64> Buffer;
2277 Buffer += ID->getFileName();
2278 // Check that the FileEntry is not null because it was not resolved and
2279 // we create a PCH even with compiler errors.
2281 Buffer += ID->getFile()->getName();
2282 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2286 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2290 // Write the offsets table for the preprocessing record.
2291 if (NumPreprocessingRecords > 0) {
2292 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2294 // Write the offsets table for identifier IDs.
2295 using namespace llvm;
2296 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2297 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2298 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2299 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2300 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2303 Record.push_back(PPD_ENTITIES_OFFSETS);
2304 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2305 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2306 data(PreprocessedEntityOffsets));
2310 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2311 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2312 if (Known != SubmoduleIDs.end())
2313 return Known->second;
2315 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2318 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2322 llvm::DenseMap<Module *, unsigned>::const_iterator
2323 Known = SubmoduleIDs.find(Mod);
2324 if (Known != SubmoduleIDs.end())
2325 return Known->second;
2330 /// \brief Compute the number of modules within the given tree (including the
2332 static unsigned getNumberOfModules(Module *Mod) {
2333 unsigned ChildModules = 0;
2334 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2335 SubEnd = Mod->submodule_end();
2336 Sub != SubEnd; ++Sub)
2337 ChildModules += getNumberOfModules(*Sub);
2339 return ChildModules + 1;
2342 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2343 // Determine the dependencies of our module and each of it's submodules.
2344 // FIXME: This feels like it belongs somewhere else, but there are no
2345 // other consumers of this information.
2346 SourceManager &SrcMgr = PP->getSourceManager();
2347 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2348 for (const auto *I : Context->local_imports()) {
2349 if (Module *ImportedFrom
2350 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2352 ImportedFrom->Imports.push_back(I->getImportedModule());
2356 // Enter the submodule description block.
2357 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/4);
2359 // Write the abbreviations needed for the submodules block.
2360 using namespace llvm;
2361 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2362 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2364 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2365 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2374 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2376 Abbrev = new BitCodeAbbrev();
2377 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2379 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2381 Abbrev = new BitCodeAbbrev();
2382 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2384 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2386 Abbrev = new BitCodeAbbrev();
2387 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2388 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2389 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2391 Abbrev = new BitCodeAbbrev();
2392 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2394 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2396 Abbrev = new BitCodeAbbrev();
2397 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2400 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2402 Abbrev = new BitCodeAbbrev();
2403 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2404 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2405 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2407 Abbrev = new BitCodeAbbrev();
2408 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2409 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2410 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2412 Abbrev = new BitCodeAbbrev();
2413 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2415 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2416 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2418 Abbrev = new BitCodeAbbrev();
2419 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2421 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2423 Abbrev = new BitCodeAbbrev();
2424 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2427 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2429 // Write the submodule metadata block.
2431 Record.push_back(getNumberOfModules(WritingModule));
2432 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2433 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2435 // Write all of the submodules.
2436 std::queue<Module *> Q;
2437 Q.push(WritingModule);
2438 while (!Q.empty()) {
2439 Module *Mod = Q.front();
2441 unsigned ID = getSubmoduleID(Mod);
2443 // Emit the definition of the block.
2445 Record.push_back(SUBMODULE_DEFINITION);
2446 Record.push_back(ID);
2448 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2449 Record.push_back(SubmoduleIDs[Mod->Parent]);
2451 Record.push_back(0);
2453 Record.push_back(Mod->IsFramework);
2454 Record.push_back(Mod->IsExplicit);
2455 Record.push_back(Mod->IsSystem);
2456 Record.push_back(Mod->IsExternC);
2457 Record.push_back(Mod->InferSubmodules);
2458 Record.push_back(Mod->InferExplicitSubmodules);
2459 Record.push_back(Mod->InferExportWildcard);
2460 Record.push_back(Mod->ConfigMacrosExhaustive);
2461 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2463 // Emit the requirements.
2464 for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
2466 Record.push_back(SUBMODULE_REQUIRES);
2467 Record.push_back(Mod->Requirements[I].second);
2468 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2469 Mod->Requirements[I].first);
2472 // Emit the umbrella header, if there is one.
2473 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
2475 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2476 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2477 UmbrellaHeader->getName());
2478 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2480 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2481 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2482 UmbrellaDir->getName());
2485 // Emit the headers.
2486 for (unsigned I = 0, N = Mod->NormalHeaders.size(); I != N; ++I) {
2488 Record.push_back(SUBMODULE_HEADER);
2489 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2490 Mod->NormalHeaders[I]->getName());
2492 // Emit the excluded headers.
2493 for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2495 Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2496 Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2497 Mod->ExcludedHeaders[I]->getName());
2499 // Emit the private headers.
2500 for (unsigned I = 0, N = Mod->PrivateHeaders.size(); I != N; ++I) {
2502 Record.push_back(SUBMODULE_PRIVATE_HEADER);
2503 Stream.EmitRecordWithBlob(PrivateHeaderAbbrev, Record,
2504 Mod->PrivateHeaders[I]->getName());
2506 ArrayRef<const FileEntry *>
2507 TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2508 for (unsigned I = 0, N = TopHeaders.size(); I != N; ++I) {
2510 Record.push_back(SUBMODULE_TOPHEADER);
2511 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
2512 TopHeaders[I]->getName());
2515 // Emit the imports.
2516 if (!Mod->Imports.empty()) {
2518 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2519 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2520 assert(ImportedID && "Unknown submodule!");
2521 Record.push_back(ImportedID);
2523 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2526 // Emit the exports.
2527 if (!Mod->Exports.empty()) {
2529 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2530 if (Module *Exported = Mod->Exports[I].getPointer()) {
2531 unsigned ExportedID = SubmoduleIDs[Exported];
2532 assert(ExportedID > 0 && "Unknown submodule ID?");
2533 Record.push_back(ExportedID);
2535 Record.push_back(0);
2538 Record.push_back(Mod->Exports[I].getInt());
2540 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2543 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2544 // Might be unnecessary as use declarations are only used to build the
2547 // Emit the link libraries.
2548 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2550 Record.push_back(SUBMODULE_LINK_LIBRARY);
2551 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2552 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2553 Mod->LinkLibraries[I].Library);
2556 // Emit the conflicts.
2557 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2559 Record.push_back(SUBMODULE_CONFLICT);
2560 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2561 assert(OtherID && "Unknown submodule!");
2562 Record.push_back(OtherID);
2563 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2564 Mod->Conflicts[I].Message);
2567 // Emit the configuration macros.
2568 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2570 Record.push_back(SUBMODULE_CONFIG_MACRO);
2571 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2572 Mod->ConfigMacros[I]);
2575 // Queue up the submodules of this module.
2576 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2577 SubEnd = Mod->submodule_end();
2578 Sub != SubEnd; ++Sub)
2584 assert((NextSubmoduleID - FirstSubmoduleID
2585 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2588 serialization::SubmoduleID
2589 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2590 if (Loc.isInvalid() || !WritingModule)
2591 return 0; // No submodule
2593 // Find the module that owns this location.
2594 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2596 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2600 // Check whether this submodule is part of our own module.
2601 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2604 return getSubmoduleID(OwningMod);
2607 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2609 // Make sure set diagnostic pragmas don't affect the translation unit that
2610 // imports the module.
2611 // FIXME: Make diagnostic pragma sections work properly with modules.
2615 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2617 unsigned CurrID = 0;
2618 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2620 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2621 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2623 const DiagnosticsEngine::DiagStatePoint &point = *I;
2624 if (point.Loc.isInvalid())
2627 Record.push_back(point.Loc.getRawEncoding());
2628 unsigned &DiagStateID = DiagStateIDMap[point.State];
2629 Record.push_back(DiagStateID);
2631 if (DiagStateID == 0) {
2632 DiagStateID = ++CurrID;
2633 for (DiagnosticsEngine::DiagState::const_iterator
2634 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2635 if (I->second.isPragma()) {
2636 Record.push_back(I->first);
2637 Record.push_back((unsigned)I->second.getSeverity());
2640 Record.push_back(-1); // mark the end of the diag/map pairs for this
2645 if (!Record.empty())
2646 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2649 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2650 if (CXXBaseSpecifiersOffsets.empty())
2655 // Create a blob abbreviation for the C++ base specifiers offsets.
2656 using namespace llvm;
2658 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2659 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2662 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2664 // Write the base specifier offsets table.
2666 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2667 Record.push_back(CXXBaseSpecifiersOffsets.size());
2668 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2669 data(CXXBaseSpecifiersOffsets));
2672 //===----------------------------------------------------------------------===//
2673 // Type Serialization
2674 //===----------------------------------------------------------------------===//
2676 /// \brief Write the representation of a type to the AST stream.
2677 void ASTWriter::WriteType(QualType T) {
2678 TypeIdx &Idx = TypeIdxs[T];
2679 if (Idx.getIndex() == 0) // we haven't seen this type before.
2680 Idx = TypeIdx(NextTypeID++);
2682 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2684 // Record the offset for this type.
2685 unsigned Index = Idx.getIndex() - FirstTypeID;
2686 if (TypeOffsets.size() == Index)
2687 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2688 else if (TypeOffsets.size() < Index) {
2689 TypeOffsets.resize(Index + 1);
2690 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2695 // Emit the type's representation.
2696 ASTTypeWriter W(*this, Record);
2699 if (T.hasLocalNonFastQualifiers()) {
2700 Qualifiers Qs = T.getLocalQualifiers();
2701 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2702 Record.push_back(Qs.getAsOpaqueValue());
2703 W.Code = TYPE_EXT_QUAL;
2704 W.AbbrevToUse = TypeExtQualAbbrev;
2706 switch (T->getTypeClass()) {
2707 // For all of the concrete, non-dependent types, call the
2708 // appropriate visitor function.
2709 #define TYPE(Class, Base) \
2710 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2711 #define ABSTRACT_TYPE(Class, Base)
2712 #include "clang/AST/TypeNodes.def"
2716 // Emit the serialized record.
2717 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
2719 // Flush any expressions that were written as part of this type.
2723 //===----------------------------------------------------------------------===//
2724 // Declaration Serialization
2725 //===----------------------------------------------------------------------===//
2727 /// \brief Write the block containing all of the declaration IDs
2728 /// lexically declared within the given DeclContext.
2730 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2731 /// bistream, or 0 if no block was written.
2732 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2734 if (DC->decls_empty())
2737 uint64_t Offset = Stream.GetCurrentBitNo();
2739 Record.push_back(DECL_CONTEXT_LEXICAL);
2740 SmallVector<KindDeclIDPair, 64> Decls;
2741 for (const auto *D : DC->decls())
2742 Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D)));
2744 ++NumLexicalDeclContexts;
2745 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2749 void ASTWriter::WriteTypeDeclOffsets() {
2750 using namespace llvm;
2753 // Write the type offsets array
2754 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2755 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2756 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2759 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2761 Record.push_back(TYPE_OFFSET);
2762 Record.push_back(TypeOffsets.size());
2763 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2764 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2766 // Write the declaration offsets array
2767 Abbrev = new BitCodeAbbrev();
2768 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2769 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2770 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2772 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2774 Record.push_back(DECL_OFFSET);
2775 Record.push_back(DeclOffsets.size());
2776 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2777 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2780 void ASTWriter::WriteFileDeclIDsMap() {
2781 using namespace llvm;
2784 // Join the vectors of DeclIDs from all files.
2785 SmallVector<DeclID, 256> FileSortedIDs;
2786 for (FileDeclIDsTy::iterator
2787 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2788 DeclIDInFileInfo &Info = *FI->second;
2789 Info.FirstDeclIndex = FileSortedIDs.size();
2790 for (LocDeclIDsTy::iterator
2791 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2792 FileSortedIDs.push_back(DI->second);
2795 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2796 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2797 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2799 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2800 Record.push_back(FILE_SORTED_DECLS);
2801 Record.push_back(FileSortedIDs.size());
2802 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2805 void ASTWriter::WriteComments() {
2806 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2807 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2809 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2810 E = RawComments.end();
2813 AddSourceRange((*I)->getSourceRange(), Record);
2814 Record.push_back((*I)->getKind());
2815 Record.push_back((*I)->isTrailingComment());
2816 Record.push_back((*I)->isAlmostTrailingComment());
2817 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2822 //===----------------------------------------------------------------------===//
2823 // Global Method Pool and Selector Serialization
2824 //===----------------------------------------------------------------------===//
2827 // Trait used for the on-disk hash table used in the method pool.
2828 class ASTMethodPoolTrait {
2832 typedef Selector key_type;
2833 typedef key_type key_type_ref;
2837 ObjCMethodList Instance, Factory;
2839 typedef const data_type& data_type_ref;
2841 typedef unsigned hash_value_type;
2842 typedef unsigned offset_type;
2844 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2846 static hash_value_type ComputeHash(Selector Sel) {
2847 return serialization::ComputeHash(Sel);
2850 std::pair<unsigned,unsigned>
2851 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2852 data_type_ref Methods) {
2853 using namespace llvm::support;
2854 endian::Writer<little> LE(Out);
2855 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2856 LE.write<uint16_t>(KeyLen);
2857 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2858 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2859 Method = Method->getNext())
2862 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2863 Method = Method->getNext())
2866 LE.write<uint16_t>(DataLen);
2867 return std::make_pair(KeyLen, DataLen);
2870 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2871 using namespace llvm::support;
2872 endian::Writer<little> LE(Out);
2873 uint64_t Start = Out.tell();
2874 assert((Start >> 32) == 0 && "Selector key offset too large");
2875 Writer.SetSelectorOffset(Sel, Start);
2876 unsigned N = Sel.getNumArgs();
2877 LE.write<uint16_t>(N);
2880 for (unsigned I = 0; I != N; ++I)
2882 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2885 void EmitData(raw_ostream& Out, key_type_ref,
2886 data_type_ref Methods, unsigned DataLen) {
2887 using namespace llvm::support;
2888 endian::Writer<little> LE(Out);
2889 uint64_t Start = Out.tell(); (void)Start;
2890 LE.write<uint32_t>(Methods.ID);
2891 unsigned NumInstanceMethods = 0;
2892 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2893 Method = Method->getNext())
2895 ++NumInstanceMethods;
2897 unsigned NumFactoryMethods = 0;
2898 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2899 Method = Method->getNext())
2901 ++NumFactoryMethods;
2903 unsigned InstanceBits = Methods.Instance.getBits();
2904 assert(InstanceBits < 4);
2905 unsigned NumInstanceMethodsAndBits =
2906 (NumInstanceMethods << 2) | InstanceBits;
2907 unsigned FactoryBits = Methods.Factory.getBits();
2908 assert(FactoryBits < 4);
2909 unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
2910 LE.write<uint16_t>(NumInstanceMethodsAndBits);
2911 LE.write<uint16_t>(NumFactoryMethodsAndBits);
2912 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2913 Method = Method->getNext())
2915 LE.write<uint32_t>(Writer.getDeclID(Method->Method));
2916 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2917 Method = Method->getNext())
2919 LE.write<uint32_t>(Writer.getDeclID(Method->Method));
2921 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2924 } // end anonymous namespace
2926 /// \brief Write ObjC data: selectors and the method pool.
2928 /// The method pool contains both instance and factory methods, stored
2929 /// in an on-disk hash table indexed by the selector. The hash table also
2930 /// contains an empty entry for every other selector known to Sema.
2931 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2932 using namespace llvm;
2934 // Do we have to do anything at all?
2935 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2937 unsigned NumTableEntries = 0;
2938 // Create and write out the blob that contains selectors and the method pool.
2940 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2941 ASTMethodPoolTrait Trait(*this);
2943 // Create the on-disk hash table representation. We walk through every
2944 // selector we've seen and look it up in the method pool.
2945 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2946 for (llvm::DenseMap<Selector, SelectorID>::iterator
2947 I = SelectorIDs.begin(), E = SelectorIDs.end();
2949 Selector S = I->first;
2950 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2951 ASTMethodPoolTrait::data_type Data = {
2956 if (F != SemaRef.MethodPool.end()) {
2957 Data.Instance = F->second.first;
2958 Data.Factory = F->second.second;
2960 // Only write this selector if it's not in an existing AST or something
2962 if (Chain && I->second < FirstSelectorID) {
2963 // Selector already exists. Did it change?
2964 bool changed = false;
2965 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2967 if (!M->Method->isFromASTFile())
2970 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2972 if (!M->Method->isFromASTFile())
2977 } else if (Data.Instance.Method || Data.Factory.Method) {
2978 // A new method pool entry.
2981 Generator.insert(S, Data, Trait);
2984 // Create the on-disk hash table in a buffer.
2985 SmallString<4096> MethodPool;
2986 uint32_t BucketOffset;
2988 using namespace llvm::support;
2989 ASTMethodPoolTrait Trait(*this);
2990 llvm::raw_svector_ostream Out(MethodPool);
2991 // Make sure that no bucket is at offset 0
2992 endian::Writer<little>(Out).write<uint32_t>(0);
2993 BucketOffset = Generator.Emit(Out, Trait);
2996 // Create a blob abbreviation
2997 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2998 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2999 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3000 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3001 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3002 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3004 // Write the method pool
3006 Record.push_back(METHOD_POOL);
3007 Record.push_back(BucketOffset);
3008 Record.push_back(NumTableEntries);
3009 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
3011 // Create a blob abbreviation for the selector table offsets.
3012 Abbrev = new BitCodeAbbrev();
3013 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3014 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3015 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3016 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3017 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3019 // Write the selector offsets table.
3021 Record.push_back(SELECTOR_OFFSETS);
3022 Record.push_back(SelectorOffsets.size());
3023 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
3024 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3025 data(SelectorOffsets));
3029 /// \brief Write the selectors referenced in @selector expression into AST file.
3030 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3031 using namespace llvm;
3032 if (SemaRef.ReferencedSelectors.empty())
3037 // Note: this writes out all references even for a dependent AST. But it is
3038 // very tricky to fix, and given that @selector shouldn't really appear in
3039 // headers, probably not worth it. It's not a correctness issue.
3040 for (DenseMap<Selector, SourceLocation>::iterator S =
3041 SemaRef.ReferencedSelectors.begin(),
3042 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
3043 Selector Sel = (*S).first;
3044 SourceLocation Loc = (*S).second;
3045 AddSelectorRef(Sel, Record);
3046 AddSourceLocation(Loc, Record);
3048 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
3051 //===----------------------------------------------------------------------===//
3052 // Identifier Table Serialization
3053 //===----------------------------------------------------------------------===//
3056 class ASTIdentifierTableTrait {
3059 IdentifierResolver &IdResolver;
3062 /// \brief Determines whether this is an "interesting" identifier
3063 /// that needs a full IdentifierInfo structure written into the hash
3065 bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) {
3066 if (II->isPoisoned() ||
3067 II->isExtensionToken() ||
3068 II->getObjCOrBuiltinID() ||
3069 II->hasRevertedTokenIDToIdentifier() ||
3070 II->getFETokenInfo<void>())
3073 return hadMacroDefinition(II, Macro);
3076 bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) {
3077 if (!II->hadMacroDefinition())
3080 if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) {
3082 return !shouldIgnoreMacro(Macro, IsModule, PP);
3085 if (getFirstPublicSubmoduleMacro(Macro, State))
3092 enum class SubmoduleMacroState {
3093 /// We've seen nothing about this macro.
3095 /// We've seen a public visibility directive.
3097 /// We've either exported a macro for this module or found that the
3098 /// module's definition of this macro is private.
3101 typedef llvm::DenseMap<SubmoduleID, SubmoduleMacroState> MacroState;
3104 getFirstPublicSubmoduleMacro(MacroDirective *MD, MacroState &State) {
3105 if (MacroDirective *NextMD = getPublicSubmoduleMacro(MD, State))
3111 getNextPublicSubmoduleMacro(MacroDirective *MD, MacroState &State) {
3112 if (MacroDirective *NextMD =
3113 getPublicSubmoduleMacro(MD->getPrevious(), State))
3118 /// \brief Traverses the macro directives history and returns the next
3119 /// public macro definition or undefinition that has not been found so far.
3121 /// A macro that is defined in submodule A and undefined in submodule B
3122 /// will still be considered as defined/exported from submodule A.
3123 MacroDirective *getPublicSubmoduleMacro(MacroDirective *MD,
3124 MacroState &State) {
3128 Optional<bool> IsPublic;
3129 for (; MD; MD = MD->getPrevious()) {
3130 // Once we hit an ignored macro, we're done: the rest of the chain
3131 // will all be ignored macros.
3132 if (shouldIgnoreMacro(MD, IsModule, PP))
3135 // If this macro was imported, re-export it.
3136 if (MD->isImported())
3139 SubmoduleID ModID = getSubmoduleID(MD);
3140 auto &S = State[ModID];
3141 assert(ModID && "found macro in no submodule");
3143 if (S == SubmoduleMacroState::Done)
3146 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
3147 // The latest visibility directive for a name in a submodule affects all
3148 // the directives that come before it.
3149 if (S == SubmoduleMacroState::None)
3150 S = VisMD->isPublic() ? SubmoduleMacroState::Public
3151 : SubmoduleMacroState::Done;
3153 S = SubmoduleMacroState::Done;
3161 ArrayRef<SubmoduleID>
3162 getOverriddenSubmodules(MacroDirective *MD,
3163 SmallVectorImpl<SubmoduleID> &ScratchSpace) {
3164 assert(!isa<VisibilityMacroDirective>(MD) &&
3165 "only #define and #undef can override");
3166 if (MD->isImported())
3167 return MD->getOverriddenModules();
3169 ScratchSpace.clear();
3170 SubmoduleID ModID = getSubmoduleID(MD);
3171 for (MD = MD->getPrevious(); MD; MD = MD->getPrevious()) {
3172 if (shouldIgnoreMacro(MD, IsModule, PP))
3175 // If this is a definition from a submodule import, that submodule's
3176 // definition is overridden by the definition or undefinition that we
3178 if (MD->isImported()) {
3179 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3180 SubmoduleID DefModuleID = DefMD->getInfo()->getOwningModuleID();
3181 assert(DefModuleID && "imported macro has no owning module");
3182 ScratchSpace.push_back(DefModuleID);
3183 } else if (auto *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
3184 // If we override a #undef, we override anything that #undef overrides.
3185 // We don't need to override it, since an active #undef doesn't affect
3186 // the meaning of a macro.
3187 auto Overrides = UndefMD->getOverriddenModules();
3188 ScratchSpace.insert(ScratchSpace.end(),
3189 Overrides.begin(), Overrides.end());
3193 // Stop once we leave the original macro's submodule.
3195 // Either this submodule #included another submodule of the same
3196 // module or it just happened to be built after the other module.
3197 // In the former case, we override the submodule's macro.
3199 // FIXME: In the latter case, we shouldn't do so, but we can't tell
3200 // these cases apart.
3202 // FIXME: We can leave this submodule and re-enter it if it #includes a
3203 // header within a different submodule of the same module. In such cases
3204 // the overrides list will be incomplete.
3205 SubmoduleID DirectiveModuleID = getSubmoduleID(MD);
3206 if (DirectiveModuleID != ModID) {
3207 if (DirectiveModuleID && !MD->isImported())
3208 ScratchSpace.push_back(DirectiveModuleID);
3213 std::sort(ScratchSpace.begin(), ScratchSpace.end());
3214 ScratchSpace.erase(std::unique(ScratchSpace.begin(), ScratchSpace.end()),
3215 ScratchSpace.end());
3216 return ScratchSpace;
3219 SubmoduleID getSubmoduleID(MacroDirective *MD) {
3220 return Writer.inferSubmoduleIDFromLocation(MD->getLocation());
3224 typedef IdentifierInfo* key_type;
3225 typedef key_type key_type_ref;
3227 typedef IdentID data_type;
3228 typedef data_type data_type_ref;
3230 typedef unsigned hash_value_type;
3231 typedef unsigned offset_type;
3233 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3234 IdentifierResolver &IdResolver, bool IsModule)
3235 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
3237 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3238 return llvm::HashString(II->getName());
3241 std::pair<unsigned,unsigned>
3242 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3243 unsigned KeyLen = II->getLength() + 1;
3244 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3245 MacroDirective *Macro = nullptr;
3246 if (isInterestingIdentifier(II, Macro)) {
3247 DataLen += 2; // 2 bytes for builtin ID
3248 DataLen += 2; // 2 bytes for flags
3249 if (hadMacroDefinition(II, Macro)) {
3250 DataLen += 4; // MacroDirectives offset.
3253 SmallVector<SubmoduleID, 16> Scratch;
3254 for (MacroDirective *MD = getFirstPublicSubmoduleMacro(Macro, State);
3255 MD; MD = getNextPublicSubmoduleMacro(MD, State)) {
3256 DataLen += 4; // MacroInfo ID or ModuleID.
3257 if (unsigned NumOverrides =
3258 getOverriddenSubmodules(MD, Scratch).size())
3259 DataLen += 4 * (1 + NumOverrides);
3261 DataLen += 4; // 0 terminator.
3265 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3266 DEnd = IdResolver.end();
3270 using namespace llvm::support;
3271 endian::Writer<little> LE(Out);
3273 LE.write<uint16_t>(DataLen);
3274 // We emit the key length after the data length so that every
3275 // string is preceded by a 16-bit length. This matches the PTH
3276 // format for storing identifiers.
3277 LE.write<uint16_t>(KeyLen);
3278 return std::make_pair(KeyLen, DataLen);
3281 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3283 // Record the location of the key data. This is used when generating
3284 // the mapping from persistent IDs to strings.
3285 Writer.SetIdentifierOffset(II, Out.tell());
3286 Out.write(II->getNameStart(), KeyLen);
3289 static void emitMacroOverrides(raw_ostream &Out,
3290 ArrayRef<SubmoduleID> Overridden) {
3291 if (!Overridden.empty()) {
3292 using namespace llvm::support;
3293 endian::Writer<little> LE(Out);
3294 LE.write<uint32_t>(Overridden.size() | 0x80000000U);
3295 for (unsigned I = 0, N = Overridden.size(); I != N; ++I) {
3296 assert(Overridden[I] && "zero module ID for override");
3297 LE.write<uint32_t>(Overridden[I]);
3302 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3303 IdentID ID, unsigned) {
3304 using namespace llvm::support;
3305 endian::Writer<little> LE(Out);
3306 MacroDirective *Macro = nullptr;
3307 if (!isInterestingIdentifier(II, Macro)) {
3308 LE.write<uint32_t>(ID << 1);
3312 LE.write<uint32_t>((ID << 1) | 0x01);
3313 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3314 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3315 LE.write<uint16_t>(Bits);
3317 bool HadMacroDefinition = hadMacroDefinition(II, Macro);
3318 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3319 Bits = (Bits << 1) | unsigned(IsModule);
3320 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3321 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3322 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3323 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3324 LE.write<uint16_t>(Bits);
3326 if (HadMacroDefinition) {
3327 LE.write<uint32_t>(Writer.getMacroDirectivesOffset(II));
3329 // Write the IDs of macros coming from different submodules.
3331 SmallVector<SubmoduleID, 16> Scratch;
3332 for (MacroDirective *MD = getFirstPublicSubmoduleMacro(Macro, State);
3333 MD; MD = getNextPublicSubmoduleMacro(MD, State)) {
3334 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3335 // FIXME: If this macro directive was created by #pragma pop_macros,
3336 // or if it was created implicitly by resolving conflicting macros,
3337 // it may be for a different submodule from the one in the MacroInfo
3338 // object. If so, we should write out its owning ModuleID.
3339 MacroID InfoID = Writer.getMacroID(DefMD->getInfo());
3341 LE.write<uint32_t>(InfoID << 1);
3343 auto *UndefMD = cast<UndefMacroDirective>(MD);
3344 SubmoduleID Mod = UndefMD->isImported()
3345 ? UndefMD->getOwningModuleID()
3346 : getSubmoduleID(UndefMD);
3347 LE.write<uint32_t>((Mod << 1) | 1);
3349 emitMacroOverrides(Out, getOverriddenSubmodules(MD, Scratch));
3351 LE.write<uint32_t>(0xdeadbeef);
3355 // Emit the declaration IDs in reverse order, because the
3356 // IdentifierResolver provides the declarations as they would be
3357 // visible (e.g., the function "stat" would come before the struct
3358 // "stat"), but the ASTReader adds declarations to the end of the list
3359 // (so we need to see the struct "status" before the function "status").
3360 // Only emit declarations that aren't from a chained PCH, though.
3361 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
3363 for (SmallVectorImpl<Decl *>::reverse_iterator D = Decls.rbegin(),
3364 DEnd = Decls.rend();
3366 LE.write<uint32_t>(Writer.getDeclID(getMostRecentLocalDecl(*D)));
3369 /// \brief Returns the most recent local decl or the given decl if there are
3370 /// no local ones. The given decl is assumed to be the most recent one.
3371 Decl *getMostRecentLocalDecl(Decl *Orig) {
3372 // The only way a "from AST file" decl would be more recent from a local one
3373 // is if it came from a module.
3374 if (!PP.getLangOpts().Modules)
3377 // Look for a local in the decl chain.
3378 for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
3379 if (!D->isFromASTFile())
3381 // If we come up a decl from a (chained-)PCH stop since we won't find a
3383 if (D->getOwningModuleID() == 0)
3390 } // end anonymous namespace
3392 /// \brief Write the identifier table into the AST file.
3394 /// The identifier table consists of a blob containing string data
3395 /// (the actual identifiers themselves) and a separate "offsets" index
3396 /// that maps identifier IDs to locations within the blob.
3397 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3398 IdentifierResolver &IdResolver,
3400 using namespace llvm;
3402 // Create and write out the blob that contains the identifier
3405 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3406 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3408 // Look for any identifiers that were named while processing the
3409 // headers, but are otherwise not needed. We add these to the hash
3410 // table to enable checking of the predefines buffer in the case
3411 // where the user adds new macro definitions when building the AST
3413 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3414 IDEnd = PP.getIdentifierTable().end();
3416 getIdentifierRef(ID->second);
3418 // Create the on-disk hash table representation. We only store offsets
3419 // for identifiers that appear here for the first time.
3420 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3421 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
3422 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
3423 ID != IDEnd; ++ID) {
3424 assert(ID->first && "NULL identifier in identifier table");
3425 if (!Chain || !ID->first->isFromAST() ||
3426 ID->first->hasChangedSinceDeserialization())
3427 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
3431 // Create the on-disk hash table in a buffer.
3432 SmallString<4096> IdentifierTable;
3433 uint32_t BucketOffset;
3435 using namespace llvm::support;
3436 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3437 llvm::raw_svector_ostream Out(IdentifierTable);
3438 // Make sure that no bucket is at offset 0
3439 endian::Writer<little>(Out).write<uint32_t>(0);
3440 BucketOffset = Generator.Emit(Out, Trait);
3443 // Create a blob abbreviation
3444 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3445 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3446 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3447 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3448 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3450 // Write the identifier table
3452 Record.push_back(IDENTIFIER_TABLE);
3453 Record.push_back(BucketOffset);
3454 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
3457 // Write the offsets table for identifier IDs.
3458 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3459 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3463 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3466 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3467 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3471 Record.push_back(IDENTIFIER_OFFSET);
3472 Record.push_back(IdentifierOffsets.size());
3473 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
3474 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3475 data(IdentifierOffsets));
3478 //===----------------------------------------------------------------------===//
3479 // DeclContext's Name Lookup Table Serialization
3480 //===----------------------------------------------------------------------===//
3482 /// Determine the declaration that should be put into the name lookup table to
3483 /// represent the given declaration in this module. This is usually D itself,
3484 /// but if D was imported and merged into a local declaration, we want the most
3485 /// recent local declaration instead. The chosen declaration will be the most
3486 /// recent declaration in any module that imports this one.
3487 static NamedDecl *getDeclForLocalLookup(NamedDecl *D) {
3488 if (!D->isFromASTFile())
3491 if (Decl *Redecl = D->getPreviousDecl()) {
3492 // For Redeclarable decls, a prior declaration might be local.
3493 for (; Redecl; Redecl = Redecl->getPreviousDecl())
3494 if (!Redecl->isFromASTFile())
3495 return cast<NamedDecl>(Redecl);
3496 } else if (Decl *First = D->getCanonicalDecl()) {
3497 // For Mergeable decls, the first decl might be local.
3498 if (!First->isFromASTFile())
3499 return cast<NamedDecl>(First);
3502 // All declarations are imported. Our most recent declaration will also be
3503 // the most recent one in anyone who imports us.
3508 // Trait used for the on-disk hash table used in the method pool.
3509 class ASTDeclContextNameLookupTrait {
3513 typedef DeclarationName key_type;
3514 typedef key_type key_type_ref;
3516 typedef DeclContext::lookup_result data_type;
3517 typedef const data_type& data_type_ref;
3519 typedef unsigned hash_value_type;
3520 typedef unsigned offset_type;
3522 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3524 hash_value_type ComputeHash(DeclarationName Name) {
3525 llvm::FoldingSetNodeID ID;
3526 ID.AddInteger(Name.getNameKind());
3528 switch (Name.getNameKind()) {
3529 case DeclarationName::Identifier:
3530 ID.AddString(Name.getAsIdentifierInfo()->getName());
3532 case DeclarationName::ObjCZeroArgSelector:
3533 case DeclarationName::ObjCOneArgSelector:
3534 case DeclarationName::ObjCMultiArgSelector:
3535 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3537 case DeclarationName::CXXConstructorName:
3538 case DeclarationName::CXXDestructorName:
3539 case DeclarationName::CXXConversionFunctionName:
3541 case DeclarationName::CXXOperatorName:
3542 ID.AddInteger(Name.getCXXOverloadedOperator());
3544 case DeclarationName::CXXLiteralOperatorName:
3545 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3546 case DeclarationName::CXXUsingDirective:
3550 return ID.ComputeHash();
3553 std::pair<unsigned,unsigned>
3554 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3555 data_type_ref Lookup) {
3556 using namespace llvm::support;
3557 endian::Writer<little> LE(Out);
3558 unsigned KeyLen = 1;
3559 switch (Name.getNameKind()) {
3560 case DeclarationName::Identifier:
3561 case DeclarationName::ObjCZeroArgSelector:
3562 case DeclarationName::ObjCOneArgSelector:
3563 case DeclarationName::ObjCMultiArgSelector:
3564 case DeclarationName::CXXLiteralOperatorName:
3567 case DeclarationName::CXXOperatorName:
3570 case DeclarationName::CXXConstructorName:
3571 case DeclarationName::CXXDestructorName:
3572 case DeclarationName::CXXConversionFunctionName:
3573 case DeclarationName::CXXUsingDirective:
3576 LE.write<uint16_t>(KeyLen);
3578 // 2 bytes for num of decls and 4 for each DeclID.
3579 unsigned DataLen = 2 + 4 * Lookup.size();
3580 LE.write<uint16_t>(DataLen);
3582 return std::make_pair(KeyLen, DataLen);
3585 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3586 using namespace llvm::support;
3587 endian::Writer<little> LE(Out);
3588 LE.write<uint8_t>(Name.getNameKind());
3589 switch (Name.getNameKind()) {
3590 case DeclarationName::Identifier:
3591 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3593 case DeclarationName::ObjCZeroArgSelector:
3594 case DeclarationName::ObjCOneArgSelector:
3595 case DeclarationName::ObjCMultiArgSelector:
3596 LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
3598 case DeclarationName::CXXOperatorName:
3599 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3600 "Invalid operator?");
3601 LE.write<uint8_t>(Name.getCXXOverloadedOperator());
3603 case DeclarationName::CXXLiteralOperatorName:
3604 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3606 case DeclarationName::CXXConstructorName:
3607 case DeclarationName::CXXDestructorName:
3608 case DeclarationName::CXXConversionFunctionName:
3609 case DeclarationName::CXXUsingDirective:
3613 llvm_unreachable("Invalid name kind?");
3616 void EmitData(raw_ostream& Out, key_type_ref,
3617 data_type Lookup, unsigned DataLen) {
3618 using namespace llvm::support;
3619 endian::Writer<little> LE(Out);
3620 uint64_t Start = Out.tell(); (void)Start;
3621 LE.write<uint16_t>(Lookup.size());
3622 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3624 LE.write<uint32_t>(Writer.GetDeclRef(getDeclForLocalLookup(*I)));
3626 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3629 } // end anonymous namespace
3631 template<typename Visitor>
3632 static void visitLocalLookupResults(const DeclContext *ConstDC,
3633 bool NeedToReconcileExternalVisibleStorage,
3634 Visitor AddLookupResult) {
3635 // FIXME: We need to build the lookups table, which is logically const.
3636 DeclContext *DC = const_cast<DeclContext*>(ConstDC);
3637 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3639 SmallVector<DeclarationName, 16> ExternalNames;
3640 for (auto &Lookup : *DC->buildLookup()) {
3641 if (Lookup.second.hasExternalDecls() ||
3642 NeedToReconcileExternalVisibleStorage) {
3643 // We don't know for sure what declarations are found by this name,
3644 // because the external source might have a different set from the set
3645 // that are in the lookup map, and we can't update it now without
3646 // risking invalidating our lookup iterator. So add it to a queue to
3648 ExternalNames.push_back(Lookup.first);
3652 AddLookupResult(Lookup.first, Lookup.second.getLookupResult());
3655 // Add the names we needed to defer. Note, this shouldn't add any new decls
3656 // to the list we need to serialize: any new declarations we find here should
3657 // be imported from an external source.
3658 // FIXME: What if the external source isn't an ASTReader?
3659 for (const auto &Name : ExternalNames)
3660 AddLookupResult(Name, DC->lookup(Name));
3663 void ASTWriter::AddUpdatedDeclContext(const DeclContext *DC) {
3664 if (UpdatedDeclContexts.insert(DC) && WritingAST) {
3665 // Ensure we emit all the visible declarations.
3666 visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3667 [&](DeclarationName Name,
3668 DeclContext::lookup_const_result Result) {
3669 for (auto *Decl : Result)
3670 GetDeclRef(getDeclForLocalLookup(Decl));
3676 ASTWriter::GenerateNameLookupTable(const DeclContext *DC,
3677 llvm::SmallVectorImpl<char> &LookupTable) {
3678 assert(!DC->LookupPtr.getInt() && "must call buildLookups first");
3680 llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
3682 ASTDeclContextNameLookupTrait Trait(*this);
3684 // Create the on-disk hash table representation.
3685 DeclarationName ConstructorName;
3686 DeclarationName ConversionName;
3687 SmallVector<NamedDecl *, 8> ConstructorDecls;
3688 SmallVector<NamedDecl *, 4> ConversionDecls;
3690 visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3691 [&](DeclarationName Name,
3692 DeclContext::lookup_result Result) {
3696 // Different DeclarationName values of certain kinds are mapped to
3697 // identical serialized keys, because we don't want to use type
3698 // identifiers in the keys (since type ids are local to the module).
3699 switch (Name.getNameKind()) {
3700 case DeclarationName::CXXConstructorName:
3701 // There may be different CXXConstructorName DeclarationName values
3702 // in a DeclContext because a UsingDecl that inherits constructors
3703 // has the DeclarationName of the inherited constructors.
3704 if (!ConstructorName)
3705 ConstructorName = Name;
3706 ConstructorDecls.append(Result.begin(), Result.end());
3709 case DeclarationName::CXXConversionFunctionName:
3710 if (!ConversionName)
3711 ConversionName = Name;
3712 ConversionDecls.append(Result.begin(), Result.end());
3719 Generator.insert(Name, Result, Trait);
3722 // Add the constructors.
3723 if (!ConstructorDecls.empty()) {
3724 Generator.insert(ConstructorName,
3725 DeclContext::lookup_result(ConstructorDecls.begin(),
3726 ConstructorDecls.end()),
3730 // Add the conversion functions.
3731 if (!ConversionDecls.empty()) {
3732 Generator.insert(ConversionName,
3733 DeclContext::lookup_result(ConversionDecls.begin(),
3734 ConversionDecls.end()),
3738 // Create the on-disk hash table in a buffer.
3739 llvm::raw_svector_ostream Out(LookupTable);
3740 // Make sure that no bucket is at offset 0
3741 using namespace llvm::support;
3742 endian::Writer<little>(Out).write<uint32_t>(0);
3743 return Generator.Emit(Out, Trait);
3746 /// \brief Write the block containing all of the declaration IDs
3747 /// visible from the given DeclContext.
3749 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3750 /// bitstream, or 0 if no block was written.
3751 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3753 if (DC->getPrimaryContext() != DC)
3756 // Since there is no name lookup into functions or methods, don't bother to
3757 // build a visible-declarations table for these entities.
3758 if (DC->isFunctionOrMethod())
3761 // If not in C++, we perform name lookup for the translation unit via the
3762 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3763 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3766 // Serialize the contents of the mapping used for lookup. Note that,
3767 // although we have two very different code paths, the serialized
3768 // representation is the same for both cases: a declaration name,
3769 // followed by a size, followed by references to the visible
3770 // declarations that have that name.
3771 uint64_t Offset = Stream.GetCurrentBitNo();
3772 StoredDeclsMap *Map = DC->buildLookup();
3773 if (!Map || Map->empty())
3776 // Create the on-disk hash table in a buffer.
3777 SmallString<4096> LookupTable;
3778 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3780 // Write the lookup table
3782 Record.push_back(DECL_CONTEXT_VISIBLE);
3783 Record.push_back(BucketOffset);
3784 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3786 ++NumVisibleDeclContexts;
3790 /// \brief Write an UPDATE_VISIBLE block for the given context.
3792 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3793 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3794 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3795 /// enumeration members (in C++11).
3796 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3797 StoredDeclsMap *Map = DC->getLookupPtr();
3798 if (!Map || Map->empty())
3801 // Create the on-disk hash table in a buffer.
3802 SmallString<4096> LookupTable;
3803 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3805 // Write the lookup table
3807 Record.push_back(UPDATE_VISIBLE);
3808 Record.push_back(getDeclID(cast<Decl>(DC)));
3809 Record.push_back(BucketOffset);
3810 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3813 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3814 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3816 Record.push_back(Opts.fp_contract);
3817 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3820 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3821 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3822 if (!SemaRef.Context.getLangOpts().OpenCL)
3825 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3827 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3828 #include "clang/Basic/OpenCLExtensions.def"
3829 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3832 void ASTWriter::WriteRedeclarations() {
3833 RecordData LocalRedeclChains;
3834 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3836 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3837 Decl *First = Redeclarations[I];
3838 assert(First->isFirstDecl() && "Not the first declaration?");
3840 Decl *MostRecent = First->getMostRecentDecl();
3842 // If we only have a single declaration, there is no point in storing
3843 // a redeclaration chain.
3844 if (First == MostRecent)
3847 unsigned Offset = LocalRedeclChains.size();
3849 LocalRedeclChains.push_back(0); // Placeholder for the size.
3851 // Collect the set of local redeclarations of this declaration.
3852 for (Decl *Prev = MostRecent; Prev != First;
3853 Prev = Prev->getPreviousDecl()) {
3854 if (!Prev->isFromASTFile()) {
3855 AddDeclRef(Prev, LocalRedeclChains);
3860 if (!First->isFromASTFile() && Chain) {
3861 Decl *FirstFromAST = MostRecent;
3862 for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3863 if (Prev->isFromASTFile())
3864 FirstFromAST = Prev;
3867 // FIXME: Do we need to do this for the first declaration from each
3868 // redeclaration chain that was merged into this one?
3869 Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3872 LocalRedeclChains[Offset] = Size;
3874 // Reverse the set of local redeclarations, so that we store them in
3875 // order (since we found them in reverse order).
3876 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3878 // Add the mapping from the first ID from the AST to the set of local
3880 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3881 LocalRedeclsMap.push_back(Info);
3883 assert(N == Redeclarations.size() &&
3884 "Deserialized a declaration we shouldn't have");
3887 if (LocalRedeclChains.empty())
3890 // Sort the local redeclarations map by the first declaration ID,
3891 // since the reader will be performing binary searches on this information.
3892 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3894 // Emit the local redeclarations map.
3895 using namespace llvm;
3896 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3897 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3899 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3900 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3903 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3904 Record.push_back(LocalRedeclsMap.size());
3905 Stream.EmitRecordWithBlob(AbbrevID, Record,
3906 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3907 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3909 // Emit the redeclaration chains.
3910 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3913 void ASTWriter::WriteObjCCategories() {
3914 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3915 RecordData Categories;
3917 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3919 unsigned StartIndex = Categories.size();
3921 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3923 // Allocate space for the size.
3924 Categories.push_back(0);
3926 // Add the categories.
3927 for (ObjCInterfaceDecl::known_categories_iterator
3928 Cat = Class->known_categories_begin(),
3929 CatEnd = Class->known_categories_end();
3930 Cat != CatEnd; ++Cat, ++Size) {
3931 assert(getDeclID(*Cat) != 0 && "Bogus category");
3932 AddDeclRef(*Cat, Categories);
3936 Categories[StartIndex] = Size;
3938 // Record this interface -> category map.
3939 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3940 CategoriesMap.push_back(CatInfo);
3943 // Sort the categories map by the definition ID, since the reader will be
3944 // performing binary searches on this information.
3945 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3947 // Emit the categories map.
3948 using namespace llvm;
3949 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3950 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3951 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3952 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3953 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3956 Record.push_back(OBJC_CATEGORIES_MAP);
3957 Record.push_back(CategoriesMap.size());
3958 Stream.EmitRecordWithBlob(AbbrevID, Record,
3959 reinterpret_cast<char*>(CategoriesMap.data()),
3960 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3962 // Emit the category lists.
3963 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3966 void ASTWriter::WriteMergedDecls() {
3967 if (!Chain || Chain->MergedDecls.empty())
3971 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3972 IEnd = Chain->MergedDecls.end();
3974 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3975 : GetDeclRef(I->first);
3976 assert(CanonID && "Merged declaration not known?");
3978 Record.push_back(CanonID);
3979 Record.push_back(I->second.size());
3980 Record.append(I->second.begin(), I->second.end());
3982 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3985 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3986 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3992 for (Sema::LateParsedTemplateMapT::iterator It = LPTMap.begin(),
3993 ItEnd = LPTMap.end();
3994 It != ItEnd; ++It) {
3995 LateParsedTemplate *LPT = It->second;
3996 AddDeclRef(It->first, Record);
3997 AddDeclRef(LPT->D, Record);
3998 Record.push_back(LPT->Toks.size());
4000 for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
4001 TokEnd = LPT->Toks.end();
4002 TokIt != TokEnd; ++TokIt) {
4003 AddToken(*TokIt, Record);
4006 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4009 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4010 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4012 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4013 AddSourceLocation(PragmaLoc, Record);
4014 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4017 //===----------------------------------------------------------------------===//
4018 // General Serialization Routines
4019 //===----------------------------------------------------------------------===//
4021 /// \brief Write a record containing the given attributes.
4022 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
4023 RecordDataImpl &Record) {
4024 Record.push_back(Attrs.size());
4025 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
4026 e = Attrs.end(); i != e; ++i){
4028 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4029 AddSourceRange(A->getRange(), Record);
4031 #include "clang/Serialization/AttrPCHWrite.inc"
4036 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4037 AddSourceLocation(Tok.getLocation(), Record);
4038 Record.push_back(Tok.getLength());
4040 // FIXME: When reading literal tokens, reconstruct the literal pointer
4042 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4043 // FIXME: Should translate token kind to a stable encoding.
4044 Record.push_back(Tok.getKind());
4045 // FIXME: Should translate token flags to a stable encoding.
4046 Record.push_back(Tok.getFlags());
4049 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4050 Record.push_back(Str.size());
4051 Record.insert(Record.end(), Str.begin(), Str.end());
4054 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4055 RecordDataImpl &Record) {
4056 Record.push_back(Version.getMajor());
4057 if (Optional<unsigned> Minor = Version.getMinor())
4058 Record.push_back(*Minor + 1);
4060 Record.push_back(0);
4061 if (Optional<unsigned> Subminor = Version.getSubminor())
4062 Record.push_back(*Subminor + 1);
4064 Record.push_back(0);
4067 /// \brief Note that the identifier II occurs at the given offset
4068 /// within the identifier table.
4069 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4070 IdentID ID = IdentifierIDs[II];
4071 // Only store offsets new to this AST file. Other identifier names are looked
4072 // up earlier in the chain and thus don't need an offset.
4073 if (ID >= FirstIdentID)
4074 IdentifierOffsets[ID - FirstIdentID] = Offset;
4077 /// \brief Note that the selector Sel occurs at the given offset
4078 /// within the method pool/selector table.
4079 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4080 unsigned ID = SelectorIDs[Sel];
4081 assert(ID && "Unknown selector");
4082 // Don't record offsets for selectors that are also available in a different
4084 if (ID < FirstSelectorID)
4086 SelectorOffsets[ID - FirstSelectorID] = Offset;
4089 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
4090 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
4091 WritingModule(nullptr), WritingAST(false),
4092 DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false),
4093 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
4094 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
4095 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
4096 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
4097 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
4098 NextSubmoduleID(FirstSubmoduleID),
4099 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4100 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4101 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
4102 NextCXXBaseSpecifiersID(1), TypeExtQualAbbrev(0),
4103 TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
4104 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
4105 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
4106 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
4107 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4108 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
4109 ExprImplicitCastAbbrev(0) {}
4111 ASTWriter::~ASTWriter() {
4112 llvm::DeleteContainerSeconds(FileDeclIDs);
4115 void ASTWriter::WriteAST(Sema &SemaRef,
4116 const std::string &OutputFile,
4117 Module *WritingModule, StringRef isysroot,
4121 ASTHasCompilerErrors = hasErrors;
4123 // Emit the file header.
4124 Stream.Emit((unsigned)'C', 8);
4125 Stream.Emit((unsigned)'P', 8);
4126 Stream.Emit((unsigned)'C', 8);
4127 Stream.Emit((unsigned)'H', 8);
4129 WriteBlockInfoBlock();
4131 Context = &SemaRef.Context;
4133 this->WritingModule = WritingModule;
4134 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4137 this->WritingModule = nullptr;
4142 template<typename Vector>
4143 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4144 ASTWriter::RecordData &Record) {
4145 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4147 Writer.AddDeclRef(*I, Record);
4151 void ASTWriter::WriteASTCore(Sema &SemaRef,
4153 const std::string &OutputFile,
4154 Module *WritingModule) {
4155 using namespace llvm;
4157 bool isModule = WritingModule != nullptr;
4159 // Make sure that the AST reader knows to finalize itself.
4161 Chain->finalizeForWriting();
4163 ASTContext &Context = SemaRef.Context;
4164 Preprocessor &PP = SemaRef.PP;
4166 // Set up predefined declaration IDs.
4167 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
4168 if (Context.ObjCIdDecl)
4169 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
4170 if (Context.ObjCSelDecl)
4171 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
4172 if (Context.ObjCClassDecl)
4173 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
4174 if (Context.ObjCProtocolClassDecl)
4175 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
4176 if (Context.Int128Decl)
4177 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
4178 if (Context.UInt128Decl)
4179 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
4180 if (Context.ObjCInstanceTypeDecl)
4181 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
4182 if (Context.BuiltinVaListDecl)
4183 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
4186 // Make sure that we emit IdentifierInfos (and any attached
4187 // declarations) for builtins. We don't need to do this when we're
4188 // emitting chained PCH files, because all of the builtins will be
4189 // in the original PCH file.
4190 // FIXME: Modules won't like this at all.
4191 IdentifierTable &Table = PP.getIdentifierTable();
4192 SmallVector<const char *, 32> BuiltinNames;
4193 if (!Context.getLangOpts().NoBuiltin) {
4194 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames);
4196 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
4197 getIdentifierRef(&Table.get(BuiltinNames[I]));
4200 // If there are any out-of-date identifiers, bring them up to date.
4201 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
4202 // Find out-of-date identifiers.
4203 SmallVector<IdentifierInfo *, 4> OutOfDate;
4204 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4205 IDEnd = PP.getIdentifierTable().end();
4206 ID != IDEnd; ++ID) {
4207 if (ID->second->isOutOfDate())
4208 OutOfDate.push_back(ID->second);
4211 // Update the out-of-date identifiers.
4212 for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
4213 ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
4217 // If we saw any DeclContext updates before we started writing the AST file,
4218 // make sure all visible decls in those DeclContexts are written out.
4219 if (!UpdatedDeclContexts.empty()) {
4220 auto OldUpdatedDeclContexts = std::move(UpdatedDeclContexts);
4221 UpdatedDeclContexts.clear();
4222 for (auto *DC : OldUpdatedDeclContexts)
4223 AddUpdatedDeclContext(DC);
4226 // Build a record containing all of the tentative definitions in this file, in
4227 // TentativeDefinitions order. Generally, this record will be empty for
4229 RecordData TentativeDefinitions;
4230 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4232 // Build a record containing all of the file scoped decls in this file.
4233 RecordData UnusedFileScopedDecls;
4235 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4236 UnusedFileScopedDecls);
4238 // Build a record containing all of the delegating constructors we still need
4240 RecordData DelegatingCtorDecls;
4242 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4244 // Write the set of weak, undeclared identifiers. We always write the
4245 // entire table, since later PCH files in a PCH chain are only interested in
4246 // the results at the end of the chain.
4247 RecordData WeakUndeclaredIdentifiers;
4248 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
4249 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
4250 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
4251 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
4252 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
4253 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
4254 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
4255 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
4259 // Build a record containing all of the locally-scoped extern "C"
4260 // declarations in this header file. Generally, this record will be
4262 RecordData LocallyScopedExternCDecls;
4263 // FIXME: This is filling in the AST file in densemap order which is
4265 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
4266 TD = SemaRef.LocallyScopedExternCDecls.begin(),
4267 TDEnd = SemaRef.LocallyScopedExternCDecls.end();
4268 TD != TDEnd; ++TD) {
4269 if (!TD->second->isFromASTFile())
4270 AddDeclRef(TD->second, LocallyScopedExternCDecls);
4273 // Build a record containing all of the ext_vector declarations.
4274 RecordData ExtVectorDecls;
4275 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4277 // Build a record containing all of the VTable uses information.
4278 RecordData VTableUses;
4279 if (!SemaRef.VTableUses.empty()) {
4280 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4281 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4282 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4283 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4287 // Build a record containing all of dynamic classes declarations.
4288 RecordData DynamicClasses;
4289 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
4291 // Build a record containing all of pending implicit instantiations.
4292 RecordData PendingInstantiations;
4293 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
4294 I = SemaRef.PendingInstantiations.begin(),
4295 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
4296 AddDeclRef(I->first, PendingInstantiations);
4297 AddSourceLocation(I->second, PendingInstantiations);
4299 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4300 "There are local ones at end of translation unit!");
4302 // Build a record containing some declaration references.
4303 RecordData SemaDeclRefs;
4304 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4305 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4306 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4309 RecordData CUDASpecialDeclRefs;
4310 if (Context.getcudaConfigureCallDecl()) {
4311 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4314 // Build a record containing all of the known namespaces.
4315 RecordData KnownNamespaces;
4316 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4317 I = SemaRef.KnownNamespaces.begin(),
4318 IEnd = SemaRef.KnownNamespaces.end();
4321 AddDeclRef(I->first, KnownNamespaces);
4324 // Build a record of all used, undefined objects that require definitions.
4325 RecordData UndefinedButUsed;
4327 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4328 SemaRef.getUndefinedButUsed(Undefined);
4329 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4330 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
4331 AddDeclRef(I->first, UndefinedButUsed);
4332 AddSourceLocation(I->second, UndefinedButUsed);
4335 // Write the control block
4336 WriteControlBlock(PP, Context, isysroot, OutputFile);
4338 // Write the remaining AST contents.
4340 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4342 // This is so that older clang versions, before the introduction
4343 // of the control block, can read and reject the newer PCH format.
4345 Record.push_back(VERSION_MAJOR);
4346 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4348 // Create a lexical update block containing all of the declarations in the
4349 // translation unit that do not come from other AST files.
4350 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4351 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
4352 for (const auto *I : TU->noload_decls()) {
4353 if (!I->isFromASTFile())
4354 NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
4357 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4358 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4359 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4360 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4362 Record.push_back(TU_UPDATE_LEXICAL);
4363 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4364 data(NewGlobalDecls));
4366 // And a visible updates block for the translation unit.
4367 Abv = new llvm::BitCodeAbbrev();
4368 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4369 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4370 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4371 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4372 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4373 WriteDeclContextVisibleUpdate(TU);
4375 // If the translation unit has an anonymous namespace, and we don't already
4376 // have an update block for it, write it as an update block.
4377 // FIXME: Why do we not do this if there's already an update block?
4378 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4379 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4381 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4384 // Add update records for all mangling numbers and static local numbers.
4385 // These aren't really update records, but this is a convenient way of
4386 // tagging this rare extra data onto the declarations.
4387 for (const auto &Number : Context.MangleNumbers)
4388 if (!Number.first->isFromASTFile())
4389 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4391 for (const auto &Number : Context.StaticLocalNumbers)
4392 if (!Number.first->isFromASTFile())
4393 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4396 // Make sure visible decls, added to DeclContexts previously loaded from
4397 // an AST file, are registered for serialization.
4398 for (SmallVectorImpl<const Decl *>::iterator
4399 I = UpdatingVisibleDecls.begin(),
4400 E = UpdatingVisibleDecls.end(); I != E; ++I) {
4404 // Make sure all decls associated with an identifier are registered for
4406 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4407 IDEnd = PP.getIdentifierTable().end();
4408 ID != IDEnd; ++ID) {
4409 const IdentifierInfo *II = ID->second;
4410 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) {
4411 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4412 DEnd = SemaRef.IdResolver.end();
4419 // Form the record of special types.
4420 RecordData SpecialTypes;
4421 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4422 AddTypeRef(Context.getFILEType(), SpecialTypes);
4423 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4424 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4425 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4426 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4427 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4428 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4431 // Write the mapping information describing our module dependencies and how
4432 // each of those modules were mapped into our own offset/ID space, so that
4433 // the reader can build the appropriate mapping to its own offset/ID space.
4434 // The map consists solely of a blob with the following format:
4435 // *(module-name-len:i16 module-name:len*i8
4436 // source-location-offset:i32
4437 // identifier-id:i32
4438 // preprocessed-entity-id:i32
4439 // macro-definition-id:i32
4442 // declaration-id:i32
4443 // c++-base-specifiers-id:i32
4446 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4447 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4449 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4450 SmallString<2048> Buffer;
4452 llvm::raw_svector_ostream Out(Buffer);
4453 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
4454 MEnd = Chain->ModuleMgr.end();
4456 using namespace llvm::support;
4457 endian::Writer<little> LE(Out);
4458 StringRef FileName = (*M)->FileName;
4459 LE.write<uint16_t>(FileName.size());
4460 Out.write(FileName.data(), FileName.size());
4462 // These values should be unique within a chain, since they will be read
4463 // as keys into ContinuousRangeMaps.
4464 LE.write<uint32_t>((*M)->SLocEntryBaseOffset);
4465 LE.write<uint32_t>((*M)->BaseIdentifierID);
4466 LE.write<uint32_t>((*M)->BaseMacroID);
4467 LE.write<uint32_t>((*M)->BasePreprocessedEntityID);
4468 LE.write<uint32_t>((*M)->BaseSubmoduleID);
4469 LE.write<uint32_t>((*M)->BaseSelectorID);
4470 LE.write<uint32_t>((*M)->BaseDeclID);
4471 LE.write<uint32_t>((*M)->BaseTypeIndex);
4475 Record.push_back(MODULE_OFFSET_MAP);
4476 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4477 Buffer.data(), Buffer.size());
4480 RecordData DeclUpdatesOffsetsRecord;
4482 // Keep writing types, declarations, and declaration update records
4483 // until we've emitted all of them.
4484 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4487 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4488 E = DeclsToRewrite.end();
4490 DeclTypesToEmit.push(const_cast<Decl*>(*I));
4492 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4493 while (!DeclTypesToEmit.empty()) {
4494 DeclOrType DOT = DeclTypesToEmit.front();
4495 DeclTypesToEmit.pop();
4497 WriteType(DOT.getType());
4499 WriteDecl(Context, DOT.getDecl());
4501 } while (!DeclUpdates.empty());
4504 DoneWritingDeclsAndTypes = true;
4506 // These things can only be done once we've written out decls and types.
4507 WriteTypeDeclOffsets();
4508 if (!DeclUpdatesOffsetsRecord.empty())
4509 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4510 WriteCXXBaseSpecifiersOffsets();
4511 WriteFileDeclIDsMap();
4512 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
4515 WritePreprocessor(PP, isModule);
4516 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
4517 WriteSelectors(SemaRef);
4518 WriteReferencedSelectorsPool(SemaRef);
4519 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4520 WriteFPPragmaOptions(SemaRef.getFPOptions());
4521 WriteOpenCLExtensions(SemaRef);
4522 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4524 // If we're emitting a module, write out the submodule information.
4526 WriteSubmodules(WritingModule);
4528 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4530 // Write the record containing external, unnamed definitions.
4531 if (!EagerlyDeserializedDecls.empty())
4532 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4534 // Write the record containing tentative definitions.
4535 if (!TentativeDefinitions.empty())
4536 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4538 // Write the record containing unused file scoped decls.
4539 if (!UnusedFileScopedDecls.empty())
4540 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4542 // Write the record containing weak undeclared identifiers.
4543 if (!WeakUndeclaredIdentifiers.empty())
4544 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4545 WeakUndeclaredIdentifiers);
4547 // Write the record containing locally-scoped extern "C" definitions.
4548 if (!LocallyScopedExternCDecls.empty())
4549 Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4550 LocallyScopedExternCDecls);
4552 // Write the record containing ext_vector type names.
4553 if (!ExtVectorDecls.empty())
4554 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4556 // Write the record containing VTable uses information.
4557 if (!VTableUses.empty())
4558 Stream.EmitRecord(VTABLE_USES, VTableUses);
4560 // Write the record containing dynamic classes declarations.
4561 if (!DynamicClasses.empty())
4562 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
4564 // Write the record containing pending implicit instantiations.
4565 if (!PendingInstantiations.empty())
4566 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4568 // Write the record containing declaration references of Sema.
4569 if (!SemaDeclRefs.empty())
4570 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4572 // Write the record containing CUDA-specific declaration references.
4573 if (!CUDASpecialDeclRefs.empty())
4574 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4576 // Write the delegating constructors.
4577 if (!DelegatingCtorDecls.empty())
4578 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4580 // Write the known namespaces.
4581 if (!KnownNamespaces.empty())
4582 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4584 // Write the undefined internal functions and variables, and inline functions.
4585 if (!UndefinedButUsed.empty())
4586 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4588 // Write the visible updates to DeclContexts.
4589 for (auto *DC : UpdatedDeclContexts)
4590 WriteDeclContextVisibleUpdate(DC);
4592 if (!WritingModule) {
4593 // Write the submodules that were imported, if any.
4597 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4599 llvm::SmallVector<ModuleInfo, 64> Imports;
4600 for (const auto *I : Context.local_imports()) {
4601 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4602 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4603 I->getImportedModule()));
4606 if (!Imports.empty()) {
4607 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4611 // Sort and deduplicate module IDs.
4612 std::sort(Imports.begin(), Imports.end(), Cmp);
4613 Imports.erase(std::unique(Imports.begin(), Imports.end(), Cmp),
4616 RecordData ImportedModules;
4617 for (const auto &Import : Imports) {
4618 ImportedModules.push_back(Import.ID);
4619 // FIXME: If the module has macros imported then later has declarations
4620 // imported, this location won't be the right one as a location for the
4621 // declaration imports.
4622 AddSourceLocation(Import.M->MacroVisibilityLoc, ImportedModules);
4625 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4629 WriteDeclReplacementsBlock();
4630 WriteRedeclarations();
4632 WriteObjCCategories();
4633 WriteLateParsedTemplates(SemaRef);
4635 WriteOptimizePragmaOptions(SemaRef);
4637 // Some simple statistics
4639 Record.push_back(NumStatements);
4640 Record.push_back(NumMacros);
4641 Record.push_back(NumLexicalDeclContexts);
4642 Record.push_back(NumVisibleDeclContexts);
4643 Stream.EmitRecord(STATISTICS, Record);
4647 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4648 if (DeclUpdates.empty())
4651 DeclUpdateMap LocalUpdates;
4652 LocalUpdates.swap(DeclUpdates);
4654 for (auto &DeclUpdate : LocalUpdates) {
4655 const Decl *D = DeclUpdate.first;
4657 continue; // The decl will be written completely,no need to store updates.
4659 bool HasUpdatedBody = false;
4661 for (auto &Update : DeclUpdate.second) {
4662 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4664 Record.push_back(Kind);
4666 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4667 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4668 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4669 assert(Update.getDecl() && "no decl to add?");
4670 Record.push_back(GetDeclRef(Update.getDecl()));
4673 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4674 // An updated body is emitted last, so that the reader doesn't need
4675 // to skip over the lazy body to reach statements for other records.
4677 HasUpdatedBody = true;
4680 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4681 AddSourceLocation(Update.getLoc(), Record);
4684 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4685 auto *RD = cast<CXXRecordDecl>(D);
4686 AddUpdatedDeclContext(RD->getPrimaryContext());
4687 AddCXXDefinitionData(RD, Record);
4688 Record.push_back(WriteDeclContextLexicalBlock(
4689 *Context, const_cast<CXXRecordDecl *>(RD)));
4691 // This state is sometimes updated by template instantiation, when we
4692 // switch from the specialization referring to the template declaration
4693 // to it referring to the template definition.
4694 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4695 Record.push_back(MSInfo->getTemplateSpecializationKind());
4696 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4698 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4699 Record.push_back(Spec->getTemplateSpecializationKind());
4700 AddSourceLocation(Spec->getPointOfInstantiation(), Record);
4702 // The instantiation might have been resolved to a partial
4703 // specialization. If so, record which one.
4704 auto From = Spec->getInstantiatedFrom();
4705 if (auto PartialSpec =
4706 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4707 Record.push_back(true);
4708 AddDeclRef(PartialSpec, Record);
4709 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4712 Record.push_back(false);
4715 Record.push_back(RD->getTagKind());
4716 AddSourceLocation(RD->getLocation(), Record);
4717 AddSourceLocation(RD->getLocStart(), Record);
4718 AddSourceLocation(RD->getRBraceLoc(), Record);
4720 // Instantiation may change attributes; write them all out afresh.
4721 Record.push_back(D->hasAttrs());
4723 WriteAttributes(ArrayRef<const Attr*>(D->getAttrs().begin(),
4724 D->getAttrs().size()), Record);
4726 // FIXME: Ensure we don't get here for explicit instantiations.
4730 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4733 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4737 case UPD_CXX_DEDUCED_RETURN_TYPE:
4738 Record.push_back(GetOrCreateTypeID(Update.getType()));
4741 case UPD_DECL_MARKED_USED:
4744 case UPD_MANGLING_NUMBER:
4745 case UPD_STATIC_LOCAL_NUMBER:
4746 Record.push_back(Update.getNumber());
4751 if (HasUpdatedBody) {
4752 const FunctionDecl *Def = cast<FunctionDecl>(D);
4753 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4754 Record.push_back(Def->isInlined());
4755 AddSourceLocation(Def->getInnerLocStart(), Record);
4756 AddFunctionDefinition(Def, Record);
4757 if (auto *DD = dyn_cast<CXXDestructorDecl>(Def))
4758 Record.push_back(GetDeclRef(DD->getOperatorDelete()));
4761 OffsetsRecord.push_back(GetDeclRef(D));
4762 OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4764 Stream.EmitRecord(DECL_UPDATES, Record);
4766 // Flush any statements that were written as part of this update record.
4769 // Flush C++ base specifiers, if there are any.
4770 FlushCXXBaseSpecifiers();
4774 void ASTWriter::WriteDeclReplacementsBlock() {
4775 if (ReplacedDecls.empty())
4779 for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4780 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4781 Record.push_back(I->ID);
4782 Record.push_back(I->Offset);
4783 Record.push_back(I->Loc);
4785 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4788 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4789 Record.push_back(Loc.getRawEncoding());
4792 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4793 AddSourceLocation(Range.getBegin(), Record);
4794 AddSourceLocation(Range.getEnd(), Record);
4797 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4798 Record.push_back(Value.getBitWidth());
4799 const uint64_t *Words = Value.getRawData();
4800 Record.append(Words, Words + Value.getNumWords());
4803 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4804 Record.push_back(Value.isUnsigned());
4805 AddAPInt(Value, Record);
4808 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4809 AddAPInt(Value.bitcastToAPInt(), Record);
4812 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4813 Record.push_back(getIdentifierRef(II));
4816 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4820 IdentID &ID = IdentifierIDs[II];
4826 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4827 // Don't emit builtin macros like __LINE__ to the AST file unless they
4828 // have been redefined by the header (in which case they are not
4830 if (!MI || MI->isBuiltinMacro())
4833 MacroID &ID = MacroIDs[MI];
4836 MacroInfoToEmitData Info = { Name, MI, ID };
4837 MacroInfosToEmit.push_back(Info);
4842 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4843 if (!MI || MI->isBuiltinMacro())
4846 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4847 return MacroIDs[MI];
4850 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4851 assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4852 return IdentMacroDirectivesOffsetMap[Name];
4855 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4856 Record.push_back(getSelectorRef(SelRef));
4859 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4860 if (Sel.getAsOpaquePtr() == nullptr) {
4864 SelectorID SID = SelectorIDs[Sel];
4865 if (SID == 0 && Chain) {
4866 // This might trigger a ReadSelector callback, which will set the ID for
4868 Chain->LoadSelector(Sel);
4869 SID = SelectorIDs[Sel];
4872 SID = NextSelectorID++;
4873 SelectorIDs[Sel] = SID;
4878 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4879 AddDeclRef(Temp->getDestructor(), Record);
4882 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4883 CXXBaseSpecifier const *BasesEnd,
4884 RecordDataImpl &Record) {
4885 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4886 CXXBaseSpecifiersToWrite.push_back(
4887 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4889 Record.push_back(NextCXXBaseSpecifiersID++);
4892 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4893 const TemplateArgumentLocInfo &Arg,
4894 RecordDataImpl &Record) {
4896 case TemplateArgument::Expression:
4897 AddStmt(Arg.getAsExpr());
4899 case TemplateArgument::Type:
4900 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4902 case TemplateArgument::Template:
4903 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4904 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4906 case TemplateArgument::TemplateExpansion:
4907 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4908 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4909 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4911 case TemplateArgument::Null:
4912 case TemplateArgument::Integral:
4913 case TemplateArgument::Declaration:
4914 case TemplateArgument::NullPtr:
4915 case TemplateArgument::Pack:
4916 // FIXME: Is this right?
4921 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4922 RecordDataImpl &Record) {
4923 AddTemplateArgument(Arg.getArgument(), Record);
4925 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4926 bool InfoHasSameExpr
4927 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4928 Record.push_back(InfoHasSameExpr);
4929 if (InfoHasSameExpr)
4930 return; // Avoid storing the same expr twice.
4932 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4936 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4937 RecordDataImpl &Record) {
4939 AddTypeRef(QualType(), Record);
4943 AddTypeLoc(TInfo->getTypeLoc(), Record);
4946 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4947 AddTypeRef(TL.getType(), Record);
4949 TypeLocWriter TLW(*this, Record);
4950 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4954 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4955 Record.push_back(GetOrCreateTypeID(T));
4958 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4960 return MakeTypeID(*Context, T,
4961 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4964 TypeID ASTWriter::getTypeID(QualType T) const {
4966 return MakeTypeID(*Context, T,
4967 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4970 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4973 assert(!T.getLocalFastQualifiers());
4975 TypeIdx &Idx = TypeIdxs[T];
4976 if (Idx.getIndex() == 0) {
4977 if (DoneWritingDeclsAndTypes) {
4978 assert(0 && "New type seen after serializing all the types to emit!");
4982 // We haven't seen this type before. Assign it a new ID and put it
4983 // into the queue of types to emit.
4984 Idx = TypeIdx(NextTypeID++);
4985 DeclTypesToEmit.push(T);
4990 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4993 assert(!T.getLocalFastQualifiers());
4995 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4996 assert(I != TypeIdxs.end() && "Type not emitted!");
5000 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5001 Record.push_back(GetDeclRef(D));
5004 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5005 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5011 // If D comes from an AST file, its declaration ID is already known and
5013 if (D->isFromASTFile())
5014 return D->getGlobalID();
5016 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5017 DeclID &ID = DeclIDs[D];
5019 if (DoneWritingDeclsAndTypes) {
5020 assert(0 && "New decl seen after serializing all the decls to emit!");
5024 // We haven't seen this declaration before. Give it a new ID and
5025 // enqueue it in the list of declarations to emit.
5027 DeclTypesToEmit.push(const_cast<Decl *>(D));
5033 DeclID ASTWriter::getDeclID(const Decl *D) {
5037 // If D comes from an AST file, its declaration ID is already known and
5039 if (D->isFromASTFile())
5040 return D->getGlobalID();
5042 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5046 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5050 SourceLocation Loc = D->getLocation();
5051 if (Loc.isInvalid())
5054 // We only keep track of the file-level declarations of each file.
5055 if (!D->getLexicalDeclContext()->isFileContext())
5057 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5058 // a function/objc method, should not have TU as lexical context.
5059 if (isa<ParmVarDecl>(D))
5062 SourceManager &SM = Context->getSourceManager();
5063 SourceLocation FileLoc = SM.getFileLoc(Loc);
5064 assert(SM.isLocalSourceLocation(FileLoc));
5067 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5068 if (FID.isInvalid())
5070 assert(SM.getSLocEntry(FID).isFile());
5072 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5074 Info = new DeclIDInFileInfo();
5076 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5077 LocDeclIDsTy &Decls = Info->DeclIDs;
5079 if (Decls.empty() || Decls.back().first <= Offset) {
5080 Decls.push_back(LocDecl);
5084 LocDeclIDsTy::iterator I =
5085 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5087 Decls.insert(I, LocDecl);
5090 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
5091 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5092 Record.push_back(Name.getNameKind());
5093 switch (Name.getNameKind()) {
5094 case DeclarationName::Identifier:
5095 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5098 case DeclarationName::ObjCZeroArgSelector:
5099 case DeclarationName::ObjCOneArgSelector:
5100 case DeclarationName::ObjCMultiArgSelector:
5101 AddSelectorRef(Name.getObjCSelector(), Record);
5104 case DeclarationName::CXXConstructorName:
5105 case DeclarationName::CXXDestructorName:
5106 case DeclarationName::CXXConversionFunctionName:
5107 AddTypeRef(Name.getCXXNameType(), Record);
5110 case DeclarationName::CXXOperatorName:
5111 Record.push_back(Name.getCXXOverloadedOperator());
5114 case DeclarationName::CXXLiteralOperatorName:
5115 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5118 case DeclarationName::CXXUsingDirective:
5119 // No extra data to emit
5124 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5125 DeclarationName Name, RecordDataImpl &Record) {
5126 switch (Name.getNameKind()) {
5127 case DeclarationName::CXXConstructorName:
5128 case DeclarationName::CXXDestructorName:
5129 case DeclarationName::CXXConversionFunctionName:
5130 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5133 case DeclarationName::CXXOperatorName:
5135 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5138 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5142 case DeclarationName::CXXLiteralOperatorName:
5144 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5148 case DeclarationName::Identifier:
5149 case DeclarationName::ObjCZeroArgSelector:
5150 case DeclarationName::ObjCOneArgSelector:
5151 case DeclarationName::ObjCMultiArgSelector:
5152 case DeclarationName::CXXUsingDirective:
5157 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5158 RecordDataImpl &Record) {
5159 AddDeclarationName(NameInfo.getName(), Record);
5160 AddSourceLocation(NameInfo.getLoc(), Record);
5161 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5164 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
5165 RecordDataImpl &Record) {
5166 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
5167 Record.push_back(Info.NumTemplParamLists);
5168 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5169 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5172 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
5173 RecordDataImpl &Record) {
5174 // Nested name specifiers usually aren't too long. I think that 8 would
5175 // typically accommodate the vast majority.
5176 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5178 // Push each of the NNS's onto a stack for serialization in reverse order.
5180 NestedNames.push_back(NNS);
5181 NNS = NNS->getPrefix();
5184 Record.push_back(NestedNames.size());
5185 while(!NestedNames.empty()) {
5186 NNS = NestedNames.pop_back_val();
5187 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5188 Record.push_back(Kind);
5190 case NestedNameSpecifier::Identifier:
5191 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5194 case NestedNameSpecifier::Namespace:
5195 AddDeclRef(NNS->getAsNamespace(), Record);
5198 case NestedNameSpecifier::NamespaceAlias:
5199 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5202 case NestedNameSpecifier::TypeSpec:
5203 case NestedNameSpecifier::TypeSpecWithTemplate:
5204 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5205 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5208 case NestedNameSpecifier::Global:
5209 // Don't need to write an associated value.
5215 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5216 RecordDataImpl &Record) {
5217 // Nested name specifiers usually aren't too long. I think that 8 would
5218 // typically accommodate the vast majority.
5219 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5221 // Push each of the nested-name-specifiers's onto a stack for
5222 // serialization in reverse order.
5224 NestedNames.push_back(NNS);
5225 NNS = NNS.getPrefix();
5228 Record.push_back(NestedNames.size());
5229 while(!NestedNames.empty()) {
5230 NNS = NestedNames.pop_back_val();
5231 NestedNameSpecifier::SpecifierKind Kind
5232 = NNS.getNestedNameSpecifier()->getKind();
5233 Record.push_back(Kind);
5235 case NestedNameSpecifier::Identifier:
5236 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5237 AddSourceRange(NNS.getLocalSourceRange(), Record);
5240 case NestedNameSpecifier::Namespace:
5241 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5242 AddSourceRange(NNS.getLocalSourceRange(), Record);
5245 case NestedNameSpecifier::NamespaceAlias:
5246 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5247 AddSourceRange(NNS.getLocalSourceRange(), Record);
5250 case NestedNameSpecifier::TypeSpec:
5251 case NestedNameSpecifier::TypeSpecWithTemplate:
5252 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5253 AddTypeLoc(NNS.getTypeLoc(), Record);
5254 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5257 case NestedNameSpecifier::Global:
5258 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5264 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
5265 TemplateName::NameKind Kind = Name.getKind();
5266 Record.push_back(Kind);
5268 case TemplateName::Template:
5269 AddDeclRef(Name.getAsTemplateDecl(), Record);
5272 case TemplateName::OverloadedTemplate: {
5273 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5274 Record.push_back(OvT->size());
5275 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
5277 AddDeclRef(*I, Record);
5281 case TemplateName::QualifiedTemplate: {
5282 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5283 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5284 Record.push_back(QualT->hasTemplateKeyword());
5285 AddDeclRef(QualT->getTemplateDecl(), Record);
5289 case TemplateName::DependentTemplate: {
5290 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5291 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5292 Record.push_back(DepT->isIdentifier());
5293 if (DepT->isIdentifier())
5294 AddIdentifierRef(DepT->getIdentifier(), Record);
5296 Record.push_back(DepT->getOperator());
5300 case TemplateName::SubstTemplateTemplateParm: {
5301 SubstTemplateTemplateParmStorage *subst
5302 = Name.getAsSubstTemplateTemplateParm();
5303 AddDeclRef(subst->getParameter(), Record);
5304 AddTemplateName(subst->getReplacement(), Record);
5308 case TemplateName::SubstTemplateTemplateParmPack: {
5309 SubstTemplateTemplateParmPackStorage *SubstPack
5310 = Name.getAsSubstTemplateTemplateParmPack();
5311 AddDeclRef(SubstPack->getParameterPack(), Record);
5312 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5318 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
5319 RecordDataImpl &Record) {
5320 Record.push_back(Arg.getKind());
5321 switch (Arg.getKind()) {
5322 case TemplateArgument::Null:
5324 case TemplateArgument::Type:
5325 AddTypeRef(Arg.getAsType(), Record);
5327 case TemplateArgument::Declaration:
5328 AddDeclRef(Arg.getAsDecl(), Record);
5329 Record.push_back(Arg.isDeclForReferenceParam());
5331 case TemplateArgument::NullPtr:
5332 AddTypeRef(Arg.getNullPtrType(), Record);
5334 case TemplateArgument::Integral:
5335 AddAPSInt(Arg.getAsIntegral(), Record);
5336 AddTypeRef(Arg.getIntegralType(), Record);
5338 case TemplateArgument::Template:
5339 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5341 case TemplateArgument::TemplateExpansion:
5342 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5343 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5344 Record.push_back(*NumExpansions + 1);
5346 Record.push_back(0);
5348 case TemplateArgument::Expression:
5349 AddStmt(Arg.getAsExpr());
5351 case TemplateArgument::Pack:
5352 Record.push_back(Arg.pack_size());
5353 for (const auto &P : Arg.pack_elements())
5354 AddTemplateArgument(P, Record);
5360 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
5361 RecordDataImpl &Record) {
5362 assert(TemplateParams && "No TemplateParams!");
5363 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5364 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5365 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5366 Record.push_back(TemplateParams->size());
5367 for (TemplateParameterList::const_iterator
5368 P = TemplateParams->begin(), PEnd = TemplateParams->end();
5370 AddDeclRef(*P, Record);
5373 /// \brief Emit a template argument list.
5375 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
5376 RecordDataImpl &Record) {
5377 assert(TemplateArgs && "No TemplateArgs!");
5378 Record.push_back(TemplateArgs->size());
5379 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5380 AddTemplateArgument(TemplateArgs->get(i), Record);
5384 ASTWriter::AddASTTemplateArgumentListInfo
5385 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5386 assert(ASTTemplArgList && "No ASTTemplArgList!");
5387 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5388 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5389 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5390 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5391 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5392 AddTemplateArgumentLoc(TemplArgs[i], Record);
5396 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
5397 Record.push_back(Set.size());
5398 for (ASTUnresolvedSet::const_iterator
5399 I = Set.begin(), E = Set.end(); I != E; ++I) {
5400 AddDeclRef(I.getDecl(), Record);
5401 Record.push_back(I.getAccess());
5405 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
5406 RecordDataImpl &Record) {
5407 Record.push_back(Base.isVirtual());
5408 Record.push_back(Base.isBaseOfClass());
5409 Record.push_back(Base.getAccessSpecifierAsWritten());
5410 Record.push_back(Base.getInheritConstructors());
5411 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
5412 AddSourceRange(Base.getSourceRange(), Record);
5413 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5418 void ASTWriter::FlushCXXBaseSpecifiers() {
5420 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
5423 // Record the offset of this base-specifier set.
5424 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5425 if (Index == CXXBaseSpecifiersOffsets.size())
5426 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5428 if (Index > CXXBaseSpecifiersOffsets.size())
5429 CXXBaseSpecifiersOffsets.resize(Index + 1);
5430 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5433 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5434 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5435 Record.push_back(BEnd - B);
5436 for (; B != BEnd; ++B)
5437 AddCXXBaseSpecifier(*B, Record);
5438 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5440 // Flush any expressions that were written as part of the base specifiers.
5444 CXXBaseSpecifiersToWrite.clear();
5447 void ASTWriter::AddCXXCtorInitializers(
5448 const CXXCtorInitializer * const *CtorInitializers,
5449 unsigned NumCtorInitializers,
5450 RecordDataImpl &Record) {
5451 Record.push_back(NumCtorInitializers);
5452 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5453 const CXXCtorInitializer *Init = CtorInitializers[i];
5455 if (Init->isBaseInitializer()) {
5456 Record.push_back(CTOR_INITIALIZER_BASE);
5457 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5458 Record.push_back(Init->isBaseVirtual());
5459 } else if (Init->isDelegatingInitializer()) {
5460 Record.push_back(CTOR_INITIALIZER_DELEGATING);
5461 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5462 } else if (Init->isMemberInitializer()){
5463 Record.push_back(CTOR_INITIALIZER_MEMBER);
5464 AddDeclRef(Init->getMember(), Record);
5466 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5467 AddDeclRef(Init->getIndirectMember(), Record);
5470 AddSourceLocation(Init->getMemberLocation(), Record);
5471 AddStmt(Init->getInit());
5472 AddSourceLocation(Init->getLParenLoc(), Record);
5473 AddSourceLocation(Init->getRParenLoc(), Record);
5474 Record.push_back(Init->isWritten());
5475 if (Init->isWritten()) {
5476 Record.push_back(Init->getSourceOrder());
5478 Record.push_back(Init->getNumArrayIndices());
5479 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5480 AddDeclRef(Init->getArrayIndex(i), Record);
5485 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
5486 auto &Data = D->data();
5487 Record.push_back(Data.IsLambda);
5488 Record.push_back(Data.UserDeclaredConstructor);
5489 Record.push_back(Data.UserDeclaredSpecialMembers);
5490 Record.push_back(Data.Aggregate);
5491 Record.push_back(Data.PlainOldData);
5492 Record.push_back(Data.Empty);
5493 Record.push_back(Data.Polymorphic);
5494 Record.push_back(Data.Abstract);
5495 Record.push_back(Data.IsStandardLayout);
5496 Record.push_back(Data.HasNoNonEmptyBases);
5497 Record.push_back(Data.HasPrivateFields);
5498 Record.push_back(Data.HasProtectedFields);
5499 Record.push_back(Data.HasPublicFields);
5500 Record.push_back(Data.HasMutableFields);
5501 Record.push_back(Data.HasVariantMembers);
5502 Record.push_back(Data.HasOnlyCMembers);
5503 Record.push_back(Data.HasInClassInitializer);
5504 Record.push_back(Data.HasUninitializedReferenceMember);
5505 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5506 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5507 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5508 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5509 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5510 Record.push_back(Data.DefaultedDestructorIsDeleted);
5511 Record.push_back(Data.HasTrivialSpecialMembers);
5512 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
5513 Record.push_back(Data.HasIrrelevantDestructor);
5514 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5515 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5516 Record.push_back(Data.HasConstexprDefaultConstructor);
5517 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5518 Record.push_back(Data.ComputedVisibleConversions);
5519 Record.push_back(Data.UserProvidedDefaultConstructor);
5520 Record.push_back(Data.DeclaredSpecialMembers);
5521 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5522 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5523 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5524 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5525 // IsLambda bit is already saved.
5527 Record.push_back(Data.NumBases);
5528 if (Data.NumBases > 0)
5529 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5532 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5533 Record.push_back(Data.NumVBases);
5534 if (Data.NumVBases > 0)
5535 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5538 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5539 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5540 // Data.Definition is the owning decl, no need to write it.
5541 AddDeclRef(D->getFirstFriend(), Record);
5543 // Add lambda-specific data.
5544 if (Data.IsLambda) {
5545 auto &Lambda = D->getLambdaData();
5546 Record.push_back(Lambda.Dependent);
5547 Record.push_back(Lambda.IsGenericLambda);
5548 Record.push_back(Lambda.CaptureDefault);
5549 Record.push_back(Lambda.NumCaptures);
5550 Record.push_back(Lambda.NumExplicitCaptures);
5551 Record.push_back(Lambda.ManglingNumber);
5552 AddDeclRef(Lambda.ContextDecl, Record);
5553 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5554 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5555 const LambdaCapture &Capture = Lambda.Captures[I];
5556 AddSourceLocation(Capture.getLocation(), Record);
5557 Record.push_back(Capture.isImplicit());
5558 Record.push_back(Capture.getCaptureKind());
5559 switch (Capture.getCaptureKind()) {
5565 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5566 AddDeclRef(Var, Record);
5567 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5576 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5577 assert(Reader && "Cannot remove chain");
5578 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5579 assert(FirstDeclID == NextDeclID &&
5580 FirstTypeID == NextTypeID &&
5581 FirstIdentID == NextIdentID &&
5582 FirstMacroID == NextMacroID &&
5583 FirstSubmoduleID == NextSubmoduleID &&
5584 FirstSelectorID == NextSelectorID &&
5585 "Setting chain after writing has started.");
5589 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5590 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5591 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5592 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5593 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5594 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5595 NextDeclID = FirstDeclID;
5596 NextTypeID = FirstTypeID;
5597 NextIdentID = FirstIdentID;
5598 NextMacroID = FirstMacroID;
5599 NextSelectorID = FirstSelectorID;
5600 NextSubmoduleID = FirstSubmoduleID;
5603 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5604 // Always keep the highest ID. See \p TypeRead() for more information.
5605 IdentID &StoredID = IdentifierIDs[II];
5610 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5611 // Always keep the highest ID. See \p TypeRead() for more information.
5612 MacroID &StoredID = MacroIDs[MI];
5617 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5618 // Always take the highest-numbered type index. This copes with an interesting
5619 // case for chained AST writing where we schedule writing the type and then,
5620 // later, deserialize the type from another AST. In this case, we want to
5621 // keep the higher-numbered entry so that we can properly write it out to
5623 TypeIdx &StoredIdx = TypeIdxs[T];
5624 if (Idx.getIndex() >= StoredIdx.getIndex())
5628 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5629 // Always keep the highest ID. See \p TypeRead() for more information.
5630 SelectorID &StoredID = SelectorIDs[S];
5635 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5636 MacroDefinition *MD) {
5637 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5638 MacroDefinitions[MD] = ID;
5641 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5642 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5643 SubmoduleIDs[Mod] = ID;
5646 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5647 assert(D->isCompleteDefinition());
5648 assert(!WritingAST && "Already writing the AST!");
5649 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5650 // We are interested when a PCH decl is modified.
5651 if (RD->isFromASTFile()) {
5652 // A forward reference was mutated into a definition. Rewrite it.
5653 // FIXME: This happens during template instantiation, should we
5654 // have created a new definition decl instead ?
5655 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5656 "completed a tag from another module but not by instantiation?");
5657 DeclUpdates[RD].push_back(
5658 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5663 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5664 assert(!WritingAST && "Already writing the AST!");
5666 // TU and namespaces are handled elsewhere.
5667 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5670 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5671 return; // Not a source decl added to a DeclContext from PCH.
5673 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5674 AddUpdatedDeclContext(DC);
5675 UpdatingVisibleDecls.push_back(D);
5678 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5679 assert(!WritingAST && "Already writing the AST!");
5680 assert(D->isImplicit());
5681 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5682 return; // Not a source member added to a class from PCH.
5683 if (!isa<CXXMethodDecl>(D))
5684 return; // We are interested in lazily declared implicit methods.
5686 // A decl coming from PCH was modified.
5687 assert(RD->isCompleteDefinition());
5688 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5691 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5692 const ClassTemplateSpecializationDecl *D) {
5693 // The specializations set is kept in the canonical template.
5694 assert(!WritingAST && "Already writing the AST!");
5695 TD = TD->getCanonicalDecl();
5696 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5697 return; // Not a source specialization added to a template from PCH.
5699 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5703 void ASTWriter::AddedCXXTemplateSpecialization(
5704 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5705 // The specializations set is kept in the canonical template.
5706 assert(!WritingAST && "Already writing the AST!");
5707 TD = TD->getCanonicalDecl();
5708 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5709 return; // Not a source specialization added to a template from PCH.
5711 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5715 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5716 const FunctionDecl *D) {
5717 // The specializations set is kept in the canonical template.
5718 assert(!WritingAST && "Already writing the AST!");
5719 TD = TD->getCanonicalDecl();
5720 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5721 return; // Not a source specialization added to a template from PCH.
5723 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5727 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5728 assert(!WritingAST && "Already writing the AST!");
5729 FD = FD->getCanonicalDecl();
5730 if (!FD->isFromASTFile())
5731 return; // Not a function declared in PCH and defined outside.
5733 DeclUpdates[FD].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5736 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5737 assert(!WritingAST && "Already writing the AST!");
5738 FD = FD->getCanonicalDecl();
5739 if (!FD->isFromASTFile())
5740 return; // Not a function declared in PCH and defined outside.
5742 DeclUpdates[FD].push_back(DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5745 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5746 assert(!WritingAST && "Already writing the AST!");
5747 if (!D->isFromASTFile())
5748 return; // Declaration not imported from PCH.
5750 // Implicit function decl from a PCH was defined.
5751 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5754 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5755 assert(!WritingAST && "Already writing the AST!");
5756 if (!D->isFromASTFile())
5759 DeclUpdates[D].push_back(
5760 DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5763 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5764 assert(!WritingAST && "Already writing the AST!");
5765 if (!D->isFromASTFile())
5768 // Since the actual instantiation is delayed, this really means that we need
5769 // to update the instantiation location.
5770 DeclUpdates[D].push_back(
5771 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5772 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5775 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5776 const ObjCInterfaceDecl *IFD) {
5777 assert(!WritingAST && "Already writing the AST!");
5778 if (!IFD->isFromASTFile())
5779 return; // Declaration not imported from PCH.
5781 assert(IFD->getDefinition() && "Category on a class without a definition?");
5782 ObjCClassesWithCategories.insert(
5783 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5787 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5788 const ObjCPropertyDecl *OrigProp,
5789 const ObjCCategoryDecl *ClassExt) {
5790 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5794 assert(!WritingAST && "Already writing the AST!");
5795 if (!D->isFromASTFile())
5796 return; // Declaration not imported from PCH.
5801 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5802 assert(!WritingAST && "Already writing the AST!");
5803 if (!D->isFromASTFile())
5806 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));