1 //===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
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 "ASTReaderInternals.h"
17 #include "MultiOnDiskHashTable.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/LambdaCapture.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/RawCommentList.h"
30 #include "clang/AST/TemplateName.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLocVisitor.h"
33 #include "clang/Basic/DiagnosticOptions.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/FileSystemOptions.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Basic/Module.h"
39 #include "clang/Basic/ObjCRuntime.h"
40 #include "clang/Basic/SourceManager.h"
41 #include "clang/Basic/SourceManagerInternals.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/TargetOptions.h"
44 #include "clang/Basic/Version.h"
45 #include "clang/Basic/VersionTuple.h"
46 #include "clang/Lex/HeaderSearch.h"
47 #include "clang/Lex/HeaderSearchOptions.h"
48 #include "clang/Lex/MacroInfo.h"
49 #include "clang/Lex/ModuleMap.h"
50 #include "clang/Lex/PreprocessingRecord.h"
51 #include "clang/Lex/Preprocessor.h"
52 #include "clang/Lex/PreprocessorOptions.h"
53 #include "clang/Lex/Token.h"
54 #include "clang/Sema/IdentifierResolver.h"
55 #include "clang/Sema/ObjCMethodList.h"
56 #include "clang/Sema/Sema.h"
57 #include "clang/Sema/Weak.h"
58 #include "clang/Serialization/ASTReader.h"
59 #include "clang/Serialization/Module.h"
60 #include "clang/Serialization/ModuleFileExtension.h"
61 #include "clang/Serialization/SerializationDiagnostic.h"
62 #include "llvm/ADT/APFloat.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/Hashing.h"
65 #include "llvm/ADT/IntrusiveRefCntPtr.h"
66 #include "llvm/ADT/Optional.h"
67 #include "llvm/ADT/SmallSet.h"
68 #include "llvm/ADT/SmallString.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/StringExtras.h"
71 #include "llvm/Bitcode/BitCodes.h"
72 #include "llvm/Bitcode/BitstreamWriter.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/Compression.h"
75 #include "llvm/Support/EndianStream.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/MemoryBuffer.h"
78 #include "llvm/Support/OnDiskHashTable.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/Process.h"
81 #include "llvm/Support/raw_ostream.h"
93 using namespace clang;
94 using namespace clang::serialization;
96 template <typename T, typename Allocator>
97 static StringRef bytes(const std::vector<T, Allocator> &v) {
98 if (v.empty()) return StringRef();
99 return StringRef(reinterpret_cast<const char*>(&v[0]),
100 sizeof(T) * v.size());
103 template <typename T>
104 static StringRef bytes(const SmallVectorImpl<T> &v) {
105 return StringRef(reinterpret_cast<const char*>(v.data()),
106 sizeof(T) * v.size());
109 //===----------------------------------------------------------------------===//
110 // Type serialization
111 //===----------------------------------------------------------------------===//
115 class ASTTypeWriter {
117 ASTRecordWriter Record;
119 /// \brief Type code that corresponds to the record generated.
121 /// \brief Abbreviation to use for the record, if any.
122 unsigned AbbrevToUse;
125 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
126 : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
129 return Record.Emit(Code, AbbrevToUse);
132 void Visit(QualType T) {
133 if (T.hasLocalNonFastQualifiers()) {
134 Qualifiers Qs = T.getLocalQualifiers();
135 Record.AddTypeRef(T.getLocalUnqualifiedType());
136 Record.push_back(Qs.getAsOpaqueValue());
137 Code = TYPE_EXT_QUAL;
138 AbbrevToUse = Writer.TypeExtQualAbbrev;
140 switch (T->getTypeClass()) {
141 // For all of the concrete, non-dependent types, call the
142 // appropriate visitor function.
143 #define TYPE(Class, Base) \
144 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
145 #define ABSTRACT_TYPE(Class, Base)
146 #include "clang/AST/TypeNodes.def"
151 void VisitArrayType(const ArrayType *T);
152 void VisitFunctionType(const FunctionType *T);
153 void VisitTagType(const TagType *T);
155 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
156 #define ABSTRACT_TYPE(Class, Base)
157 #include "clang/AST/TypeNodes.def"
160 } // end namespace clang
162 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
163 llvm_unreachable("Built-in types are never serialized");
166 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
167 Record.AddTypeRef(T->getElementType());
171 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
172 Record.AddTypeRef(T->getPointeeType());
176 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
177 Record.AddTypeRef(T->getOriginalType());
181 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
182 Record.AddTypeRef(T->getOriginalType());
183 Record.AddTypeRef(T->getAdjustedType());
184 Code = TYPE_ADJUSTED;
187 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
188 Record.AddTypeRef(T->getPointeeType());
189 Code = TYPE_BLOCK_POINTER;
192 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
193 Record.AddTypeRef(T->getPointeeTypeAsWritten());
194 Record.push_back(T->isSpelledAsLValue());
195 Code = TYPE_LVALUE_REFERENCE;
198 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
199 Record.AddTypeRef(T->getPointeeTypeAsWritten());
200 Code = TYPE_RVALUE_REFERENCE;
203 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
204 Record.AddTypeRef(T->getPointeeType());
205 Record.AddTypeRef(QualType(T->getClass(), 0));
206 Code = TYPE_MEMBER_POINTER;
209 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
210 Record.AddTypeRef(T->getElementType());
211 Record.push_back(T->getSizeModifier()); // FIXME: stable values
212 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
215 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
217 Record.AddAPInt(T->getSize());
218 Code = TYPE_CONSTANT_ARRAY;
221 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
223 Code = TYPE_INCOMPLETE_ARRAY;
226 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
228 Record.AddSourceLocation(T->getLBracketLoc());
229 Record.AddSourceLocation(T->getRBracketLoc());
230 Record.AddStmt(T->getSizeExpr());
231 Code = TYPE_VARIABLE_ARRAY;
234 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
235 Record.AddTypeRef(T->getElementType());
236 Record.push_back(T->getNumElements());
237 Record.push_back(T->getVectorKind());
241 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
243 Code = TYPE_EXT_VECTOR;
246 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
247 Record.AddTypeRef(T->getReturnType());
248 FunctionType::ExtInfo C = T->getExtInfo();
249 Record.push_back(C.getNoReturn());
250 Record.push_back(C.getHasRegParm());
251 Record.push_back(C.getRegParm());
252 // FIXME: need to stabilize encoding of calling convention...
253 Record.push_back(C.getCC());
254 Record.push_back(C.getProducesResult());
256 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
260 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
261 VisitFunctionType(T);
262 Code = TYPE_FUNCTION_NO_PROTO;
265 static void addExceptionSpec(const FunctionProtoType *T,
266 ASTRecordWriter &Record) {
267 Record.push_back(T->getExceptionSpecType());
268 if (T->getExceptionSpecType() == EST_Dynamic) {
269 Record.push_back(T->getNumExceptions());
270 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
271 Record.AddTypeRef(T->getExceptionType(I));
272 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
273 Record.AddStmt(T->getNoexceptExpr());
274 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
275 Record.AddDeclRef(T->getExceptionSpecDecl());
276 Record.AddDeclRef(T->getExceptionSpecTemplate());
277 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
278 Record.AddDeclRef(T->getExceptionSpecDecl());
282 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
283 VisitFunctionType(T);
285 Record.push_back(T->isVariadic());
286 Record.push_back(T->hasTrailingReturn());
287 Record.push_back(T->getTypeQuals());
288 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
289 addExceptionSpec(T, Record);
291 Record.push_back(T->getNumParams());
292 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
293 Record.AddTypeRef(T->getParamType(I));
295 if (T->hasExtParameterInfos()) {
296 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
297 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
300 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
301 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
302 T->hasExtParameterInfos())
305 Code = TYPE_FUNCTION_PROTO;
308 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
309 Record.AddDeclRef(T->getDecl());
310 Code = TYPE_UNRESOLVED_USING;
313 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
314 Record.AddDeclRef(T->getDecl());
315 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
316 Record.AddTypeRef(T->getCanonicalTypeInternal());
320 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
321 Record.AddStmt(T->getUnderlyingExpr());
322 Code = TYPE_TYPEOF_EXPR;
325 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
326 Record.AddTypeRef(T->getUnderlyingType());
330 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
331 Record.AddTypeRef(T->getUnderlyingType());
332 Record.AddStmt(T->getUnderlyingExpr());
333 Code = TYPE_DECLTYPE;
336 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
337 Record.AddTypeRef(T->getBaseType());
338 Record.AddTypeRef(T->getUnderlyingType());
339 Record.push_back(T->getUTTKind());
340 Code = TYPE_UNARY_TRANSFORM;
343 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
344 Record.AddTypeRef(T->getDeducedType());
345 Record.push_back((unsigned)T->getKeyword());
346 if (T->getDeducedType().isNull())
347 Record.push_back(T->isDependentType());
351 void ASTTypeWriter::VisitTagType(const TagType *T) {
352 Record.push_back(T->isDependentType());
353 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
354 assert(!T->isBeingDefined() &&
355 "Cannot serialize in the middle of a type definition");
358 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
363 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
368 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
369 Record.AddTypeRef(T->getModifiedType());
370 Record.AddTypeRef(T->getEquivalentType());
371 Record.push_back(T->getAttrKind());
372 Code = TYPE_ATTRIBUTED;
376 ASTTypeWriter::VisitSubstTemplateTypeParmType(
377 const SubstTemplateTypeParmType *T) {
378 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
379 Record.AddTypeRef(T->getReplacementType());
380 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
384 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
385 const SubstTemplateTypeParmPackType *T) {
386 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
387 Record.AddTemplateArgument(T->getArgumentPack());
388 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
392 ASTTypeWriter::VisitTemplateSpecializationType(
393 const TemplateSpecializationType *T) {
394 Record.push_back(T->isDependentType());
395 Record.AddTemplateName(T->getTemplateName());
396 Record.push_back(T->getNumArgs());
397 for (const auto &ArgI : *T)
398 Record.AddTemplateArgument(ArgI);
399 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
400 : T->isCanonicalUnqualified()
402 : T->getCanonicalTypeInternal());
403 Code = TYPE_TEMPLATE_SPECIALIZATION;
407 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
409 Record.AddStmt(T->getSizeExpr());
410 Record.AddSourceRange(T->getBracketsRange());
411 Code = TYPE_DEPENDENT_SIZED_ARRAY;
415 ASTTypeWriter::VisitDependentSizedExtVectorType(
416 const DependentSizedExtVectorType *T) {
417 // FIXME: Serialize this type (C++ only)
418 llvm_unreachable("Cannot serialize dependent sized extended vector types");
422 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
423 Record.push_back(T->getDepth());
424 Record.push_back(T->getIndex());
425 Record.push_back(T->isParameterPack());
426 Record.AddDeclRef(T->getDecl());
427 Code = TYPE_TEMPLATE_TYPE_PARM;
431 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
432 Record.push_back(T->getKeyword());
433 Record.AddNestedNameSpecifier(T->getQualifier());
434 Record.AddIdentifierRef(T->getIdentifier());
436 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
437 Code = TYPE_DEPENDENT_NAME;
441 ASTTypeWriter::VisitDependentTemplateSpecializationType(
442 const DependentTemplateSpecializationType *T) {
443 Record.push_back(T->getKeyword());
444 Record.AddNestedNameSpecifier(T->getQualifier());
445 Record.AddIdentifierRef(T->getIdentifier());
446 Record.push_back(T->getNumArgs());
447 for (const auto &I : *T)
448 Record.AddTemplateArgument(I);
449 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
452 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
453 Record.AddTypeRef(T->getPattern());
454 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
455 Record.push_back(*NumExpansions + 1);
458 Code = TYPE_PACK_EXPANSION;
461 void ASTTypeWriter::VisitParenType(const ParenType *T) {
462 Record.AddTypeRef(T->getInnerType());
466 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
467 Record.push_back(T->getKeyword());
468 Record.AddNestedNameSpecifier(T->getQualifier());
469 Record.AddTypeRef(T->getNamedType());
470 Code = TYPE_ELABORATED;
473 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
474 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
475 Record.AddTypeRef(T->getInjectedSpecializationType());
476 Code = TYPE_INJECTED_CLASS_NAME;
479 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
480 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
481 Code = TYPE_OBJC_INTERFACE;
484 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
485 Record.AddDeclRef(T->getDecl());
486 Record.push_back(T->getNumProtocols());
487 for (const auto *I : T->quals())
488 Record.AddDeclRef(I);
489 Code = TYPE_OBJC_TYPE_PARAM;
492 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
493 Record.AddTypeRef(T->getBaseType());
494 Record.push_back(T->getTypeArgsAsWritten().size());
495 for (auto TypeArg : T->getTypeArgsAsWritten())
496 Record.AddTypeRef(TypeArg);
497 Record.push_back(T->getNumProtocols());
498 for (const auto *I : T->quals())
499 Record.AddDeclRef(I);
500 Record.push_back(T->isKindOfTypeAsWritten());
501 Code = TYPE_OBJC_OBJECT;
505 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
506 Record.AddTypeRef(T->getPointeeType());
507 Code = TYPE_OBJC_OBJECT_POINTER;
511 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
512 Record.AddTypeRef(T->getValueType());
517 ASTTypeWriter::VisitPipeType(const PipeType *T) {
518 Record.AddTypeRef(T->getElementType());
519 Record.push_back(T->isReadOnly());
525 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
526 ASTRecordWriter &Record;
529 TypeLocWriter(ASTRecordWriter &Record)
532 #define ABSTRACT_TYPELOC(CLASS, PARENT)
533 #define TYPELOC(CLASS, PARENT) \
534 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
535 #include "clang/AST/TypeLocNodes.def"
537 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
538 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
541 } // end anonymous namespace
543 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
547 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
548 Record.AddSourceLocation(TL.getBuiltinLoc());
549 if (TL.needsExtraLocalData()) {
550 Record.push_back(TL.getWrittenTypeSpec());
551 Record.push_back(TL.getWrittenSignSpec());
552 Record.push_back(TL.getWrittenWidthSpec());
553 Record.push_back(TL.hasModeAttr());
557 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
558 Record.AddSourceLocation(TL.getNameLoc());
561 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
562 Record.AddSourceLocation(TL.getStarLoc());
565 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
569 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
573 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
574 Record.AddSourceLocation(TL.getCaretLoc());
577 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
578 Record.AddSourceLocation(TL.getAmpLoc());
581 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
582 Record.AddSourceLocation(TL.getAmpAmpLoc());
585 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
586 Record.AddSourceLocation(TL.getStarLoc());
587 Record.AddTypeSourceInfo(TL.getClassTInfo());
590 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
591 Record.AddSourceLocation(TL.getLBracketLoc());
592 Record.AddSourceLocation(TL.getRBracketLoc());
593 Record.push_back(TL.getSizeExpr() ? 1 : 0);
594 if (TL.getSizeExpr())
595 Record.AddStmt(TL.getSizeExpr());
598 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
599 VisitArrayTypeLoc(TL);
602 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
603 VisitArrayTypeLoc(TL);
606 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
607 VisitArrayTypeLoc(TL);
610 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
611 DependentSizedArrayTypeLoc TL) {
612 VisitArrayTypeLoc(TL);
615 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
616 DependentSizedExtVectorTypeLoc TL) {
617 Record.AddSourceLocation(TL.getNameLoc());
620 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
621 Record.AddSourceLocation(TL.getNameLoc());
624 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
625 Record.AddSourceLocation(TL.getNameLoc());
628 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
629 Record.AddSourceLocation(TL.getLocalRangeBegin());
630 Record.AddSourceLocation(TL.getLParenLoc());
631 Record.AddSourceLocation(TL.getRParenLoc());
632 Record.AddSourceLocation(TL.getLocalRangeEnd());
633 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
634 Record.AddDeclRef(TL.getParam(i));
636 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
637 VisitFunctionTypeLoc(TL);
639 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
640 VisitFunctionTypeLoc(TL);
642 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
643 Record.AddSourceLocation(TL.getNameLoc());
645 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
646 Record.AddSourceLocation(TL.getNameLoc());
648 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
649 if (TL.getNumProtocols()) {
650 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
651 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
653 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
654 Record.AddSourceLocation(TL.getProtocolLoc(i));
656 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
657 Record.AddSourceLocation(TL.getTypeofLoc());
658 Record.AddSourceLocation(TL.getLParenLoc());
659 Record.AddSourceLocation(TL.getRParenLoc());
662 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
663 Record.AddSourceLocation(TL.getTypeofLoc());
664 Record.AddSourceLocation(TL.getLParenLoc());
665 Record.AddSourceLocation(TL.getRParenLoc());
666 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
669 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
670 Record.AddSourceLocation(TL.getNameLoc());
673 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
674 Record.AddSourceLocation(TL.getKWLoc());
675 Record.AddSourceLocation(TL.getLParenLoc());
676 Record.AddSourceLocation(TL.getRParenLoc());
677 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
680 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
681 Record.AddSourceLocation(TL.getNameLoc());
684 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
685 Record.AddSourceLocation(TL.getNameLoc());
688 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
689 Record.AddSourceLocation(TL.getNameLoc());
692 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
693 Record.AddSourceLocation(TL.getAttrNameLoc());
694 if (TL.hasAttrOperand()) {
695 SourceRange range = TL.getAttrOperandParensRange();
696 Record.AddSourceLocation(range.getBegin());
697 Record.AddSourceLocation(range.getEnd());
699 if (TL.hasAttrExprOperand()) {
700 Expr *operand = TL.getAttrExprOperand();
701 Record.push_back(operand ? 1 : 0);
702 if (operand) Record.AddStmt(operand);
703 } else if (TL.hasAttrEnumOperand()) {
704 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
708 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
709 Record.AddSourceLocation(TL.getNameLoc());
712 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
713 SubstTemplateTypeParmTypeLoc TL) {
714 Record.AddSourceLocation(TL.getNameLoc());
717 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
718 SubstTemplateTypeParmPackTypeLoc TL) {
719 Record.AddSourceLocation(TL.getNameLoc());
722 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
723 TemplateSpecializationTypeLoc TL) {
724 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
725 Record.AddSourceLocation(TL.getTemplateNameLoc());
726 Record.AddSourceLocation(TL.getLAngleLoc());
727 Record.AddSourceLocation(TL.getRAngleLoc());
728 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
729 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
730 TL.getArgLoc(i).getLocInfo());
733 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
734 Record.AddSourceLocation(TL.getLParenLoc());
735 Record.AddSourceLocation(TL.getRParenLoc());
738 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
739 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
740 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
743 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
744 Record.AddSourceLocation(TL.getNameLoc());
747 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
748 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
749 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
750 Record.AddSourceLocation(TL.getNameLoc());
753 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
754 DependentTemplateSpecializationTypeLoc TL) {
755 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
756 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
757 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
758 Record.AddSourceLocation(TL.getTemplateNameLoc());
759 Record.AddSourceLocation(TL.getLAngleLoc());
760 Record.AddSourceLocation(TL.getRAngleLoc());
761 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
762 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
763 TL.getArgLoc(I).getLocInfo());
766 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
767 Record.AddSourceLocation(TL.getEllipsisLoc());
770 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
771 Record.AddSourceLocation(TL.getNameLoc());
774 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
775 Record.push_back(TL.hasBaseTypeAsWritten());
776 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
777 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
778 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
779 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
780 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
781 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
782 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
783 Record.AddSourceLocation(TL.getProtocolLoc(i));
786 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
787 Record.AddSourceLocation(TL.getStarLoc());
790 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
791 Record.AddSourceLocation(TL.getKWLoc());
792 Record.AddSourceLocation(TL.getLParenLoc());
793 Record.AddSourceLocation(TL.getRParenLoc());
796 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
797 Record.AddSourceLocation(TL.getKWLoc());
800 void ASTWriter::WriteTypeAbbrevs() {
801 using namespace llvm;
803 std::shared_ptr<BitCodeAbbrev> Abv;
805 // Abbreviation for TYPE_EXT_QUAL
806 Abv = std::make_shared<BitCodeAbbrev>();
807 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
808 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
809 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
810 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
812 // Abbreviation for TYPE_FUNCTION_PROTO
813 Abv = std::make_shared<BitCodeAbbrev>();
814 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
816 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
817 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
818 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
819 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
820 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
821 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
823 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
824 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
825 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
826 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
827 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
828 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
829 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
830 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
831 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
834 //===----------------------------------------------------------------------===//
835 // ASTWriter Implementation
836 //===----------------------------------------------------------------------===//
838 static void EmitBlockID(unsigned ID, const char *Name,
839 llvm::BitstreamWriter &Stream,
840 ASTWriter::RecordDataImpl &Record) {
842 Record.push_back(ID);
843 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
845 // Emit the block name if present.
846 if (!Name || Name[0] == 0)
850 Record.push_back(*Name++);
851 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
854 static void EmitRecordID(unsigned ID, const char *Name,
855 llvm::BitstreamWriter &Stream,
856 ASTWriter::RecordDataImpl &Record) {
858 Record.push_back(ID);
860 Record.push_back(*Name++);
861 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
864 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
865 ASTWriter::RecordDataImpl &Record) {
866 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
868 RECORD(STMT_NULL_PTR);
869 RECORD(STMT_REF_PTR);
871 RECORD(STMT_COMPOUND);
873 RECORD(STMT_DEFAULT);
875 RECORD(STMT_ATTRIBUTED);
882 RECORD(STMT_INDIRECT_GOTO);
883 RECORD(STMT_CONTINUE);
889 RECORD(EXPR_PREDEFINED);
890 RECORD(EXPR_DECL_REF);
891 RECORD(EXPR_INTEGER_LITERAL);
892 RECORD(EXPR_FLOATING_LITERAL);
893 RECORD(EXPR_IMAGINARY_LITERAL);
894 RECORD(EXPR_STRING_LITERAL);
895 RECORD(EXPR_CHARACTER_LITERAL);
897 RECORD(EXPR_PAREN_LIST);
898 RECORD(EXPR_UNARY_OPERATOR);
899 RECORD(EXPR_SIZEOF_ALIGN_OF);
900 RECORD(EXPR_ARRAY_SUBSCRIPT);
903 RECORD(EXPR_BINARY_OPERATOR);
904 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
905 RECORD(EXPR_CONDITIONAL_OPERATOR);
906 RECORD(EXPR_IMPLICIT_CAST);
907 RECORD(EXPR_CSTYLE_CAST);
908 RECORD(EXPR_COMPOUND_LITERAL);
909 RECORD(EXPR_EXT_VECTOR_ELEMENT);
910 RECORD(EXPR_INIT_LIST);
911 RECORD(EXPR_DESIGNATED_INIT);
912 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
913 RECORD(EXPR_IMPLICIT_VALUE_INIT);
914 RECORD(EXPR_NO_INIT);
916 RECORD(EXPR_ADDR_LABEL);
919 RECORD(EXPR_GNU_NULL);
920 RECORD(EXPR_SHUFFLE_VECTOR);
922 RECORD(EXPR_GENERIC_SELECTION);
923 RECORD(EXPR_OBJC_STRING_LITERAL);
924 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
925 RECORD(EXPR_OBJC_ARRAY_LITERAL);
926 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
927 RECORD(EXPR_OBJC_ENCODE);
928 RECORD(EXPR_OBJC_SELECTOR_EXPR);
929 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
930 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
931 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
932 RECORD(EXPR_OBJC_KVC_REF_EXPR);
933 RECORD(EXPR_OBJC_MESSAGE_EXPR);
934 RECORD(STMT_OBJC_FOR_COLLECTION);
935 RECORD(STMT_OBJC_CATCH);
936 RECORD(STMT_OBJC_FINALLY);
937 RECORD(STMT_OBJC_AT_TRY);
938 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
939 RECORD(STMT_OBJC_AT_THROW);
940 RECORD(EXPR_OBJC_BOOL_LITERAL);
941 RECORD(STMT_CXX_CATCH);
942 RECORD(STMT_CXX_TRY);
943 RECORD(STMT_CXX_FOR_RANGE);
944 RECORD(EXPR_CXX_OPERATOR_CALL);
945 RECORD(EXPR_CXX_MEMBER_CALL);
946 RECORD(EXPR_CXX_CONSTRUCT);
947 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
948 RECORD(EXPR_CXX_STATIC_CAST);
949 RECORD(EXPR_CXX_DYNAMIC_CAST);
950 RECORD(EXPR_CXX_REINTERPRET_CAST);
951 RECORD(EXPR_CXX_CONST_CAST);
952 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
953 RECORD(EXPR_USER_DEFINED_LITERAL);
954 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
955 RECORD(EXPR_CXX_BOOL_LITERAL);
956 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
957 RECORD(EXPR_CXX_TYPEID_EXPR);
958 RECORD(EXPR_CXX_TYPEID_TYPE);
959 RECORD(EXPR_CXX_THIS);
960 RECORD(EXPR_CXX_THROW);
961 RECORD(EXPR_CXX_DEFAULT_ARG);
962 RECORD(EXPR_CXX_DEFAULT_INIT);
963 RECORD(EXPR_CXX_BIND_TEMPORARY);
964 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
965 RECORD(EXPR_CXX_NEW);
966 RECORD(EXPR_CXX_DELETE);
967 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
968 RECORD(EXPR_EXPR_WITH_CLEANUPS);
969 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
970 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
971 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
972 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
973 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
974 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
975 RECORD(EXPR_CXX_NOEXCEPT);
976 RECORD(EXPR_OPAQUE_VALUE);
977 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
978 RECORD(EXPR_TYPE_TRAIT);
979 RECORD(EXPR_ARRAY_TYPE_TRAIT);
980 RECORD(EXPR_PACK_EXPANSION);
981 RECORD(EXPR_SIZEOF_PACK);
982 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
983 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
984 RECORD(EXPR_FUNCTION_PARM_PACK);
985 RECORD(EXPR_MATERIALIZE_TEMPORARY);
986 RECORD(EXPR_CUDA_KERNEL_CALL);
987 RECORD(EXPR_CXX_UUIDOF_EXPR);
988 RECORD(EXPR_CXX_UUIDOF_TYPE);
993 void ASTWriter::WriteBlockInfoBlock() {
995 Stream.EnterBlockInfoBlock();
997 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
998 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1001 BLOCK(CONTROL_BLOCK);
1004 RECORD(MODULE_NAME);
1005 RECORD(MODULE_DIRECTORY);
1006 RECORD(MODULE_MAP_FILE);
1008 RECORD(ORIGINAL_FILE);
1009 RECORD(ORIGINAL_PCH_DIR);
1010 RECORD(ORIGINAL_FILE_ID);
1011 RECORD(INPUT_FILE_OFFSETS);
1013 BLOCK(OPTIONS_BLOCK);
1014 RECORD(LANGUAGE_OPTIONS);
1015 RECORD(TARGET_OPTIONS);
1016 RECORD(DIAGNOSTIC_OPTIONS);
1017 RECORD(FILE_SYSTEM_OPTIONS);
1018 RECORD(HEADER_SEARCH_OPTIONS);
1019 RECORD(PREPROCESSOR_OPTIONS);
1021 BLOCK(INPUT_FILES_BLOCK);
1024 // AST Top-Level Block.
1026 RECORD(TYPE_OFFSET);
1027 RECORD(DECL_OFFSET);
1028 RECORD(IDENTIFIER_OFFSET);
1029 RECORD(IDENTIFIER_TABLE);
1030 RECORD(EAGERLY_DESERIALIZED_DECLS);
1031 RECORD(SPECIAL_TYPES);
1033 RECORD(TENTATIVE_DEFINITIONS);
1034 RECORD(SELECTOR_OFFSETS);
1035 RECORD(METHOD_POOL);
1036 RECORD(PP_COUNTER_VALUE);
1037 RECORD(SOURCE_LOCATION_OFFSETS);
1038 RECORD(SOURCE_LOCATION_PRELOADS);
1039 RECORD(EXT_VECTOR_DECLS);
1040 RECORD(UNUSED_FILESCOPED_DECLS);
1041 RECORD(PPD_ENTITIES_OFFSETS);
1042 RECORD(VTABLE_USES);
1043 RECORD(REFERENCED_SELECTOR_POOL);
1044 RECORD(TU_UPDATE_LEXICAL);
1045 RECORD(SEMA_DECL_REFS);
1046 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1047 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1048 RECORD(UPDATE_VISIBLE);
1049 RECORD(DECL_UPDATE_OFFSETS);
1050 RECORD(DECL_UPDATES);
1051 RECORD(DIAG_PRAGMA_MAPPINGS);
1052 RECORD(CUDA_SPECIAL_DECL_REFS);
1053 RECORD(HEADER_SEARCH_TABLE);
1054 RECORD(FP_PRAGMA_OPTIONS);
1055 RECORD(OPENCL_EXTENSIONS);
1056 RECORD(OPENCL_EXTENSION_TYPES);
1057 RECORD(OPENCL_EXTENSION_DECLS);
1058 RECORD(DELEGATING_CTORS);
1059 RECORD(KNOWN_NAMESPACES);
1060 RECORD(MODULE_OFFSET_MAP);
1061 RECORD(SOURCE_MANAGER_LINE_TABLE);
1062 RECORD(OBJC_CATEGORIES_MAP);
1063 RECORD(FILE_SORTED_DECLS);
1064 RECORD(IMPORTED_MODULES);
1065 RECORD(OBJC_CATEGORIES);
1066 RECORD(MACRO_OFFSET);
1067 RECORD(INTERESTING_IDENTIFIERS);
1068 RECORD(UNDEFINED_BUT_USED);
1069 RECORD(LATE_PARSED_TEMPLATE);
1070 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1071 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1072 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1073 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1074 RECORD(DELETE_EXPRS_TO_ANALYZE);
1075 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1077 // SourceManager Block.
1078 BLOCK(SOURCE_MANAGER_BLOCK);
1079 RECORD(SM_SLOC_FILE_ENTRY);
1080 RECORD(SM_SLOC_BUFFER_ENTRY);
1081 RECORD(SM_SLOC_BUFFER_BLOB);
1082 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1083 RECORD(SM_SLOC_EXPANSION_ENTRY);
1085 // Preprocessor Block.
1086 BLOCK(PREPROCESSOR_BLOCK);
1087 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1088 RECORD(PP_MACRO_FUNCTION_LIKE);
1089 RECORD(PP_MACRO_OBJECT_LIKE);
1090 RECORD(PP_MODULE_MACRO);
1094 BLOCK(SUBMODULE_BLOCK);
1095 RECORD(SUBMODULE_METADATA);
1096 RECORD(SUBMODULE_DEFINITION);
1097 RECORD(SUBMODULE_UMBRELLA_HEADER);
1098 RECORD(SUBMODULE_HEADER);
1099 RECORD(SUBMODULE_TOPHEADER);
1100 RECORD(SUBMODULE_UMBRELLA_DIR);
1101 RECORD(SUBMODULE_IMPORTS);
1102 RECORD(SUBMODULE_EXPORTS);
1103 RECORD(SUBMODULE_REQUIRES);
1104 RECORD(SUBMODULE_EXCLUDED_HEADER);
1105 RECORD(SUBMODULE_LINK_LIBRARY);
1106 RECORD(SUBMODULE_CONFIG_MACRO);
1107 RECORD(SUBMODULE_CONFLICT);
1108 RECORD(SUBMODULE_PRIVATE_HEADER);
1109 RECORD(SUBMODULE_TEXTUAL_HEADER);
1110 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1111 RECORD(SUBMODULE_INITIALIZERS);
1114 BLOCK(COMMENTS_BLOCK);
1115 RECORD(COMMENTS_RAW_COMMENT);
1117 // Decls and Types block.
1118 BLOCK(DECLTYPES_BLOCK);
1119 RECORD(TYPE_EXT_QUAL);
1120 RECORD(TYPE_COMPLEX);
1121 RECORD(TYPE_POINTER);
1122 RECORD(TYPE_BLOCK_POINTER);
1123 RECORD(TYPE_LVALUE_REFERENCE);
1124 RECORD(TYPE_RVALUE_REFERENCE);
1125 RECORD(TYPE_MEMBER_POINTER);
1126 RECORD(TYPE_CONSTANT_ARRAY);
1127 RECORD(TYPE_INCOMPLETE_ARRAY);
1128 RECORD(TYPE_VARIABLE_ARRAY);
1129 RECORD(TYPE_VECTOR);
1130 RECORD(TYPE_EXT_VECTOR);
1131 RECORD(TYPE_FUNCTION_NO_PROTO);
1132 RECORD(TYPE_FUNCTION_PROTO);
1133 RECORD(TYPE_TYPEDEF);
1134 RECORD(TYPE_TYPEOF_EXPR);
1135 RECORD(TYPE_TYPEOF);
1136 RECORD(TYPE_RECORD);
1138 RECORD(TYPE_OBJC_INTERFACE);
1139 RECORD(TYPE_OBJC_OBJECT_POINTER);
1140 RECORD(TYPE_DECLTYPE);
1141 RECORD(TYPE_ELABORATED);
1142 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1143 RECORD(TYPE_UNRESOLVED_USING);
1144 RECORD(TYPE_INJECTED_CLASS_NAME);
1145 RECORD(TYPE_OBJC_OBJECT);
1146 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1147 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1148 RECORD(TYPE_DEPENDENT_NAME);
1149 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1150 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1152 RECORD(TYPE_PACK_EXPANSION);
1153 RECORD(TYPE_ATTRIBUTED);
1154 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1156 RECORD(TYPE_UNARY_TRANSFORM);
1157 RECORD(TYPE_ATOMIC);
1158 RECORD(TYPE_DECAYED);
1159 RECORD(TYPE_ADJUSTED);
1160 RECORD(TYPE_OBJC_TYPE_PARAM);
1161 RECORD(LOCAL_REDECLARATIONS);
1162 RECORD(DECL_TYPEDEF);
1163 RECORD(DECL_TYPEALIAS);
1165 RECORD(DECL_RECORD);
1166 RECORD(DECL_ENUM_CONSTANT);
1167 RECORD(DECL_FUNCTION);
1168 RECORD(DECL_OBJC_METHOD);
1169 RECORD(DECL_OBJC_INTERFACE);
1170 RECORD(DECL_OBJC_PROTOCOL);
1171 RECORD(DECL_OBJC_IVAR);
1172 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1173 RECORD(DECL_OBJC_CATEGORY);
1174 RECORD(DECL_OBJC_CATEGORY_IMPL);
1175 RECORD(DECL_OBJC_IMPLEMENTATION);
1176 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1177 RECORD(DECL_OBJC_PROPERTY);
1178 RECORD(DECL_OBJC_PROPERTY_IMPL);
1180 RECORD(DECL_MS_PROPERTY);
1182 RECORD(DECL_IMPLICIT_PARAM);
1183 RECORD(DECL_PARM_VAR);
1184 RECORD(DECL_FILE_SCOPE_ASM);
1186 RECORD(DECL_CONTEXT_LEXICAL);
1187 RECORD(DECL_CONTEXT_VISIBLE);
1188 RECORD(DECL_NAMESPACE);
1189 RECORD(DECL_NAMESPACE_ALIAS);
1191 RECORD(DECL_USING_SHADOW);
1192 RECORD(DECL_USING_DIRECTIVE);
1193 RECORD(DECL_UNRESOLVED_USING_VALUE);
1194 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1195 RECORD(DECL_LINKAGE_SPEC);
1196 RECORD(DECL_CXX_RECORD);
1197 RECORD(DECL_CXX_METHOD);
1198 RECORD(DECL_CXX_CONSTRUCTOR);
1199 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
1200 RECORD(DECL_CXX_DESTRUCTOR);
1201 RECORD(DECL_CXX_CONVERSION);
1202 RECORD(DECL_ACCESS_SPEC);
1203 RECORD(DECL_FRIEND);
1204 RECORD(DECL_FRIEND_TEMPLATE);
1205 RECORD(DECL_CLASS_TEMPLATE);
1206 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1207 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1208 RECORD(DECL_VAR_TEMPLATE);
1209 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1210 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1211 RECORD(DECL_FUNCTION_TEMPLATE);
1212 RECORD(DECL_TEMPLATE_TYPE_PARM);
1213 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1214 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1215 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1216 RECORD(DECL_STATIC_ASSERT);
1217 RECORD(DECL_CXX_BASE_SPECIFIERS);
1218 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1219 RECORD(DECL_INDIRECTFIELD);
1220 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1221 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1222 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1223 RECORD(DECL_IMPORT);
1224 RECORD(DECL_OMP_THREADPRIVATE);
1226 RECORD(DECL_OBJC_TYPE_PARAM);
1227 RECORD(DECL_OMP_CAPTUREDEXPR);
1228 RECORD(DECL_PRAGMA_COMMENT);
1229 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1230 RECORD(DECL_OMP_DECLARE_REDUCTION);
1232 // Statements and Exprs can occur in the Decls and Types block.
1233 AddStmtsExprs(Stream, Record);
1235 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1236 RECORD(PPD_MACRO_EXPANSION);
1237 RECORD(PPD_MACRO_DEFINITION);
1238 RECORD(PPD_INCLUSION_DIRECTIVE);
1240 // Decls and Types block.
1241 BLOCK(EXTENSION_BLOCK);
1242 RECORD(EXTENSION_METADATA);
1249 /// \brief Prepares a path for being written to an AST file by converting it
1250 /// to an absolute path and removing nested './'s.
1252 /// \return \c true if the path was changed.
1253 static bool cleanPathForOutput(FileManager &FileMgr,
1254 SmallVectorImpl<char> &Path) {
1255 bool Changed = FileMgr.makeAbsolutePath(Path);
1256 return Changed | llvm::sys::path::remove_dots(Path);
1259 /// \brief Adjusts the given filename to only write out the portion of the
1260 /// filename that is not part of the system root directory.
1262 /// \param Filename the file name to adjust.
1264 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1265 /// the returned filename will be adjusted by this root directory.
1267 /// \returns either the original filename (if it needs no adjustment) or the
1268 /// adjusted filename (which points into the @p Filename parameter).
1270 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1271 assert(Filename && "No file name to adjust?");
1273 if (BaseDir.empty())
1276 // Verify that the filename and the system root have the same prefix.
1278 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1279 if (Filename[Pos] != BaseDir[Pos])
1280 return Filename; // Prefixes don't match.
1282 // We hit the end of the filename before we hit the end of the system root.
1286 // If there's not a path separator at the end of the base directory nor
1287 // immediately after it, then this isn't within the base directory.
1288 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1289 if (!llvm::sys::path::is_separator(BaseDir.back()))
1292 // If the file name has a '/' at the current position, skip over the '/'.
1293 // We distinguish relative paths from absolute paths by the
1294 // absence of '/' at the beginning of relative paths.
1296 // FIXME: This is wrong. We distinguish them by asking if the path is
1297 // absolute, which isn't the same thing. And there might be multiple '/'s
1298 // in a row. Use a better mechanism to indicate whether we have emitted an
1299 // absolute or relative path.
1303 return Filename + Pos;
1306 static ASTFileSignature getSignature() {
1308 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1310 // Rely on GetRandomNumber to eventually return non-zero...
1314 /// \brief Write the control block.
1315 uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1316 ASTContext &Context,
1318 const std::string &OutputFile) {
1319 ASTFileSignature Signature = 0;
1321 using namespace llvm;
1322 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1326 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1327 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1328 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1329 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1330 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1331 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1332 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1333 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1334 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1335 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1336 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1337 assert((!WritingModule || isysroot.empty()) &&
1338 "writing module as a relocatable PCH?");
1340 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1341 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1342 !isysroot.empty(), IncludeTimestamps,
1343 ASTHasCompilerErrors};
1344 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1345 getClangFullRepositoryVersion());
1347 if (WritingModule) {
1348 // For implicit modules we output a signature that we can use to ensure
1349 // duplicate module builds don't collide in the cache as their output order
1350 // is non-deterministic.
1351 // FIXME: Remove this when output is deterministic.
1352 if (Context.getLangOpts().ImplicitModules) {
1353 Signature = getSignature();
1354 RecordData::value_type Record[] = {Signature};
1355 Stream.EmitRecord(SIGNATURE, Record);
1359 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1360 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1361 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1362 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1363 RecordData::value_type Record[] = {MODULE_NAME};
1364 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1367 if (WritingModule && WritingModule->Directory) {
1368 SmallString<128> BaseDir(WritingModule->Directory->getName());
1369 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1371 // If the home of the module is the current working directory, then we
1372 // want to pick up the cwd of the build process loading the module, not
1373 // our cwd, when we load this module.
1374 if (!PP.getHeaderSearchInfo()
1375 .getHeaderSearchOpts()
1376 .ModuleMapFileHomeIsCwd ||
1377 WritingModule->Directory->getName() != StringRef(".")) {
1378 // Module directory.
1379 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1380 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1382 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1384 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1385 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1388 // Write out all other paths relative to the base directory if possible.
1389 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1390 } else if (!isysroot.empty()) {
1391 // Write out paths relative to the sysroot if possible.
1392 BaseDirectory = isysroot;
1396 if (WritingModule) {
1399 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1401 // Primary module map file.
1402 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1404 // Additional module map files.
1405 if (auto *AdditionalModMaps =
1406 Map.getAdditionalModuleMapFiles(WritingModule)) {
1407 Record.push_back(AdditionalModMaps->size());
1408 for (const FileEntry *F : *AdditionalModMaps)
1409 AddPath(F->getName(), Record);
1411 Record.push_back(0);
1414 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1419 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1422 for (auto *M : Mgr) {
1423 // Skip modules that weren't directly imported.
1424 if (!M->isDirectlyImported())
1427 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1428 AddSourceLocation(M->ImportLoc, Record);
1429 Record.push_back(M->File->getSize());
1430 Record.push_back(getTimestampForOutput(M->File));
1431 Record.push_back(M->Signature);
1432 AddPath(M->FileName, Record);
1434 Stream.EmitRecord(IMPORTS, Record);
1437 // Write the options block.
1438 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1440 // Language options.
1442 const LangOptions &LangOpts = Context.getLangOpts();
1443 #define LANGOPT(Name, Bits, Default, Description) \
1444 Record.push_back(LangOpts.Name);
1445 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1446 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1447 #include "clang/Basic/LangOptions.def"
1448 #define SANITIZER(NAME, ID) \
1449 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1450 #include "clang/Basic/Sanitizers.def"
1452 Record.push_back(LangOpts.ModuleFeatures.size());
1453 for (StringRef Feature : LangOpts.ModuleFeatures)
1454 AddString(Feature, Record);
1456 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1457 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1459 AddString(LangOpts.CurrentModule, Record);
1462 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1463 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1464 AddString(I, Record);
1466 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1468 // OpenMP offloading options.
1469 Record.push_back(LangOpts.OMPTargetTriples.size());
1470 for (auto &T : LangOpts.OMPTargetTriples)
1471 AddString(T.getTriple(), Record);
1473 AddString(LangOpts.OMPHostIRFile, Record);
1475 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1479 const TargetInfo &Target = Context.getTargetInfo();
1480 const TargetOptions &TargetOpts = Target.getTargetOpts();
1481 AddString(TargetOpts.Triple, Record);
1482 AddString(TargetOpts.CPU, Record);
1483 AddString(TargetOpts.ABI, Record);
1484 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1485 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1486 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1488 Record.push_back(TargetOpts.Features.size());
1489 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1490 AddString(TargetOpts.Features[I], Record);
1492 Stream.EmitRecord(TARGET_OPTIONS, Record);
1494 // Diagnostic options.
1496 const DiagnosticOptions &DiagOpts
1497 = Context.getDiagnostics().getDiagnosticOptions();
1498 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1499 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1500 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1501 #include "clang/Basic/DiagnosticOptions.def"
1502 Record.push_back(DiagOpts.Warnings.size());
1503 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1504 AddString(DiagOpts.Warnings[I], Record);
1505 Record.push_back(DiagOpts.Remarks.size());
1506 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1507 AddString(DiagOpts.Remarks[I], Record);
1508 // Note: we don't serialize the log or serialization file names, because they
1509 // are generally transient files and will almost always be overridden.
1510 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1512 // File system options.
1514 const FileSystemOptions &FSOpts =
1515 Context.getSourceManager().getFileManager().getFileSystemOpts();
1516 AddString(FSOpts.WorkingDir, Record);
1517 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1519 // Header search options.
1521 const HeaderSearchOptions &HSOpts
1522 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1523 AddString(HSOpts.Sysroot, Record);
1526 Record.push_back(HSOpts.UserEntries.size());
1527 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1528 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1529 AddString(Entry.Path, Record);
1530 Record.push_back(static_cast<unsigned>(Entry.Group));
1531 Record.push_back(Entry.IsFramework);
1532 Record.push_back(Entry.IgnoreSysRoot);
1535 // System header prefixes.
1536 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1537 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1538 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1539 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1542 AddString(HSOpts.ResourceDir, Record);
1543 AddString(HSOpts.ModuleCachePath, Record);
1544 AddString(HSOpts.ModuleUserBuildPath, Record);
1545 Record.push_back(HSOpts.DisableModuleHash);
1546 Record.push_back(HSOpts.UseBuiltinIncludes);
1547 Record.push_back(HSOpts.UseStandardSystemIncludes);
1548 Record.push_back(HSOpts.UseStandardCXXIncludes);
1549 Record.push_back(HSOpts.UseLibcxx);
1550 // Write out the specific module cache path that contains the module files.
1551 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1552 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1554 // Preprocessor options.
1556 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1558 // Macro definitions.
1559 Record.push_back(PPOpts.Macros.size());
1560 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1561 AddString(PPOpts.Macros[I].first, Record);
1562 Record.push_back(PPOpts.Macros[I].second);
1566 Record.push_back(PPOpts.Includes.size());
1567 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1568 AddString(PPOpts.Includes[I], Record);
1571 Record.push_back(PPOpts.MacroIncludes.size());
1572 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1573 AddString(PPOpts.MacroIncludes[I], Record);
1575 Record.push_back(PPOpts.UsePredefines);
1576 // Detailed record is important since it is used for the module cache hash.
1577 Record.push_back(PPOpts.DetailedRecord);
1578 AddString(PPOpts.ImplicitPCHInclude, Record);
1579 AddString(PPOpts.ImplicitPTHInclude, Record);
1580 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1581 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1583 // Leave the options block.
1586 // Original file name and file ID
1587 SourceManager &SM = Context.getSourceManager();
1588 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1589 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1590 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1591 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1592 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1593 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1596 Record.push_back(ORIGINAL_FILE);
1597 Record.push_back(SM.getMainFileID().getOpaqueValue());
1598 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1602 Record.push_back(SM.getMainFileID().getOpaqueValue());
1603 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1605 // Original PCH directory
1606 if (!OutputFile.empty() && OutputFile != "-") {
1607 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1608 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1610 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1612 SmallString<128> OutputPath(OutputFile);
1614 SM.getFileManager().makeAbsolutePath(OutputPath);
1615 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1617 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1618 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1621 WriteInputFiles(Context.SourceMgr,
1622 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1623 PP.getLangOpts().Modules);
1630 /// \brief An input file.
1631 struct InputFileEntry {
1632 const FileEntry *File;
1635 bool BufferOverridden;
1638 } // end anonymous namespace
1640 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1641 HeaderSearchOptions &HSOpts,
1643 using namespace llvm;
1644 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1646 // Create input-file abbreviation.
1647 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1648 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1649 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1650 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1651 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1652 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1653 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1654 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1655 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1657 // Get all ContentCache objects for files, sorted by whether the file is a
1658 // system one or not. System files go at the back, users files at the front.
1659 std::deque<InputFileEntry> SortedFiles;
1660 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1661 // Get this source location entry.
1662 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1663 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1665 // We only care about file entries that were not overridden.
1666 if (!SLoc->isFile())
1668 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1669 if (!Cache->OrigEntry)
1672 InputFileEntry Entry;
1673 Entry.File = Cache->OrigEntry;
1674 Entry.IsSystemFile = Cache->IsSystemFile;
1675 Entry.IsTransient = Cache->IsTransient;
1676 Entry.BufferOverridden = Cache->BufferOverridden;
1677 if (Cache->IsSystemFile)
1678 SortedFiles.push_back(Entry);
1680 SortedFiles.push_front(Entry);
1683 unsigned UserFilesNum = 0;
1684 // Write out all of the input files.
1685 std::vector<uint64_t> InputFileOffsets;
1686 for (const auto &Entry : SortedFiles) {
1687 uint32_t &InputFileID = InputFileIDs[Entry.File];
1688 if (InputFileID != 0)
1689 continue; // already recorded this file.
1691 // Record this entry's offset.
1692 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1694 InputFileID = InputFileOffsets.size();
1696 if (!Entry.IsSystemFile)
1699 // Emit size/modification time for this file.
1700 // And whether this file was overridden.
1701 RecordData::value_type Record[] = {
1703 InputFileOffsets.size(),
1704 (uint64_t)Entry.File->getSize(),
1705 (uint64_t)getTimestampForOutput(Entry.File),
1706 Entry.BufferOverridden,
1709 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1714 // Create input file offsets abbreviation.
1715 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1716 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1717 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1718 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1720 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1721 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1723 // Write input file offsets.
1724 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1725 InputFileOffsets.size(), UserFilesNum};
1726 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1729 //===----------------------------------------------------------------------===//
1730 // Source Manager Serialization
1731 //===----------------------------------------------------------------------===//
1733 /// \brief Create an abbreviation for the SLocEntry that refers to a
1735 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1736 using namespace llvm;
1738 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1739 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1740 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1744 // FileEntry fields.
1745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1749 return Stream.EmitAbbrev(std::move(Abbrev));
1752 /// \brief Create an abbreviation for the SLocEntry that refers to a
1754 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1755 using namespace llvm;
1757 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1758 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1764 return Stream.EmitAbbrev(std::move(Abbrev));
1767 /// \brief Create an abbreviation for the SLocEntry that refers to a
1769 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1771 using namespace llvm;
1773 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1774 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1775 : SM_SLOC_BUFFER_BLOB));
1777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1779 return Stream.EmitAbbrev(std::move(Abbrev));
1782 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1784 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1785 using namespace llvm;
1787 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1788 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1790 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1791 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1792 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1793 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1794 return Stream.EmitAbbrev(std::move(Abbrev));
1799 // Trait used for the on-disk hash table of header search information.
1800 class HeaderFileInfoTrait {
1802 const HeaderSearch &HS;
1804 // Keep track of the framework names we've used during serialization.
1805 SmallVector<char, 128> FrameworkStringData;
1806 llvm::StringMap<unsigned> FrameworkNameOffset;
1809 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1810 : Writer(Writer), HS(HS) { }
1813 const FileEntry *FE;
1816 typedef const key_type &key_type_ref;
1818 typedef HeaderFileInfo data_type;
1819 typedef const data_type &data_type_ref;
1820 typedef unsigned hash_value_type;
1821 typedef unsigned offset_type;
1823 hash_value_type ComputeHash(key_type_ref key) {
1824 // The hash is based only on size/time of the file, so that the reader can
1825 // match even when symlinking or excess path elements ("foo/../", "../")
1826 // change the form of the name. However, complete path is still the key.
1827 return llvm::hash_combine(key.FE->getSize(),
1828 Writer.getTimestampForOutput(key.FE));
1831 std::pair<unsigned,unsigned>
1832 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1833 using namespace llvm::support;
1834 endian::Writer<little> LE(Out);
1835 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1836 LE.write<uint16_t>(KeyLen);
1837 unsigned DataLen = 1 + 2 + 4 + 4;
1838 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1839 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1841 LE.write<uint8_t>(DataLen);
1842 return std::make_pair(KeyLen, DataLen);
1845 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1846 using namespace llvm::support;
1847 endian::Writer<little> LE(Out);
1848 LE.write<uint64_t>(key.FE->getSize());
1850 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
1852 Out.write(key.Filename.data(), KeyLen);
1855 void EmitData(raw_ostream &Out, key_type_ref key,
1856 data_type_ref Data, unsigned DataLen) {
1857 using namespace llvm::support;
1858 endian::Writer<little> LE(Out);
1859 uint64_t Start = Out.tell(); (void)Start;
1861 unsigned char Flags = (Data.isImport << 4)
1862 | (Data.isPragmaOnce << 3)
1863 | (Data.DirInfo << 1)
1864 | Data.IndexHeaderMapHeader;
1865 LE.write<uint8_t>(Flags);
1866 LE.write<uint16_t>(Data.NumIncludes);
1868 if (!Data.ControllingMacro)
1869 LE.write<uint32_t>(Data.ControllingMacroID);
1871 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1873 unsigned Offset = 0;
1874 if (!Data.Framework.empty()) {
1875 // If this header refers into a framework, save the framework name.
1876 llvm::StringMap<unsigned>::iterator Pos
1877 = FrameworkNameOffset.find(Data.Framework);
1878 if (Pos == FrameworkNameOffset.end()) {
1879 Offset = FrameworkStringData.size() + 1;
1880 FrameworkStringData.append(Data.Framework.begin(),
1881 Data.Framework.end());
1882 FrameworkStringData.push_back(0);
1884 FrameworkNameOffset[Data.Framework] = Offset;
1886 Offset = Pos->second;
1888 LE.write<uint32_t>(Offset);
1890 // FIXME: If the header is excluded, we should write out some
1891 // record of that fact.
1892 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1893 if (uint32_t ModID =
1894 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1895 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1896 assert((Value >> 2) == ModID && "overflow in header module info");
1897 LE.write<uint32_t>(Value);
1901 assert(Out.tell() - Start == DataLen && "Wrong data length");
1904 const char *strings_begin() const { return FrameworkStringData.begin(); }
1905 const char *strings_end() const { return FrameworkStringData.end(); }
1908 } // end anonymous namespace
1910 /// \brief Write the header search block for the list of files that
1912 /// \param HS The header search structure to save.
1913 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1914 SmallVector<const FileEntry *, 16> FilesByUID;
1915 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1917 if (FilesByUID.size() > HS.header_file_size())
1918 FilesByUID.resize(HS.header_file_size());
1920 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1921 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1922 SmallVector<const char *, 4> SavedStrings;
1923 unsigned NumHeaderSearchEntries = 0;
1924 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1925 const FileEntry *File = FilesByUID[UID];
1929 // Get the file info. This will load info from the external source if
1930 // necessary. Skip emitting this file if we have no information on it
1931 // as a header file (in which case HFI will be null) or if it hasn't
1932 // changed since it was loaded. Also skip it if it's for a modular header
1933 // from a different module; in that case, we rely on the module(s)
1934 // containing the header to provide this information.
1935 const HeaderFileInfo *HFI =
1936 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1937 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1940 // Massage the file path into an appropriate form.
1941 StringRef Filename = File->getName();
1942 SmallString<128> FilenameTmp(Filename);
1943 if (PreparePathForOutput(FilenameTmp)) {
1944 // If we performed any translation on the file name at all, we need to
1945 // save this string, since the generator will refer to it later.
1946 Filename = StringRef(strdup(FilenameTmp.c_str()));
1947 SavedStrings.push_back(Filename.data());
1950 HeaderFileInfoTrait::key_type key = { File, Filename };
1951 Generator.insert(key, *HFI, GeneratorTrait);
1952 ++NumHeaderSearchEntries;
1955 // Create the on-disk hash table in a buffer.
1956 SmallString<4096> TableData;
1957 uint32_t BucketOffset;
1959 using namespace llvm::support;
1960 llvm::raw_svector_ostream Out(TableData);
1961 // Make sure that no bucket is at offset 0
1962 endian::Writer<little>(Out).write<uint32_t>(0);
1963 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1966 // Create a blob abbreviation
1967 using namespace llvm;
1969 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1970 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1971 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1972 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1973 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1974 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1975 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1977 // Write the header search table
1978 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1979 NumHeaderSearchEntries, TableData.size()};
1980 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1981 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1983 // Free all of the strings we had to duplicate.
1984 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1985 free(const_cast<char *>(SavedStrings[I]));
1988 /// \brief Writes the block containing the serialized form of the
1991 /// TODO: We should probably use an on-disk hash table (stored in a
1992 /// blob), indexed based on the file name, so that we only create
1993 /// entries for files that we actually need. In the common case (no
1994 /// errors), we probably won't have to create file entries for any of
1995 /// the files in the AST.
1996 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1997 const Preprocessor &PP) {
2000 // Enter the source manager block.
2001 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2003 // Abbreviations for the various kinds of source-location entries.
2004 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2005 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2006 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2007 unsigned SLocBufferBlobCompressedAbbrv =
2008 CreateSLocBufferBlobAbbrev(Stream, true);
2009 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2011 // Write out the source location entry table. We skip the first
2012 // entry, which is always the same dummy entry.
2013 std::vector<uint32_t> SLocEntryOffsets;
2014 RecordData PreloadSLocs;
2015 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2016 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2018 // Get this source location entry.
2019 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2020 FileID FID = FileID::get(I);
2021 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2023 // Record the offset of this source-location entry.
2024 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2026 // Figure out which record code to use.
2028 if (SLoc->isFile()) {
2029 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2030 if (Cache->OrigEntry) {
2031 Code = SM_SLOC_FILE_ENTRY;
2033 Code = SM_SLOC_BUFFER_ENTRY;
2035 Code = SM_SLOC_EXPANSION_ENTRY;
2037 Record.push_back(Code);
2039 // Starting offset of this entry within this module, so skip the dummy.
2040 Record.push_back(SLoc->getOffset() - 2);
2041 if (SLoc->isFile()) {
2042 const SrcMgr::FileInfo &File = SLoc->getFile();
2043 AddSourceLocation(File.getIncludeLoc(), Record);
2044 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2045 Record.push_back(File.hasLineDirectives());
2047 const SrcMgr::ContentCache *Content = File.getContentCache();
2048 bool EmitBlob = false;
2049 if (Content->OrigEntry) {
2050 assert(Content->OrigEntry == Content->ContentsEntry &&
2051 "Writing to AST an overridden file is not supported");
2053 // The source location entry is a file. Emit input file ID.
2054 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2055 Record.push_back(InputFileIDs[Content->OrigEntry]);
2057 Record.push_back(File.NumCreatedFIDs);
2059 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2060 if (FDI != FileDeclIDs.end()) {
2061 Record.push_back(FDI->second->FirstDeclIndex);
2062 Record.push_back(FDI->second->DeclIDs.size());
2064 Record.push_back(0);
2065 Record.push_back(0);
2068 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2070 if (Content->BufferOverridden || Content->IsTransient)
2073 // The source location entry is a buffer. The blob associated
2074 // with this entry contains the contents of the buffer.
2076 // We add one to the size so that we capture the trailing NULL
2077 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2078 // the reader side).
2079 const llvm::MemoryBuffer *Buffer
2080 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2081 StringRef Name = Buffer->getBufferIdentifier();
2082 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2083 StringRef(Name.data(), Name.size() + 1));
2086 if (Name == "<built-in>")
2087 PreloadSLocs.push_back(SLocEntryOffsets.size());
2091 // Include the implicit terminating null character in the on-disk buffer
2092 // if we're writing it uncompressed.
2093 const llvm::MemoryBuffer *Buffer =
2094 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2095 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2097 // Compress the buffer if possible. We expect that almost all PCM
2098 // consumers will not want its contents.
2099 SmallString<0> CompressedBuffer;
2100 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2101 llvm::zlib::StatusOK) {
2102 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2104 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2107 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2108 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2112 // The source location entry is a macro expansion.
2113 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2114 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2115 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2116 AddSourceLocation(Expansion.isMacroArgExpansion()
2118 : Expansion.getExpansionLocEnd(),
2121 // Compute the token length for this macro expansion.
2122 unsigned NextOffset = SourceMgr.getNextLocalOffset();
2124 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2125 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2126 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2132 if (SLocEntryOffsets.empty())
2135 // Write the source-location offsets table into the AST block. This
2136 // table is used for lazily loading source-location information.
2137 using namespace llvm;
2139 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2140 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2141 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2142 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2143 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2144 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2146 RecordData::value_type Record[] = {
2147 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2148 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2149 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2150 bytes(SLocEntryOffsets));
2152 // Write the source location entry preloads array, telling the AST
2153 // reader which source locations entries it should load eagerly.
2154 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2156 // Write the line table. It depends on remapping working, so it must come
2157 // after the source location offsets.
2158 if (SourceMgr.hasLineTable()) {
2159 LineTableInfo &LineTable = SourceMgr.getLineTable();
2163 // Emit the needed file names.
2164 llvm::DenseMap<int, int> FilenameMap;
2165 for (const auto &L : LineTable) {
2168 for (auto &LE : L.second) {
2169 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2170 FilenameMap.size())).second)
2171 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2174 Record.push_back(0);
2176 // Emit the line entries
2177 for (const auto &L : LineTable) {
2178 // Only emit entries for local files.
2183 Record.push_back(L.first.ID);
2185 // Emit the line entries
2186 Record.push_back(L.second.size());
2187 for (const auto &LE : L.second) {
2188 Record.push_back(LE.FileOffset);
2189 Record.push_back(LE.LineNo);
2190 Record.push_back(FilenameMap[LE.FilenameID]);
2191 Record.push_back((unsigned)LE.FileKind);
2192 Record.push_back(LE.IncludeOffset);
2196 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2200 //===----------------------------------------------------------------------===//
2201 // Preprocessor Serialization
2202 //===----------------------------------------------------------------------===//
2204 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2205 const Preprocessor &PP) {
2206 if (MacroInfo *MI = MD->getMacroInfo())
2207 if (MI->isBuiltinMacro())
2211 SourceLocation Loc = MD->getLocation();
2212 if (Loc.isInvalid())
2214 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2221 /// \brief Writes the block containing the serialized form of the
2224 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2225 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2227 WritePreprocessorDetail(*PPRec);
2230 RecordData ModuleMacroRecord;
2232 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2233 if (PP.getCounterValue() != 0) {
2234 RecordData::value_type Record[] = {PP.getCounterValue()};
2235 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2238 // Enter the preprocessor block.
2239 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2241 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2242 // FIXME: Include a location for the use, and say which one was used.
2243 if (PP.SawDateOrTime())
2244 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2246 // Loop over all the macro directives that are live at the end of the file,
2247 // emitting each to the PP section.
2249 // Construct the list of identifiers with macro directives that need to be
2251 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2252 for (auto &Id : PP.getIdentifierTable())
2253 if (Id.second->hadMacroDefinition() &&
2254 (!Id.second->isFromAST() ||
2255 Id.second->hasChangedSinceDeserialization()))
2256 MacroIdentifiers.push_back(Id.second);
2257 // Sort the set of macro definitions that need to be serialized by the
2258 // name of the macro, to provide a stable ordering.
2259 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2260 llvm::less_ptr<IdentifierInfo>());
2262 // Emit the macro directives as a list and associate the offset with the
2263 // identifier they belong to.
2264 for (const IdentifierInfo *Name : MacroIdentifiers) {
2265 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2266 auto StartOffset = Stream.GetCurrentBitNo();
2268 // Emit the macro directives in reverse source order.
2269 for (; MD; MD = MD->getPrevious()) {
2270 // Once we hit an ignored macro, we're done: the rest of the chain
2271 // will all be ignored macros.
2272 if (shouldIgnoreMacro(MD, IsModule, PP))
2275 AddSourceLocation(MD->getLocation(), Record);
2276 Record.push_back(MD->getKind());
2277 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2278 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2279 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2280 Record.push_back(VisMD->isPublic());
2284 // Write out any exported module macros.
2285 bool EmittedModuleMacros = false;
2286 // We write out exported module macros for PCH as well.
2287 auto Leafs = PP.getLeafModuleMacros(Name);
2288 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2289 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2290 while (!Worklist.empty()) {
2291 auto *Macro = Worklist.pop_back_val();
2293 // Emit a record indicating this submodule exports this macro.
2294 ModuleMacroRecord.push_back(
2295 getSubmoduleID(Macro->getOwningModule()));
2296 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2297 for (auto *M : Macro->overrides())
2298 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2300 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2301 ModuleMacroRecord.clear();
2303 // Enqueue overridden macros once we've visited all their ancestors.
2304 for (auto *M : Macro->overrides())
2305 if (++Visits[M] == M->getNumOverridingMacros())
2306 Worklist.push_back(M);
2308 EmittedModuleMacros = true;
2311 if (Record.empty() && !EmittedModuleMacros)
2314 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2315 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2319 /// \brief Offsets of each of the macros into the bitstream, indexed by
2320 /// the local macro ID
2322 /// For each identifier that is associated with a macro, this map
2323 /// provides the offset into the bitstream where that macro is
2325 std::vector<uint32_t> MacroOffsets;
2327 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2328 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2329 MacroInfo *MI = MacroInfosToEmit[I].MI;
2330 MacroID ID = MacroInfosToEmit[I].ID;
2332 if (ID < FirstMacroID) {
2333 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2337 // Record the local offset of this macro.
2338 unsigned Index = ID - FirstMacroID;
2339 if (Index == MacroOffsets.size())
2340 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2342 if (Index > MacroOffsets.size())
2343 MacroOffsets.resize(Index + 1);
2345 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2348 AddIdentifierRef(Name, Record);
2349 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2350 AddSourceLocation(MI->getDefinitionLoc(), Record);
2351 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2352 Record.push_back(MI->isUsed());
2353 Record.push_back(MI->isUsedForHeaderGuard());
2355 if (MI->isObjectLike()) {
2356 Code = PP_MACRO_OBJECT_LIKE;
2358 Code = PP_MACRO_FUNCTION_LIKE;
2360 Record.push_back(MI->isC99Varargs());
2361 Record.push_back(MI->isGNUVarargs());
2362 Record.push_back(MI->hasCommaPasting());
2363 Record.push_back(MI->getNumArgs());
2364 for (const IdentifierInfo *Arg : MI->args())
2365 AddIdentifierRef(Arg, Record);
2368 // If we have a detailed preprocessing record, record the macro definition
2369 // ID that corresponds to this macro.
2371 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2373 Stream.EmitRecord(Code, Record);
2376 // Emit the tokens array.
2377 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2378 // Note that we know that the preprocessor does not have any annotation
2379 // tokens in it because they are created by the parser, and thus can't
2380 // be in a macro definition.
2381 const Token &Tok = MI->getReplacementToken(TokNo);
2382 AddToken(Tok, Record);
2383 Stream.EmitRecord(PP_TOKEN, Record);
2391 // Write the offsets table for macro IDs.
2392 using namespace llvm;
2394 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2395 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2396 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2397 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2400 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2402 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2403 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2404 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2408 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2409 if (PPRec.local_begin() == PPRec.local_end())
2412 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2414 // Enter the preprocessor block.
2415 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2417 // If the preprocessor has a preprocessing record, emit it.
2418 unsigned NumPreprocessingRecords = 0;
2419 using namespace llvm;
2421 // Set up the abbreviation for
2422 unsigned InclusionAbbrev = 0;
2424 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2425 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2431 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2434 unsigned FirstPreprocessorEntityID
2435 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2436 + NUM_PREDEF_PP_ENTITY_IDS;
2437 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2439 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2440 EEnd = PPRec.local_end();
2442 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2445 PreprocessedEntityOffsets.push_back(
2446 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2448 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2449 // Record this macro definition's ID.
2450 MacroDefinitions[MD] = NextPreprocessorEntityID;
2452 AddIdentifierRef(MD->getName(), Record);
2453 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2457 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2458 Record.push_back(ME->isBuiltinMacro());
2459 if (ME->isBuiltinMacro())
2460 AddIdentifierRef(ME->getName(), Record);
2462 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2463 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2467 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2468 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2469 Record.push_back(ID->getFileName().size());
2470 Record.push_back(ID->wasInQuotes());
2471 Record.push_back(static_cast<unsigned>(ID->getKind()));
2472 Record.push_back(ID->importedModule());
2473 SmallString<64> Buffer;
2474 Buffer += ID->getFileName();
2475 // Check that the FileEntry is not null because it was not resolved and
2476 // we create a PCH even with compiler errors.
2478 Buffer += ID->getFile()->getName();
2479 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2483 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2487 // Write the offsets table for the preprocessing record.
2488 if (NumPreprocessingRecords > 0) {
2489 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2491 // Write the offsets table for identifier IDs.
2492 using namespace llvm;
2494 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2495 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2496 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2498 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2500 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2501 FirstPreprocessorEntityID -
2502 NUM_PREDEF_PP_ENTITY_IDS};
2503 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2504 bytes(PreprocessedEntityOffsets));
2508 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2512 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2513 if (Known != SubmoduleIDs.end())
2514 return Known->second;
2516 auto *Top = Mod->getTopLevelModule();
2517 if (Top != WritingModule &&
2518 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule)))
2521 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2524 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2525 // FIXME: This can easily happen, if we have a reference to a submodule that
2526 // did not result in us loading a module file for that submodule. For
2527 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2528 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2529 assert((ID || !Mod) &&
2530 "asked for module ID for non-local, non-imported module");
2534 /// \brief Compute the number of modules within the given tree (including the
2536 static unsigned getNumberOfModules(Module *Mod) {
2537 unsigned ChildModules = 0;
2538 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2539 Sub != SubEnd; ++Sub)
2540 ChildModules += getNumberOfModules(*Sub);
2542 return ChildModules + 1;
2545 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2546 // Enter the submodule description block.
2547 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2549 // Write the abbreviations needed for the submodules block.
2550 using namespace llvm;
2552 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2553 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2560 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2565 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2567 Abbrev = std::make_shared<BitCodeAbbrev>();
2568 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2570 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2572 Abbrev = std::make_shared<BitCodeAbbrev>();
2573 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2575 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2577 Abbrev = std::make_shared<BitCodeAbbrev>();
2578 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2579 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2580 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2582 Abbrev = std::make_shared<BitCodeAbbrev>();
2583 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2585 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2587 Abbrev = std::make_shared<BitCodeAbbrev>();
2588 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2590 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2591 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2593 Abbrev = std::make_shared<BitCodeAbbrev>();
2594 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2595 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2596 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2598 Abbrev = std::make_shared<BitCodeAbbrev>();
2599 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2601 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2603 Abbrev = std::make_shared<BitCodeAbbrev>();
2604 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2605 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2606 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2608 Abbrev = std::make_shared<BitCodeAbbrev>();
2609 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2611 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2613 Abbrev = std::make_shared<BitCodeAbbrev>();
2614 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2617 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2619 Abbrev = std::make_shared<BitCodeAbbrev>();
2620 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2622 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2624 Abbrev = std::make_shared<BitCodeAbbrev>();
2625 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2628 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2630 // Write the submodule metadata block.
2631 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2633 NUM_PREDEF_SUBMODULE_IDS};
2634 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2636 // Write all of the submodules.
2637 std::queue<Module *> Q;
2638 Q.push(WritingModule);
2639 while (!Q.empty()) {
2640 Module *Mod = Q.front();
2642 unsigned ID = getSubmoduleID(Mod);
2644 uint64_t ParentID = 0;
2646 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2647 ParentID = SubmoduleIDs[Mod->Parent];
2650 // Emit the definition of the block.
2652 RecordData::value_type Record[] = {
2653 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2654 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2655 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2656 Mod->ConfigMacrosExhaustive};
2657 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2660 // Emit the requirements.
2661 for (const auto &R : Mod->Requirements) {
2662 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2663 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2666 // Emit the umbrella header, if there is one.
2667 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2668 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2669 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2670 UmbrellaHeader.NameAsWritten);
2671 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2672 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2673 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2674 UmbrellaDir.NameAsWritten);
2677 // Emit the headers.
2679 unsigned RecordKind;
2681 Module::HeaderKind HeaderKind;
2683 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2684 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2685 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2686 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2687 Module::HK_PrivateTextual},
2688 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2690 for (auto &HL : HeaderLists) {
2691 RecordData::value_type Record[] = {HL.RecordKind};
2692 for (auto &H : Mod->Headers[HL.HeaderKind])
2693 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2696 // Emit the top headers.
2698 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2699 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2700 for (auto *H : TopHeaders)
2701 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2704 // Emit the imports.
2705 if (!Mod->Imports.empty()) {
2707 for (auto *I : Mod->Imports)
2708 Record.push_back(getSubmoduleID(I));
2709 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2712 // Emit the exports.
2713 if (!Mod->Exports.empty()) {
2715 for (const auto &E : Mod->Exports) {
2716 // FIXME: This may fail; we don't require that all exported modules
2717 // are local or imported.
2718 Record.push_back(getSubmoduleID(E.getPointer()));
2719 Record.push_back(E.getInt());
2721 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2724 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2725 // Might be unnecessary as use declarations are only used to build the
2728 // Emit the link libraries.
2729 for (const auto &LL : Mod->LinkLibraries) {
2730 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2732 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2735 // Emit the conflicts.
2736 for (const auto &C : Mod->Conflicts) {
2737 // FIXME: This may fail; we don't require that all conflicting modules
2738 // are local or imported.
2739 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2740 getSubmoduleID(C.Other)};
2741 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2744 // Emit the configuration macros.
2745 for (const auto &CM : Mod->ConfigMacros) {
2746 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2747 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2750 // Emit the initializers, if any.
2752 for (Decl *D : Context->getModuleInitializers(Mod))
2753 Inits.push_back(GetDeclRef(D));
2755 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2757 // Queue up the submodules of this module.
2758 for (auto *M : Mod->submodules())
2764 assert((NextSubmoduleID - FirstSubmoduleID ==
2765 getNumberOfModules(WritingModule)) &&
2766 "Wrong # of submodules; found a reference to a non-local, "
2767 "non-imported submodule?");
2770 serialization::SubmoduleID
2771 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2772 if (Loc.isInvalid() || !WritingModule)
2773 return 0; // No submodule
2775 // Find the module that owns this location.
2776 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2778 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2782 // Check whether this submodule is part of our own module.
2783 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2786 return getSubmoduleID(OwningMod);
2789 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2791 // Make sure set diagnostic pragmas don't affect the translation unit that
2792 // imports the module.
2793 // FIXME: Make diagnostic pragma sections work properly with modules.
2797 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2799 unsigned CurrID = 0;
2800 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2802 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2803 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2805 const DiagnosticsEngine::DiagStatePoint &point = *I;
2806 if (point.Loc.isInvalid())
2809 AddSourceLocation(point.Loc, Record);
2810 unsigned &DiagStateID = DiagStateIDMap[point.State];
2811 Record.push_back(DiagStateID);
2813 if (DiagStateID == 0) {
2814 DiagStateID = ++CurrID;
2815 for (const auto &I : *(point.State)) {
2816 if (I.second.isPragma()) {
2817 Record.push_back(I.first);
2818 Record.push_back((unsigned)I.second.getSeverity());
2821 Record.push_back(-1); // mark the end of the diag/map pairs for this
2826 if (!Record.empty())
2827 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2830 //===----------------------------------------------------------------------===//
2831 // Type Serialization
2832 //===----------------------------------------------------------------------===//
2834 /// \brief Write the representation of a type to the AST stream.
2835 void ASTWriter::WriteType(QualType T) {
2836 TypeIdx &IdxRef = TypeIdxs[T];
2837 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2838 IdxRef = TypeIdx(NextTypeID++);
2839 TypeIdx Idx = IdxRef;
2841 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2845 // Emit the type's representation.
2846 ASTTypeWriter W(*this, Record);
2848 uint64_t Offset = W.Emit();
2850 // Record the offset for this type.
2851 unsigned Index = Idx.getIndex() - FirstTypeID;
2852 if (TypeOffsets.size() == Index)
2853 TypeOffsets.push_back(Offset);
2854 else if (TypeOffsets.size() < Index) {
2855 TypeOffsets.resize(Index + 1);
2856 TypeOffsets[Index] = Offset;
2858 llvm_unreachable("Types emitted in wrong order");
2862 //===----------------------------------------------------------------------===//
2863 // Declaration Serialization
2864 //===----------------------------------------------------------------------===//
2866 /// \brief Write the block containing all of the declaration IDs
2867 /// lexically declared within the given DeclContext.
2869 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2870 /// bistream, or 0 if no block was written.
2871 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2873 if (DC->decls_empty())
2876 uint64_t Offset = Stream.GetCurrentBitNo();
2877 SmallVector<uint32_t, 128> KindDeclPairs;
2878 for (const auto *D : DC->decls()) {
2879 KindDeclPairs.push_back(D->getKind());
2880 KindDeclPairs.push_back(GetDeclRef(D));
2883 ++NumLexicalDeclContexts;
2884 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
2885 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2886 bytes(KindDeclPairs));
2890 void ASTWriter::WriteTypeDeclOffsets() {
2891 using namespace llvm;
2893 // Write the type offsets array
2894 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2895 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2899 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2901 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2902 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2903 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2906 // Write the declaration offsets array
2907 Abbrev = std::make_shared<BitCodeAbbrev>();
2908 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2910 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2911 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2912 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2914 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2915 FirstDeclID - NUM_PREDEF_DECL_IDS};
2916 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2920 void ASTWriter::WriteFileDeclIDsMap() {
2921 using namespace llvm;
2923 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2924 FileDeclIDs.begin(), FileDeclIDs.end());
2925 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2926 llvm::less_first());
2928 // Join the vectors of DeclIDs from all files.
2929 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2930 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2931 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2932 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2933 for (auto &LocDeclEntry : Info.DeclIDs)
2934 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2937 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2938 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2939 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2940 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2941 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
2942 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2943 FileGroupedDeclIDs.size()};
2944 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2947 void ASTWriter::WriteComments() {
2948 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2949 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2951 for (const auto *I : RawComments) {
2953 AddSourceRange(I->getSourceRange(), Record);
2954 Record.push_back(I->getKind());
2955 Record.push_back(I->isTrailingComment());
2956 Record.push_back(I->isAlmostTrailingComment());
2957 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2962 //===----------------------------------------------------------------------===//
2963 // Global Method Pool and Selector Serialization
2964 //===----------------------------------------------------------------------===//
2968 // Trait used for the on-disk hash table used in the method pool.
2969 class ASTMethodPoolTrait {
2973 typedef Selector key_type;
2974 typedef key_type key_type_ref;
2978 ObjCMethodList Instance, Factory;
2980 typedef const data_type& data_type_ref;
2982 typedef unsigned hash_value_type;
2983 typedef unsigned offset_type;
2985 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2987 static hash_value_type ComputeHash(Selector Sel) {
2988 return serialization::ComputeHash(Sel);
2991 std::pair<unsigned,unsigned>
2992 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2993 data_type_ref Methods) {
2994 using namespace llvm::support;
2995 endian::Writer<little> LE(Out);
2996 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2997 LE.write<uint16_t>(KeyLen);
2998 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2999 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3000 Method = Method->getNext())
3001 if (Method->getMethod())
3003 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3004 Method = Method->getNext())
3005 if (Method->getMethod())
3007 LE.write<uint16_t>(DataLen);
3008 return std::make_pair(KeyLen, DataLen);
3011 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3012 using namespace llvm::support;
3013 endian::Writer<little> LE(Out);
3014 uint64_t Start = Out.tell();
3015 assert((Start >> 32) == 0 && "Selector key offset too large");
3016 Writer.SetSelectorOffset(Sel, Start);
3017 unsigned N = Sel.getNumArgs();
3018 LE.write<uint16_t>(N);
3021 for (unsigned I = 0; I != N; ++I)
3023 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3026 void EmitData(raw_ostream& Out, key_type_ref,
3027 data_type_ref Methods, unsigned DataLen) {
3028 using namespace llvm::support;
3029 endian::Writer<little> LE(Out);
3030 uint64_t Start = Out.tell(); (void)Start;
3031 LE.write<uint32_t>(Methods.ID);
3032 unsigned NumInstanceMethods = 0;
3033 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3034 Method = Method->getNext())
3035 if (Method->getMethod())
3036 ++NumInstanceMethods;
3038 unsigned NumFactoryMethods = 0;
3039 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3040 Method = Method->getNext())
3041 if (Method->getMethod())
3042 ++NumFactoryMethods;
3044 unsigned InstanceBits = Methods.Instance.getBits();
3045 assert(InstanceBits < 4);
3046 unsigned InstanceHasMoreThanOneDeclBit =
3047 Methods.Instance.hasMoreThanOneDecl();
3048 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3049 (InstanceHasMoreThanOneDeclBit << 2) |
3051 unsigned FactoryBits = Methods.Factory.getBits();
3052 assert(FactoryBits < 4);
3053 unsigned FactoryHasMoreThanOneDeclBit =
3054 Methods.Factory.hasMoreThanOneDecl();
3055 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3056 (FactoryHasMoreThanOneDeclBit << 2) |
3058 LE.write<uint16_t>(FullInstanceBits);
3059 LE.write<uint16_t>(FullFactoryBits);
3060 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3061 Method = Method->getNext())
3062 if (Method->getMethod())
3063 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3064 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3065 Method = Method->getNext())
3066 if (Method->getMethod())
3067 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3069 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3073 } // end anonymous namespace
3075 /// \brief Write ObjC data: selectors and the method pool.
3077 /// The method pool contains both instance and factory methods, stored
3078 /// in an on-disk hash table indexed by the selector. The hash table also
3079 /// contains an empty entry for every other selector known to Sema.
3080 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3081 using namespace llvm;
3083 // Do we have to do anything at all?
3084 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3086 unsigned NumTableEntries = 0;
3087 // Create and write out the blob that contains selectors and the method pool.
3089 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3090 ASTMethodPoolTrait Trait(*this);
3092 // Create the on-disk hash table representation. We walk through every
3093 // selector we've seen and look it up in the method pool.
3094 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3095 for (auto &SelectorAndID : SelectorIDs) {
3096 Selector S = SelectorAndID.first;
3097 SelectorID ID = SelectorAndID.second;
3098 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3099 ASTMethodPoolTrait::data_type Data = {
3104 if (F != SemaRef.MethodPool.end()) {
3105 Data.Instance = F->second.first;
3106 Data.Factory = F->second.second;
3108 // Only write this selector if it's not in an existing AST or something
3110 if (Chain && ID < FirstSelectorID) {
3111 // Selector already exists. Did it change?
3112 bool changed = false;
3113 for (ObjCMethodList *M = &Data.Instance;
3114 !changed && M && M->getMethod(); M = M->getNext()) {
3115 if (!M->getMethod()->isFromASTFile())
3118 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3120 if (!M->getMethod()->isFromASTFile())
3125 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3126 // A new method pool entry.
3129 Generator.insert(S, Data, Trait);
3132 // Create the on-disk hash table in a buffer.
3133 SmallString<4096> MethodPool;
3134 uint32_t BucketOffset;
3136 using namespace llvm::support;
3137 ASTMethodPoolTrait Trait(*this);
3138 llvm::raw_svector_ostream Out(MethodPool);
3139 // Make sure that no bucket is at offset 0
3140 endian::Writer<little>(Out).write<uint32_t>(0);
3141 BucketOffset = Generator.Emit(Out, Trait);
3144 // Create a blob abbreviation
3145 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3146 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3148 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3149 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3150 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3152 // Write the method pool
3154 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3156 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3159 // Create a blob abbreviation for the selector table offsets.
3160 Abbrev = std::make_shared<BitCodeAbbrev>();
3161 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3162 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3165 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3167 // Write the selector offsets table.
3169 RecordData::value_type Record[] = {
3170 SELECTOR_OFFSETS, SelectorOffsets.size(),
3171 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3172 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3173 bytes(SelectorOffsets));
3178 /// \brief Write the selectors referenced in @selector expression into AST file.
3179 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3180 using namespace llvm;
3181 if (SemaRef.ReferencedSelectors.empty())
3185 ASTRecordWriter Writer(*this, Record);
3187 // Note: this writes out all references even for a dependent AST. But it is
3188 // very tricky to fix, and given that @selector shouldn't really appear in
3189 // headers, probably not worth it. It's not a correctness issue.
3190 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3191 Selector Sel = SelectorAndLocation.first;
3192 SourceLocation Loc = SelectorAndLocation.second;
3193 Writer.AddSelectorRef(Sel);
3194 Writer.AddSourceLocation(Loc);
3196 Writer.Emit(REFERENCED_SELECTOR_POOL);
3199 //===----------------------------------------------------------------------===//
3200 // Identifier Table Serialization
3201 //===----------------------------------------------------------------------===//
3203 /// Determine the declaration that should be put into the name lookup table to
3204 /// represent the given declaration in this module. This is usually D itself,
3205 /// but if D was imported and merged into a local declaration, we want the most
3206 /// recent local declaration instead. The chosen declaration will be the most
3207 /// recent declaration in any module that imports this one.
3208 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3210 if (!LangOpts.Modules || !D->isFromASTFile())
3213 if (Decl *Redecl = D->getPreviousDecl()) {
3214 // For Redeclarable decls, a prior declaration might be local.
3215 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3216 // If we find a local decl, we're done.
3217 if (!Redecl->isFromASTFile()) {
3218 // Exception: in very rare cases (for injected-class-names), not all
3219 // redeclarations are in the same semantic context. Skip ones in a
3220 // different context. They don't go in this lookup table at all.
3221 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3222 D->getDeclContext()->getRedeclContext()))
3224 return cast<NamedDecl>(Redecl);
3227 // If we find a decl from a (chained-)PCH stop since we won't find a
3229 if (Redecl->getOwningModuleID() == 0)
3232 } else if (Decl *First = D->getCanonicalDecl()) {
3233 // For Mergeable decls, the first decl might be local.
3234 if (!First->isFromASTFile())
3235 return cast<NamedDecl>(First);
3238 // All declarations are imported. Our most recent declaration will also be
3239 // the most recent one in anyone who imports us.
3245 class ASTIdentifierTableTrait {
3248 IdentifierResolver &IdResolver;
3251 ASTWriter::RecordData *InterestingIdentifierOffsets;
3253 /// \brief Determines whether this is an "interesting" identifier that needs a
3254 /// full IdentifierInfo structure written into the hash table. Notably, this
3255 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3257 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3260 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3261 II->hasRevertedTokenIDToIdentifier() ||
3262 (NeedDecls && II->getFETokenInfo<void>()))
3269 typedef IdentifierInfo* key_type;
3270 typedef key_type key_type_ref;
3272 typedef IdentID data_type;
3273 typedef data_type data_type_ref;
3275 typedef unsigned hash_value_type;
3276 typedef unsigned offset_type;
3278 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3279 IdentifierResolver &IdResolver, bool IsModule,
3280 ASTWriter::RecordData *InterestingIdentifierOffsets)
3281 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3282 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3283 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3285 bool needDecls() const { return NeedDecls; }
3287 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3288 return llvm::HashString(II->getName());
3291 bool isInterestingIdentifier(const IdentifierInfo *II) {
3292 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3293 return isInterestingIdentifier(II, MacroOffset);
3296 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3297 return isInterestingIdentifier(II, 0);
3300 std::pair<unsigned,unsigned>
3301 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3302 unsigned KeyLen = II->getLength() + 1;
3303 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3304 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3305 if (isInterestingIdentifier(II, MacroOffset)) {
3306 DataLen += 2; // 2 bytes for builtin ID
3307 DataLen += 2; // 2 bytes for flags
3309 DataLen += 4; // MacroDirectives offset.
3312 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3313 DEnd = IdResolver.end();
3318 using namespace llvm::support;
3319 endian::Writer<little> LE(Out);
3321 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3322 LE.write<uint16_t>(DataLen);
3323 // We emit the key length after the data length so that every
3324 // string is preceded by a 16-bit length. This matches the PTH
3325 // format for storing identifiers.
3326 LE.write<uint16_t>(KeyLen);
3327 return std::make_pair(KeyLen, DataLen);
3330 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3332 // Record the location of the key data. This is used when generating
3333 // the mapping from persistent IDs to strings.
3334 Writer.SetIdentifierOffset(II, Out.tell());
3336 // Emit the offset of the key/data length information to the interesting
3337 // identifiers table if necessary.
3338 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3339 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3341 Out.write(II->getNameStart(), KeyLen);
3344 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3345 IdentID ID, unsigned) {
3346 using namespace llvm::support;
3347 endian::Writer<little> LE(Out);
3349 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3350 if (!isInterestingIdentifier(II, MacroOffset)) {
3351 LE.write<uint32_t>(ID << 1);
3355 LE.write<uint32_t>((ID << 1) | 0x01);
3356 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3357 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3358 LE.write<uint16_t>(Bits);
3360 bool HadMacroDefinition = MacroOffset != 0;
3361 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3362 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3363 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3364 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3365 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3366 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3367 LE.write<uint16_t>(Bits);
3369 if (HadMacroDefinition)
3370 LE.write<uint32_t>(MacroOffset);
3373 // Emit the declaration IDs in reverse order, because the
3374 // IdentifierResolver provides the declarations as they would be
3375 // visible (e.g., the function "stat" would come before the struct
3376 // "stat"), but the ASTReader adds declarations to the end of the list
3377 // (so we need to see the struct "stat" before the function "stat").
3378 // Only emit declarations that aren't from a chained PCH, though.
3379 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3381 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3382 DEnd = Decls.rend();
3385 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
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 RecordData InterestingIdents;
3404 // Create and write out the blob that contains the identifier
3407 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3408 ASTIdentifierTableTrait Trait(
3409 *this, PP, IdResolver, IsModule,
3410 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3412 // Look for any identifiers that were named while processing the
3413 // headers, but are otherwise not needed. We add these to the hash
3414 // table to enable checking of the predefines buffer in the case
3415 // where the user adds new macro definitions when building the AST
3417 SmallVector<const IdentifierInfo *, 128> IIs;
3418 for (const auto &ID : PP.getIdentifierTable())
3419 IIs.push_back(ID.second);
3420 // Sort the identifiers lexicographically before getting them references so
3421 // that their order is stable.
3422 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3423 for (const IdentifierInfo *II : IIs)
3424 if (Trait.isInterestingNonMacroIdentifier(II))
3425 getIdentifierRef(II);
3427 // Create the on-disk hash table representation. We only store offsets
3428 // for identifiers that appear here for the first time.
3429 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3430 for (auto IdentIDPair : IdentifierIDs) {
3431 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3432 IdentID ID = IdentIDPair.second;
3433 assert(II && "NULL identifier in identifier table");
3434 // Write out identifiers if either the ID is local or the identifier has
3435 // changed since it was loaded.
3436 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3437 || II->hasChangedSinceDeserialization() ||
3438 (Trait.needDecls() &&
3439 II->hasFETokenInfoChangedSinceDeserialization()))
3440 Generator.insert(II, ID, Trait);
3443 // Create the on-disk hash table in a buffer.
3444 SmallString<4096> IdentifierTable;
3445 uint32_t BucketOffset;
3447 using namespace llvm::support;
3448 llvm::raw_svector_ostream Out(IdentifierTable);
3449 // Make sure that no bucket is at offset 0
3450 endian::Writer<little>(Out).write<uint32_t>(0);
3451 BucketOffset = Generator.Emit(Out, Trait);
3454 // Create a blob abbreviation
3455 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3456 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3459 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3461 // Write the identifier table
3462 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3463 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3466 // Write the offsets table for identifier IDs.
3467 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3468 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3470 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3472 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3475 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3476 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3479 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3480 IdentifierOffsets.size(),
3481 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3482 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3483 bytes(IdentifierOffsets));
3485 // In C++, write the list of interesting identifiers (those that are
3486 // defined as macros, poisoned, or similar unusual things).
3487 if (!InterestingIdents.empty())
3488 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3491 //===----------------------------------------------------------------------===//
3492 // DeclContext's Name Lookup Table Serialization
3493 //===----------------------------------------------------------------------===//
3497 // Trait used for the on-disk hash table used in the method pool.
3498 class ASTDeclContextNameLookupTrait {
3500 llvm::SmallVector<DeclID, 64> DeclIDs;
3503 typedef DeclarationNameKey key_type;
3504 typedef key_type key_type_ref;
3506 /// A start and end index into DeclIDs, representing a sequence of decls.
3507 typedef std::pair<unsigned, unsigned> data_type;
3508 typedef const data_type& data_type_ref;
3510 typedef unsigned hash_value_type;
3511 typedef unsigned offset_type;
3513 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3515 template<typename Coll>
3516 data_type getData(const Coll &Decls) {
3517 unsigned Start = DeclIDs.size();
3518 for (NamedDecl *D : Decls) {
3520 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3522 return std::make_pair(Start, DeclIDs.size());
3525 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3526 unsigned Start = DeclIDs.size();
3527 for (auto ID : FromReader)
3528 DeclIDs.push_back(ID);
3529 return std::make_pair(Start, DeclIDs.size());
3532 static bool EqualKey(key_type_ref a, key_type_ref b) {
3536 hash_value_type ComputeHash(DeclarationNameKey Name) {
3537 return Name.getHash();
3540 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3541 assert(Writer.hasChain() &&
3542 "have reference to loaded module file but no chain?");
3544 using namespace llvm::support;
3545 endian::Writer<little>(Out)
3546 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3549 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3550 DeclarationNameKey Name,
3551 data_type_ref Lookup) {
3552 using namespace llvm::support;
3553 endian::Writer<little> LE(Out);
3554 unsigned KeyLen = 1;
3555 switch (Name.getKind()) {
3556 case DeclarationName::Identifier:
3557 case DeclarationName::ObjCZeroArgSelector:
3558 case DeclarationName::ObjCOneArgSelector:
3559 case DeclarationName::ObjCMultiArgSelector:
3560 case DeclarationName::CXXLiteralOperatorName:
3563 case DeclarationName::CXXOperatorName:
3566 case DeclarationName::CXXConstructorName:
3567 case DeclarationName::CXXDestructorName:
3568 case DeclarationName::CXXConversionFunctionName:
3569 case DeclarationName::CXXUsingDirective:
3572 LE.write<uint16_t>(KeyLen);
3574 // 4 bytes for each DeclID.
3575 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3576 assert(uint16_t(DataLen) == DataLen &&
3577 "too many decls for serialized lookup result");
3578 LE.write<uint16_t>(DataLen);
3580 return std::make_pair(KeyLen, DataLen);
3583 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3584 using namespace llvm::support;
3585 endian::Writer<little> LE(Out);
3586 LE.write<uint8_t>(Name.getKind());
3587 switch (Name.getKind()) {
3588 case DeclarationName::Identifier:
3589 case DeclarationName::CXXLiteralOperatorName:
3590 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3592 case DeclarationName::ObjCZeroArgSelector:
3593 case DeclarationName::ObjCOneArgSelector:
3594 case DeclarationName::ObjCMultiArgSelector:
3595 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3597 case DeclarationName::CXXOperatorName:
3598 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3599 "Invalid operator?");
3600 LE.write<uint8_t>(Name.getOperatorKind());
3602 case DeclarationName::CXXConstructorName:
3603 case DeclarationName::CXXDestructorName:
3604 case DeclarationName::CXXConversionFunctionName:
3605 case DeclarationName::CXXUsingDirective:
3609 llvm_unreachable("Invalid name kind?");
3612 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3614 using namespace llvm::support;
3615 endian::Writer<little> LE(Out);
3616 uint64_t Start = Out.tell(); (void)Start;
3617 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3618 LE.write<uint32_t>(DeclIDs[I]);
3619 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3623 } // end anonymous namespace
3625 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3627 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3630 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3632 for (auto *D : Result.getLookupResult())
3633 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3640 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3641 llvm::SmallVectorImpl<char> &LookupTable) {
3642 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3643 !ConstDC->HasLazyExternalLexicalLookups &&
3644 "must call buildLookups first");
3646 // FIXME: We need to build the lookups table, which is logically const.
3647 auto *DC = const_cast<DeclContext*>(ConstDC);
3648 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3650 // Create the on-disk hash table representation.
3651 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3652 ASTDeclContextNameLookupTrait> Generator;
3653 ASTDeclContextNameLookupTrait Trait(*this);
3655 // The first step is to collect the declaration names which we need to
3656 // serialize into the name lookup table, and to collect them in a stable
3658 SmallVector<DeclarationName, 16> Names;
3660 // We also build up small sets of the constructor and conversion function
3661 // names which are visible.
3662 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3664 for (auto &Lookup : *DC->buildLookup()) {
3665 auto &Name = Lookup.first;
3666 auto &Result = Lookup.second;
3668 // If there are no local declarations in our lookup result, we
3669 // don't need to write an entry for the name at all. If we can't
3670 // write out a lookup set without performing more deserialization,
3671 // just skip this entry.
3672 if (isLookupResultExternal(Result, DC) &&
3673 isLookupResultEntirelyExternal(Result, DC))
3676 // We also skip empty results. If any of the results could be external and
3677 // the currently available results are empty, then all of the results are
3678 // external and we skip it above. So the only way we get here with an empty
3679 // results is when no results could have been external *and* we have
3680 // external results.
3682 // FIXME: While we might want to start emitting on-disk entries for negative
3683 // lookups into a decl context as an optimization, today we *have* to skip
3684 // them because there are names with empty lookup results in decl contexts
3685 // which we can't emit in any stable ordering: we lookup constructors and
3686 // conversion functions in the enclosing namespace scope creating empty
3687 // results for them. This in almost certainly a bug in Clang's name lookup,
3688 // but that is likely to be hard or impossible to fix and so we tolerate it
3689 // here by omitting lookups with empty results.
3690 if (Lookup.second.getLookupResult().empty())
3693 switch (Lookup.first.getNameKind()) {
3695 Names.push_back(Lookup.first);
3698 case DeclarationName::CXXConstructorName:
3699 assert(isa<CXXRecordDecl>(DC) &&
3700 "Cannot have a constructor name outside of a class!");
3701 ConstructorNameSet.insert(Name);
3704 case DeclarationName::CXXConversionFunctionName:
3705 assert(isa<CXXRecordDecl>(DC) &&
3706 "Cannot have a conversion function name outside of a class!");
3707 ConversionNameSet.insert(Name);
3712 // Sort the names into a stable order.
3713 std::sort(Names.begin(), Names.end());
3715 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3716 // We need to establish an ordering of constructor and conversion function
3717 // names, and they don't have an intrinsic ordering.
3719 // First we try the easy case by forming the current context's constructor
3720 // name and adding that name first. This is a very useful optimization to
3721 // avoid walking the lexical declarations in many cases, and it also
3722 // handles the only case where a constructor name can come from some other
3723 // lexical context -- when that name is an implicit constructor merged from
3724 // another declaration in the redecl chain. Any non-implicit constructor or
3725 // conversion function which doesn't occur in all the lexical contexts
3726 // would be an ODR violation.
3727 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3728 Context->getCanonicalType(Context->getRecordType(D)));
3729 if (ConstructorNameSet.erase(ImplicitCtorName))
3730 Names.push_back(ImplicitCtorName);
3732 // If we still have constructors or conversion functions, we walk all the
3733 // names in the decl and add the constructors and conversion functions
3734 // which are visible in the order they lexically occur within the context.
3735 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3736 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3737 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3738 auto Name = ChildND->getDeclName();
3739 switch (Name.getNameKind()) {
3743 case DeclarationName::CXXConstructorName:
3744 if (ConstructorNameSet.erase(Name))
3745 Names.push_back(Name);
3748 case DeclarationName::CXXConversionFunctionName:
3749 if (ConversionNameSet.erase(Name))
3750 Names.push_back(Name);
3754 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3758 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3759 "constructors by walking all the "
3760 "lexical members of the context.");
3761 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3762 "conversion functions by walking all "
3763 "the lexical members of the context.");
3766 // Next we need to do a lookup with each name into this decl context to fully
3767 // populate any results from external sources. We don't actually use the
3768 // results of these lookups because we only want to use the results after all
3769 // results have been loaded and the pointers into them will be stable.
3770 for (auto &Name : Names)
3773 // Now we need to insert the results for each name into the hash table. For
3774 // constructor names and conversion function names, we actually need to merge
3775 // all of the results for them into one list of results each and insert
3777 SmallVector<NamedDecl *, 8> ConstructorDecls;
3778 SmallVector<NamedDecl *, 8> ConversionDecls;
3780 // Now loop over the names, either inserting them or appending for the two
3782 for (auto &Name : Names) {
3783 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3785 switch (Name.getNameKind()) {
3787 Generator.insert(Name, Trait.getData(Result), Trait);
3790 case DeclarationName::CXXConstructorName:
3791 ConstructorDecls.append(Result.begin(), Result.end());
3794 case DeclarationName::CXXConversionFunctionName:
3795 ConversionDecls.append(Result.begin(), Result.end());
3800 // Handle our two special cases if we ended up having any. We arbitrarily use
3801 // the first declaration's name here because the name itself isn't part of
3802 // the key, only the kind of name is used.
3803 if (!ConstructorDecls.empty())
3804 Generator.insert(ConstructorDecls.front()->getDeclName(),
3805 Trait.getData(ConstructorDecls), Trait);
3806 if (!ConversionDecls.empty())
3807 Generator.insert(ConversionDecls.front()->getDeclName(),
3808 Trait.getData(ConversionDecls), Trait);
3810 // Create the on-disk hash table. Also emit the existing imported and
3811 // merged table if there is one.
3812 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3813 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3816 /// \brief Write the block containing all of the declaration IDs
3817 /// visible from the given DeclContext.
3819 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3820 /// bitstream, or 0 if no block was written.
3821 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3823 // If we imported a key declaration of this namespace, write the visible
3824 // lookup results as an update record for it rather than including them
3825 // on this declaration. We will only look at key declarations on reload.
3826 if (isa<NamespaceDecl>(DC) && Chain &&
3827 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3828 // Only do this once, for the first local declaration of the namespace.
3829 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3830 Prev = Prev->getPreviousDecl())
3831 if (!Prev->isFromASTFile())
3834 // Note that we need to emit an update record for the primary context.
3835 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3837 // Make sure all visible decls are written. They will be recorded later. We
3838 // do this using a side data structure so we can sort the names into
3839 // a deterministic order.
3840 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3841 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3844 LookupResults.reserve(Map->size());
3845 for (auto &Entry : *Map)
3846 LookupResults.push_back(
3847 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3850 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3851 for (auto &NameAndResult : LookupResults) {
3852 DeclarationName Name = NameAndResult.first;
3853 DeclContext::lookup_result Result = NameAndResult.second;
3854 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3855 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3856 // We have to work around a name lookup bug here where negative lookup
3857 // results for these names get cached in namespace lookup tables (these
3858 // names should never be looked up in a namespace).
3859 assert(Result.empty() && "Cannot have a constructor or conversion "
3860 "function name in a namespace!");
3864 for (NamedDecl *ND : Result)
3865 if (!ND->isFromASTFile())
3872 if (DC->getPrimaryContext() != DC)
3875 // Skip contexts which don't support name lookup.
3876 if (!DC->isLookupContext())
3879 // If not in C++, we perform name lookup for the translation unit via the
3880 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3881 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3884 // Serialize the contents of the mapping used for lookup. Note that,
3885 // although we have two very different code paths, the serialized
3886 // representation is the same for both cases: a declaration name,
3887 // followed by a size, followed by references to the visible
3888 // declarations that have that name.
3889 uint64_t Offset = Stream.GetCurrentBitNo();
3890 StoredDeclsMap *Map = DC->buildLookup();
3891 if (!Map || Map->empty())
3894 // Create the on-disk hash table in a buffer.
3895 SmallString<4096> LookupTable;
3896 GenerateNameLookupTable(DC, LookupTable);
3898 // Write the lookup table
3899 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3900 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3902 ++NumVisibleDeclContexts;
3906 /// \brief Write an UPDATE_VISIBLE block for the given context.
3908 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3909 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3910 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3911 /// enumeration members (in C++11).
3912 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3913 StoredDeclsMap *Map = DC->getLookupPtr();
3914 if (!Map || Map->empty())
3917 // Create the on-disk hash table in a buffer.
3918 SmallString<4096> LookupTable;
3919 GenerateNameLookupTable(DC, LookupTable);
3921 // If we're updating a namespace, select a key declaration as the key for the
3922 // update record; those are the only ones that will be checked on reload.
3923 if (isa<NamespaceDecl>(DC))
3924 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3926 // Write the lookup table
3927 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3928 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3931 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3932 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3933 RecordData::value_type Record[] = {Opts.fp_contract};
3934 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3937 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3938 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3939 if (!SemaRef.Context.getLangOpts().OpenCL)
3942 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3944 for (const auto &I:Opts.OptMap) {
3945 AddString(I.getKey(), Record);
3946 auto V = I.getValue();
3947 Record.push_back(V.Supported ? 1 : 0);
3948 Record.push_back(V.Enabled ? 1 : 0);
3949 Record.push_back(V.Avail);
3950 Record.push_back(V.Core);
3952 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3955 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3956 if (!SemaRef.Context.getLangOpts().OpenCL)
3960 for (const auto &I : SemaRef.OpenCLTypeExtMap) {
3962 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
3963 Record.push_back(I.second.size());
3964 for (auto Ext : I.second)
3965 AddString(Ext, Record);
3967 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3970 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3971 if (!SemaRef.Context.getLangOpts().OpenCL)
3975 for (const auto &I : SemaRef.OpenCLDeclExtMap) {
3976 Record.push_back(getDeclID(I.first));
3977 Record.push_back(static_cast<unsigned>(I.second.size()));
3978 for (auto Ext : I.second)
3979 AddString(Ext, Record);
3981 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
3984 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3985 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3986 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3987 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
3991 void ASTWriter::WriteObjCCategories() {
3992 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3993 RecordData Categories;
3995 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3997 unsigned StartIndex = Categories.size();
3999 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4001 // Allocate space for the size.
4002 Categories.push_back(0);
4004 // Add the categories.
4005 for (ObjCInterfaceDecl::known_categories_iterator
4006 Cat = Class->known_categories_begin(),
4007 CatEnd = Class->known_categories_end();
4008 Cat != CatEnd; ++Cat, ++Size) {
4009 assert(getDeclID(*Cat) != 0 && "Bogus category");
4010 AddDeclRef(*Cat, Categories);
4014 Categories[StartIndex] = Size;
4016 // Record this interface -> category map.
4017 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4018 CategoriesMap.push_back(CatInfo);
4021 // Sort the categories map by the definition ID, since the reader will be
4022 // performing binary searches on this information.
4023 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4025 // Emit the categories map.
4026 using namespace llvm;
4028 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4029 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4030 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4031 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4032 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4034 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4035 Stream.EmitRecordWithBlob(AbbrevID, Record,
4036 reinterpret_cast<char *>(CategoriesMap.data()),
4037 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4039 // Emit the category lists.
4040 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4043 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4044 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4050 for (auto &LPTMapEntry : LPTMap) {
4051 const FunctionDecl *FD = LPTMapEntry.first;
4052 LateParsedTemplate &LPT = *LPTMapEntry.second;
4053 AddDeclRef(FD, Record);
4054 AddDeclRef(LPT.D, Record);
4055 Record.push_back(LPT.Toks.size());
4057 for (const auto &Tok : LPT.Toks) {
4058 AddToken(Tok, Record);
4061 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4064 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4065 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4067 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4068 AddSourceLocation(PragmaLoc, Record);
4069 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4072 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
4073 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4075 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4076 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4079 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
4081 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4083 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4084 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4085 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4088 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4089 ModuleFileExtensionWriter &Writer) {
4090 // Enter the extension block.
4091 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4093 // Emit the metadata record abbreviation.
4094 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4095 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4096 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4097 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4098 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4099 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4100 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4101 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4103 // Emit the metadata record.
4105 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4106 Record.push_back(EXTENSION_METADATA);
4107 Record.push_back(Metadata.MajorVersion);
4108 Record.push_back(Metadata.MinorVersion);
4109 Record.push_back(Metadata.BlockName.size());
4110 Record.push_back(Metadata.UserInfo.size());
4111 SmallString<64> Buffer;
4112 Buffer += Metadata.BlockName;
4113 Buffer += Metadata.UserInfo;
4114 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4116 // Emit the contents of the extension block.
4117 Writer.writeExtensionContents(SemaRef, Stream);
4119 // Exit the extension block.
4123 //===----------------------------------------------------------------------===//
4124 // General Serialization Routines
4125 //===----------------------------------------------------------------------===//
4127 /// \brief Emit the list of attributes to the specified record.
4128 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4129 auto &Record = *this;
4130 Record.push_back(Attrs.size());
4131 for (const auto *A : Attrs) {
4132 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4133 Record.AddSourceRange(A->getRange());
4135 #include "clang/Serialization/AttrPCHWrite.inc"
4140 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4141 AddSourceLocation(Tok.getLocation(), Record);
4142 Record.push_back(Tok.getLength());
4144 // FIXME: When reading literal tokens, reconstruct the literal pointer
4146 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4147 // FIXME: Should translate token kind to a stable encoding.
4148 Record.push_back(Tok.getKind());
4149 // FIXME: Should translate token flags to a stable encoding.
4150 Record.push_back(Tok.getFlags());
4153 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4154 Record.push_back(Str.size());
4155 Record.insert(Record.end(), Str.begin(), Str.end());
4158 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4159 assert(Context && "should have context when outputting path");
4162 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4164 // Remove a prefix to make the path relative, if relevant.
4165 const char *PathBegin = Path.data();
4166 const char *PathPtr =
4167 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4168 if (PathPtr != PathBegin) {
4169 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4176 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4177 SmallString<128> FilePath(Path);
4178 PreparePathForOutput(FilePath);
4179 AddString(FilePath, Record);
4182 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4184 SmallString<128> FilePath(Path);
4185 PreparePathForOutput(FilePath);
4186 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4189 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4190 RecordDataImpl &Record) {
4191 Record.push_back(Version.getMajor());
4192 if (Optional<unsigned> Minor = Version.getMinor())
4193 Record.push_back(*Minor + 1);
4195 Record.push_back(0);
4196 if (Optional<unsigned> Subminor = Version.getSubminor())
4197 Record.push_back(*Subminor + 1);
4199 Record.push_back(0);
4202 /// \brief Note that the identifier II occurs at the given offset
4203 /// within the identifier table.
4204 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4205 IdentID ID = IdentifierIDs[II];
4206 // Only store offsets new to this AST file. Other identifier names are looked
4207 // up earlier in the chain and thus don't need an offset.
4208 if (ID >= FirstIdentID)
4209 IdentifierOffsets[ID - FirstIdentID] = Offset;
4212 /// \brief Note that the selector Sel occurs at the given offset
4213 /// within the method pool/selector table.
4214 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4215 unsigned ID = SelectorIDs[Sel];
4216 assert(ID && "Unknown selector");
4217 // Don't record offsets for selectors that are also available in a different
4219 if (ID < FirstSelectorID)
4221 SelectorOffsets[ID - FirstSelectorID] = Offset;
4224 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4225 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4226 bool IncludeTimestamps)
4227 : Stream(Stream), IncludeTimestamps(IncludeTimestamps) {
4228 for (const auto &Ext : Extensions) {
4229 if (auto Writer = Ext->createExtensionWriter(*this))
4230 ModuleFileExtensionWriters.push_back(std::move(Writer));
4234 ASTWriter::~ASTWriter() {
4235 llvm::DeleteContainerSeconds(FileDeclIDs);
4238 const LangOptions &ASTWriter::getLangOpts() const {
4239 assert(WritingAST && "can't determine lang opts when not writing AST");
4240 return Context->getLangOpts();
4243 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4244 return IncludeTimestamps ? E->getModificationTime() : 0;
4247 uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4248 Module *WritingModule, StringRef isysroot,
4252 ASTHasCompilerErrors = hasErrors;
4254 // Emit the file header.
4255 Stream.Emit((unsigned)'C', 8);
4256 Stream.Emit((unsigned)'P', 8);
4257 Stream.Emit((unsigned)'C', 8);
4258 Stream.Emit((unsigned)'H', 8);
4260 WriteBlockInfoBlock();
4262 Context = &SemaRef.Context;
4264 this->WritingModule = WritingModule;
4265 ASTFileSignature Signature =
4266 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4269 this->WritingModule = nullptr;
4270 this->BaseDirectory.clear();
4276 template<typename Vector>
4277 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4278 ASTWriter::RecordData &Record) {
4279 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4281 Writer.AddDeclRef(*I, Record);
4285 uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4286 const std::string &OutputFile,
4287 Module *WritingModule) {
4288 using namespace llvm;
4290 bool isModule = WritingModule != nullptr;
4292 // Make sure that the AST reader knows to finalize itself.
4294 Chain->finalizeForWriting();
4296 ASTContext &Context = SemaRef.Context;
4297 Preprocessor &PP = SemaRef.PP;
4299 // Set up predefined declaration IDs.
4300 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4302 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4306 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4307 PREDEF_DECL_TRANSLATION_UNIT_ID);
4308 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4309 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4310 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4311 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4312 PREDEF_DECL_OBJC_PROTOCOL_ID);
4313 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4314 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4315 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4316 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4317 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4318 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4319 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4320 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4321 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4322 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4323 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4324 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4325 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4326 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4327 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4328 RegisterPredefDecl(Context.TypePackElementDecl,
4329 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4331 // Build a record containing all of the tentative definitions in this file, in
4332 // TentativeDefinitions order. Generally, this record will be empty for
4334 RecordData TentativeDefinitions;
4335 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4337 // Build a record containing all of the file scoped decls in this file.
4338 RecordData UnusedFileScopedDecls;
4340 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4341 UnusedFileScopedDecls);
4343 // Build a record containing all of the delegating constructors we still need
4345 RecordData DelegatingCtorDecls;
4347 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4349 // Write the set of weak, undeclared identifiers. We always write the
4350 // entire table, since later PCH files in a PCH chain are only interested in
4351 // the results at the end of the chain.
4352 RecordData WeakUndeclaredIdentifiers;
4353 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4354 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4355 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4356 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4357 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4358 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4359 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4362 // Build a record containing all of the ext_vector declarations.
4363 RecordData ExtVectorDecls;
4364 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4366 // Build a record containing all of the VTable uses information.
4367 RecordData VTableUses;
4368 if (!SemaRef.VTableUses.empty()) {
4369 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4370 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4371 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4372 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4376 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4377 RecordData UnusedLocalTypedefNameCandidates;
4378 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4379 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4381 // Build a record containing all of pending implicit instantiations.
4382 RecordData PendingInstantiations;
4383 for (const auto &I : SemaRef.PendingInstantiations) {
4384 AddDeclRef(I.first, PendingInstantiations);
4385 AddSourceLocation(I.second, PendingInstantiations);
4387 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4388 "There are local ones at end of translation unit!");
4390 // Build a record containing some declaration references.
4391 RecordData SemaDeclRefs;
4392 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4393 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4394 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4395 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4398 RecordData CUDASpecialDeclRefs;
4399 if (Context.getcudaConfigureCallDecl()) {
4400 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4403 // Build a record containing all of the known namespaces.
4404 RecordData KnownNamespaces;
4405 for (const auto &I : SemaRef.KnownNamespaces) {
4407 AddDeclRef(I.first, KnownNamespaces);
4410 // Build a record of all used, undefined objects that require definitions.
4411 RecordData UndefinedButUsed;
4413 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4414 SemaRef.getUndefinedButUsed(Undefined);
4415 for (const auto &I : Undefined) {
4416 AddDeclRef(I.first, UndefinedButUsed);
4417 AddSourceLocation(I.second, UndefinedButUsed);
4420 // Build a record containing all delete-expressions that we would like to
4421 // analyze later in AST.
4422 RecordData DeleteExprsToAnalyze;
4424 for (const auto &DeleteExprsInfo :
4425 SemaRef.getMismatchingDeleteExpressions()) {
4426 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4427 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4428 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4429 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4430 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4434 // Write the control block
4435 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
4437 // Write the remaining AST contents.
4438 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4440 // This is so that older clang versions, before the introduction
4441 // of the control block, can read and reject the newer PCH format.
4443 RecordData Record = {VERSION_MAJOR};
4444 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4447 // Create a lexical update block containing all of the declarations in the
4448 // translation unit that do not come from other AST files.
4449 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4450 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4451 for (const auto *D : TU->noload_decls()) {
4452 if (!D->isFromASTFile()) {
4453 NewGlobalKindDeclPairs.push_back(D->getKind());
4454 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4458 auto Abv = std::make_shared<BitCodeAbbrev>();
4459 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4460 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4461 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4463 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4464 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4465 bytes(NewGlobalKindDeclPairs));
4468 // And a visible updates block for the translation unit.
4469 Abv = std::make_shared<BitCodeAbbrev>();
4470 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4471 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4472 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4473 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4474 WriteDeclContextVisibleUpdate(TU);
4476 // If we have any extern "C" names, write out a visible update for them.
4477 if (Context.ExternCContext)
4478 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4480 // If the translation unit has an anonymous namespace, and we don't already
4481 // have an update block for it, write it as an update block.
4482 // FIXME: Why do we not do this if there's already an update block?
4483 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4484 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4486 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4489 // Add update records for all mangling numbers and static local numbers.
4490 // These aren't really update records, but this is a convenient way of
4491 // tagging this rare extra data onto the declarations.
4492 for (const auto &Number : Context.MangleNumbers)
4493 if (!Number.first->isFromASTFile())
4494 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4496 for (const auto &Number : Context.StaticLocalNumbers)
4497 if (!Number.first->isFromASTFile())
4498 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4501 // Make sure visible decls, added to DeclContexts previously loaded from
4502 // an AST file, are registered for serialization. Likewise for template
4503 // specializations added to imported templates.
4504 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4508 // Make sure all decls associated with an identifier are registered for
4509 // serialization, if we're storing decls with identifiers.
4510 if (!WritingModule || !getLangOpts().CPlusPlus) {
4511 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4512 for (const auto &ID : PP.getIdentifierTable()) {
4513 const IdentifierInfo *II = ID.second;
4514 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4517 // Sort the identifiers to visit based on their name.
4518 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4519 for (const IdentifierInfo *II : IIs) {
4520 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4521 DEnd = SemaRef.IdResolver.end();
4528 // For method pool in the module, if it contains an entry for a selector,
4529 // the entry should be complete, containing everything introduced by that
4530 // module and all modules it imports. It's possible that the entry is out of
4531 // date, so we need to pull in the new content here.
4533 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4534 // safe, we copy all selectors out.
4535 llvm::SmallVector<Selector, 256> AllSelectors;
4536 for (auto &SelectorAndID : SelectorIDs)
4537 AllSelectors.push_back(SelectorAndID.first);
4538 for (auto &Selector : AllSelectors)
4539 SemaRef.updateOutOfDateSelector(Selector);
4541 // Form the record of special types.
4542 RecordData SpecialTypes;
4543 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4544 AddTypeRef(Context.getFILEType(), SpecialTypes);
4545 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4546 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4547 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4548 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4549 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4550 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4553 // Write the mapping information describing our module dependencies and how
4554 // each of those modules were mapped into our own offset/ID space, so that
4555 // the reader can build the appropriate mapping to its own offset/ID space.
4556 // The map consists solely of a blob with the following format:
4557 // *(module-name-len:i16 module-name:len*i8
4558 // source-location-offset:i32
4559 // identifier-id:i32
4560 // preprocessed-entity-id:i32
4561 // macro-definition-id:i32
4564 // declaration-id:i32
4565 // c++-base-specifiers-id:i32
4568 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4569 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4571 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4572 SmallString<2048> Buffer;
4574 llvm::raw_svector_ostream Out(Buffer);
4575 for (ModuleFile *M : Chain->ModuleMgr) {
4576 using namespace llvm::support;
4577 endian::Writer<little> LE(Out);
4578 StringRef FileName = M->FileName;
4579 LE.write<uint16_t>(FileName.size());
4580 Out.write(FileName.data(), FileName.size());
4582 // Note: if a base ID was uint max, it would not be possible to load
4583 // another module after it or have more than one entity inside it.
4584 uint32_t None = std::numeric_limits<uint32_t>::max();
4586 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4587 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4589 LE.write<uint32_t>(BaseID);
4591 LE.write<uint32_t>(None);
4594 // These values should be unique within a chain, since they will be read
4595 // as keys into ContinuousRangeMaps.
4596 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4597 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4598 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4599 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4600 M->NumPreprocessedEntities);
4601 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4602 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4603 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4604 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4607 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4608 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4609 Buffer.data(), Buffer.size());
4612 RecordData DeclUpdatesOffsetsRecord;
4614 // Keep writing types, declarations, and declaration update records
4615 // until we've emitted all of them.
4616 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4620 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4621 while (!DeclTypesToEmit.empty()) {
4622 DeclOrType DOT = DeclTypesToEmit.front();
4623 DeclTypesToEmit.pop();
4625 WriteType(DOT.getType());
4627 WriteDecl(Context, DOT.getDecl());
4629 } while (!DeclUpdates.empty());
4632 DoneWritingDeclsAndTypes = true;
4634 // These things can only be done once we've written out decls and types.
4635 WriteTypeDeclOffsets();
4636 if (!DeclUpdatesOffsetsRecord.empty())
4637 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4638 WriteFileDeclIDsMap();
4639 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4641 WritePreprocessor(PP, isModule);
4642 WriteHeaderSearch(PP.getHeaderSearchInfo());
4643 WriteSelectors(SemaRef);
4644 WriteReferencedSelectorsPool(SemaRef);
4645 WriteLateParsedTemplates(SemaRef);
4646 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4647 WriteFPPragmaOptions(SemaRef.getFPOptions());
4648 WriteOpenCLExtensions(SemaRef);
4649 WriteOpenCLExtensionTypes(SemaRef);
4650 WriteOpenCLExtensionDecls(SemaRef);
4651 WriteCUDAPragmas(SemaRef);
4652 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4654 // If we're emitting a module, write out the submodule information.
4656 WriteSubmodules(WritingModule);
4658 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4660 // Write the record containing external, unnamed definitions.
4661 if (!EagerlyDeserializedDecls.empty())
4662 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4664 // Write the record containing tentative definitions.
4665 if (!TentativeDefinitions.empty())
4666 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4668 // Write the record containing unused file scoped decls.
4669 if (!UnusedFileScopedDecls.empty())
4670 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4672 // Write the record containing weak undeclared identifiers.
4673 if (!WeakUndeclaredIdentifiers.empty())
4674 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4675 WeakUndeclaredIdentifiers);
4677 // Write the record containing ext_vector type names.
4678 if (!ExtVectorDecls.empty())
4679 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4681 // Write the record containing VTable uses information.
4682 if (!VTableUses.empty())
4683 Stream.EmitRecord(VTABLE_USES, VTableUses);
4685 // Write the record containing potentially unused local typedefs.
4686 if (!UnusedLocalTypedefNameCandidates.empty())
4687 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4688 UnusedLocalTypedefNameCandidates);
4690 // Write the record containing pending implicit instantiations.
4691 if (!PendingInstantiations.empty())
4692 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4694 // Write the record containing declaration references of Sema.
4695 if (!SemaDeclRefs.empty())
4696 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4698 // Write the record containing CUDA-specific declaration references.
4699 if (!CUDASpecialDeclRefs.empty())
4700 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4702 // Write the delegating constructors.
4703 if (!DelegatingCtorDecls.empty())
4704 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4706 // Write the known namespaces.
4707 if (!KnownNamespaces.empty())
4708 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4710 // Write the undefined internal functions and variables, and inline functions.
4711 if (!UndefinedButUsed.empty())
4712 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4714 if (!DeleteExprsToAnalyze.empty())
4715 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4717 // Write the visible updates to DeclContexts.
4718 for (auto *DC : UpdatedDeclContexts)
4719 WriteDeclContextVisibleUpdate(DC);
4721 if (!WritingModule) {
4722 // Write the submodules that were imported, if any.
4726 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4728 llvm::SmallVector<ModuleInfo, 64> Imports;
4729 for (const auto *I : Context.local_imports()) {
4730 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4731 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4732 I->getImportedModule()));
4735 if (!Imports.empty()) {
4736 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4739 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4740 return A.ID == B.ID;
4743 // Sort and deduplicate module IDs.
4744 std::sort(Imports.begin(), Imports.end(), Cmp);
4745 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4748 RecordData ImportedModules;
4749 for (const auto &Import : Imports) {
4750 ImportedModules.push_back(Import.ID);
4751 // FIXME: If the module has macros imported then later has declarations
4752 // imported, this location won't be the right one as a location for the
4753 // declaration imports.
4754 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4757 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4761 WriteObjCCategories();
4762 if(!WritingModule) {
4763 WriteOptimizePragmaOptions(SemaRef);
4764 WriteMSStructPragmaOptions(SemaRef);
4765 WriteMSPointersToMembersPragmaOptions(SemaRef);
4768 // Some simple statistics
4769 RecordData::value_type Record[] = {
4770 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4771 Stream.EmitRecord(STATISTICS, Record);
4774 // Write the module file extension blocks.
4775 for (const auto &ExtWriter : ModuleFileExtensionWriters)
4776 WriteModuleFileExtension(SemaRef, *ExtWriter);
4781 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4782 if (DeclUpdates.empty())
4785 DeclUpdateMap LocalUpdates;
4786 LocalUpdates.swap(DeclUpdates);
4788 for (auto &DeclUpdate : LocalUpdates) {
4789 const Decl *D = DeclUpdate.first;
4791 bool HasUpdatedBody = false;
4792 RecordData RecordData;
4793 ASTRecordWriter Record(*this, RecordData);
4794 for (auto &Update : DeclUpdate.second) {
4795 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4797 // An updated body is emitted last, so that the reader doesn't need
4798 // to skip over the lazy body to reach statements for other records.
4799 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4800 HasUpdatedBody = true;
4802 Record.push_back(Kind);
4805 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4806 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4807 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4808 assert(Update.getDecl() && "no decl to add?");
4809 Record.push_back(GetDeclRef(Update.getDecl()));
4812 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4815 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4816 Record.AddSourceLocation(Update.getLoc());
4819 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4820 Record.AddStmt(const_cast<Expr *>(
4821 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4824 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4826 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4829 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4830 auto *RD = cast<CXXRecordDecl>(D);
4831 UpdatedDeclContexts.insert(RD->getPrimaryContext());
4832 Record.AddCXXDefinitionData(RD);
4833 Record.AddOffset(WriteDeclContextLexicalBlock(
4834 *Context, const_cast<CXXRecordDecl *>(RD)));
4836 // This state is sometimes updated by template instantiation, when we
4837 // switch from the specialization referring to the template declaration
4838 // to it referring to the template definition.
4839 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4840 Record.push_back(MSInfo->getTemplateSpecializationKind());
4841 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4843 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4844 Record.push_back(Spec->getTemplateSpecializationKind());
4845 Record.AddSourceLocation(Spec->getPointOfInstantiation());
4847 // The instantiation might have been resolved to a partial
4848 // specialization. If so, record which one.
4849 auto From = Spec->getInstantiatedFrom();
4850 if (auto PartialSpec =
4851 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4852 Record.push_back(true);
4853 Record.AddDeclRef(PartialSpec);
4854 Record.AddTemplateArgumentList(
4855 &Spec->getTemplateInstantiationArgs());
4857 Record.push_back(false);
4860 Record.push_back(RD->getTagKind());
4861 Record.AddSourceLocation(RD->getLocation());
4862 Record.AddSourceLocation(RD->getLocStart());
4863 Record.AddSourceRange(RD->getBraceRange());
4865 // Instantiation may change attributes; write them all out afresh.
4866 Record.push_back(D->hasAttrs());
4868 Record.AddAttributes(D->getAttrs());
4870 // FIXME: Ensure we don't get here for explicit instantiations.
4874 case UPD_CXX_RESOLVED_DTOR_DELETE:
4875 Record.AddDeclRef(Update.getDecl());
4878 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4880 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4884 case UPD_CXX_DEDUCED_RETURN_TYPE:
4885 Record.push_back(GetOrCreateTypeID(Update.getType()));
4888 case UPD_DECL_MARKED_USED:
4891 case UPD_MANGLING_NUMBER:
4892 case UPD_STATIC_LOCAL_NUMBER:
4893 Record.push_back(Update.getNumber());
4896 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4897 Record.AddSourceRange(
4898 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
4901 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4902 Record.AddSourceRange(
4903 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4906 case UPD_DECL_EXPORTED:
4907 Record.push_back(getSubmoduleID(Update.getModule()));
4910 case UPD_ADDED_ATTR_TO_RECORD:
4911 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
4916 if (HasUpdatedBody) {
4917 const auto *Def = cast<FunctionDecl>(D);
4918 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4919 Record.push_back(Def->isInlined());
4920 Record.AddSourceLocation(Def->getInnerLocStart());
4921 Record.AddFunctionDefinition(Def);
4924 OffsetsRecord.push_back(GetDeclRef(D));
4925 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
4929 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4930 uint32_t Raw = Loc.getRawEncoding();
4931 Record.push_back((Raw << 1) | (Raw >> 31));
4934 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4935 AddSourceLocation(Range.getBegin(), Record);
4936 AddSourceLocation(Range.getEnd(), Record);
4939 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4940 Record->push_back(Value.getBitWidth());
4941 const uint64_t *Words = Value.getRawData();
4942 Record->append(Words, Words + Value.getNumWords());
4945 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4946 Record->push_back(Value.isUnsigned());
4950 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4951 AddAPInt(Value.bitcastToAPInt());
4954 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4955 Record.push_back(getIdentifierRef(II));
4958 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4962 IdentID &ID = IdentifierIDs[II];
4968 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4969 // Don't emit builtin macros like __LINE__ to the AST file unless they
4970 // have been redefined by the header (in which case they are not
4972 if (!MI || MI->isBuiltinMacro())
4975 MacroID &ID = MacroIDs[MI];
4978 MacroInfoToEmitData Info = { Name, MI, ID };
4979 MacroInfosToEmit.push_back(Info);
4984 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4985 if (!MI || MI->isBuiltinMacro())
4988 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4989 return MacroIDs[MI];
4992 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4993 return IdentMacroDirectivesOffsetMap.lookup(Name);
4996 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
4997 Record->push_back(Writer->getSelectorRef(SelRef));
5000 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5001 if (Sel.getAsOpaquePtr() == nullptr) {
5005 SelectorID SID = SelectorIDs[Sel];
5006 if (SID == 0 && Chain) {
5007 // This might trigger a ReadSelector callback, which will set the ID for
5009 Chain->LoadSelector(Sel);
5010 SID = SelectorIDs[Sel];
5013 SID = NextSelectorID++;
5014 SelectorIDs[Sel] = SID;
5019 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5020 AddDeclRef(Temp->getDestructor());
5023 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5024 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5026 case TemplateArgument::Expression:
5027 AddStmt(Arg.getAsExpr());
5029 case TemplateArgument::Type:
5030 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5032 case TemplateArgument::Template:
5033 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5034 AddSourceLocation(Arg.getTemplateNameLoc());
5036 case TemplateArgument::TemplateExpansion:
5037 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5038 AddSourceLocation(Arg.getTemplateNameLoc());
5039 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5041 case TemplateArgument::Null:
5042 case TemplateArgument::Integral:
5043 case TemplateArgument::Declaration:
5044 case TemplateArgument::NullPtr:
5045 case TemplateArgument::Pack:
5046 // FIXME: Is this right?
5051 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5052 AddTemplateArgument(Arg.getArgument());
5054 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5055 bool InfoHasSameExpr
5056 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5057 Record->push_back(InfoHasSameExpr);
5058 if (InfoHasSameExpr)
5059 return; // Avoid storing the same expr twice.
5061 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5064 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5066 AddTypeRef(QualType());
5070 AddTypeLoc(TInfo->getTypeLoc());
5073 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5074 AddTypeRef(TL.getType());
5076 TypeLocWriter TLW(*this);
5077 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5081 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5082 Record.push_back(GetOrCreateTypeID(T));
5085 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5087 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5090 assert(!T.getLocalFastQualifiers());
5092 TypeIdx &Idx = TypeIdxs[T];
5093 if (Idx.getIndex() == 0) {
5094 if (DoneWritingDeclsAndTypes) {
5095 assert(0 && "New type seen after serializing all the types to emit!");
5099 // We haven't seen this type before. Assign it a new ID and put it
5100 // into the queue of types to emit.
5101 Idx = TypeIdx(NextTypeID++);
5102 DeclTypesToEmit.push(T);
5108 TypeID ASTWriter::getTypeID(QualType T) const {
5110 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5113 assert(!T.getLocalFastQualifiers());
5115 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5116 assert(I != TypeIdxs.end() && "Type not emitted!");
5121 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5122 Record.push_back(GetDeclRef(D));
5125 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5126 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5132 // If D comes from an AST file, its declaration ID is already known and
5134 if (D->isFromASTFile())
5135 return D->getGlobalID();
5137 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5138 DeclID &ID = DeclIDs[D];
5140 if (DoneWritingDeclsAndTypes) {
5141 assert(0 && "New decl seen after serializing all the decls to emit!");
5145 // We haven't seen this declaration before. Give it a new ID and
5146 // enqueue it in the list of declarations to emit.
5148 DeclTypesToEmit.push(const_cast<Decl *>(D));
5154 DeclID ASTWriter::getDeclID(const Decl *D) {
5158 // If D comes from an AST file, its declaration ID is already known and
5160 if (D->isFromASTFile())
5161 return D->getGlobalID();
5163 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5167 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5171 SourceLocation Loc = D->getLocation();
5172 if (Loc.isInvalid())
5175 // We only keep track of the file-level declarations of each file.
5176 if (!D->getLexicalDeclContext()->isFileContext())
5178 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5179 // a function/objc method, should not have TU as lexical context.
5180 if (isa<ParmVarDecl>(D))
5183 SourceManager &SM = Context->getSourceManager();
5184 SourceLocation FileLoc = SM.getFileLoc(Loc);
5185 assert(SM.isLocalSourceLocation(FileLoc));
5188 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5189 if (FID.isInvalid())
5191 assert(SM.getSLocEntry(FID).isFile());
5193 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5195 Info = new DeclIDInFileInfo();
5197 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5198 LocDeclIDsTy &Decls = Info->DeclIDs;
5200 if (Decls.empty() || Decls.back().first <= Offset) {
5201 Decls.push_back(LocDecl);
5205 LocDeclIDsTy::iterator I =
5206 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5208 Decls.insert(I, LocDecl);
5211 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5212 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5213 Record->push_back(Name.getNameKind());
5214 switch (Name.getNameKind()) {
5215 case DeclarationName::Identifier:
5216 AddIdentifierRef(Name.getAsIdentifierInfo());
5219 case DeclarationName::ObjCZeroArgSelector:
5220 case DeclarationName::ObjCOneArgSelector:
5221 case DeclarationName::ObjCMultiArgSelector:
5222 AddSelectorRef(Name.getObjCSelector());
5225 case DeclarationName::CXXConstructorName:
5226 case DeclarationName::CXXDestructorName:
5227 case DeclarationName::CXXConversionFunctionName:
5228 AddTypeRef(Name.getCXXNameType());
5231 case DeclarationName::CXXOperatorName:
5232 Record->push_back(Name.getCXXOverloadedOperator());
5235 case DeclarationName::CXXLiteralOperatorName:
5236 AddIdentifierRef(Name.getCXXLiteralIdentifier());
5239 case DeclarationName::CXXUsingDirective:
5240 // No extra data to emit
5245 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5246 assert(needsAnonymousDeclarationNumber(D) &&
5247 "expected an anonymous declaration");
5249 // Number the anonymous declarations within this context, if we've not
5251 auto It = AnonymousDeclarationNumbers.find(D);
5252 if (It == AnonymousDeclarationNumbers.end()) {
5253 auto *DC = D->getLexicalDeclContext();
5254 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5255 AnonymousDeclarationNumbers[ND] = Number;
5258 It = AnonymousDeclarationNumbers.find(D);
5259 assert(It != AnonymousDeclarationNumbers.end() &&
5260 "declaration not found within its lexical context");
5266 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5267 DeclarationName Name) {
5268 switch (Name.getNameKind()) {
5269 case DeclarationName::CXXConstructorName:
5270 case DeclarationName::CXXDestructorName:
5271 case DeclarationName::CXXConversionFunctionName:
5272 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5275 case DeclarationName::CXXOperatorName:
5276 AddSourceLocation(SourceLocation::getFromRawEncoding(
5277 DNLoc.CXXOperatorName.BeginOpNameLoc));
5279 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5282 case DeclarationName::CXXLiteralOperatorName:
5283 AddSourceLocation(SourceLocation::getFromRawEncoding(
5284 DNLoc.CXXLiteralOperatorName.OpNameLoc));
5287 case DeclarationName::Identifier:
5288 case DeclarationName::ObjCZeroArgSelector:
5289 case DeclarationName::ObjCOneArgSelector:
5290 case DeclarationName::ObjCMultiArgSelector:
5291 case DeclarationName::CXXUsingDirective:
5296 void ASTRecordWriter::AddDeclarationNameInfo(
5297 const DeclarationNameInfo &NameInfo) {
5298 AddDeclarationName(NameInfo.getName());
5299 AddSourceLocation(NameInfo.getLoc());
5300 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5303 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5304 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5305 Record->push_back(Info.NumTemplParamLists);
5306 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5307 AddTemplateParameterList(Info.TemplParamLists[i]);
5310 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5311 // Nested name specifiers usually aren't too long. I think that 8 would
5312 // typically accommodate the vast majority.
5313 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5315 // Push each of the NNS's onto a stack for serialization in reverse order.
5317 NestedNames.push_back(NNS);
5318 NNS = NNS->getPrefix();
5321 Record->push_back(NestedNames.size());
5322 while(!NestedNames.empty()) {
5323 NNS = NestedNames.pop_back_val();
5324 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5325 Record->push_back(Kind);
5327 case NestedNameSpecifier::Identifier:
5328 AddIdentifierRef(NNS->getAsIdentifier());
5331 case NestedNameSpecifier::Namespace:
5332 AddDeclRef(NNS->getAsNamespace());
5335 case NestedNameSpecifier::NamespaceAlias:
5336 AddDeclRef(NNS->getAsNamespaceAlias());
5339 case NestedNameSpecifier::TypeSpec:
5340 case NestedNameSpecifier::TypeSpecWithTemplate:
5341 AddTypeRef(QualType(NNS->getAsType(), 0));
5342 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5345 case NestedNameSpecifier::Global:
5346 // Don't need to write an associated value.
5349 case NestedNameSpecifier::Super:
5350 AddDeclRef(NNS->getAsRecordDecl());
5356 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5357 // Nested name specifiers usually aren't too long. I think that 8 would
5358 // typically accommodate the vast majority.
5359 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5361 // Push each of the nested-name-specifiers's onto a stack for
5362 // serialization in reverse order.
5364 NestedNames.push_back(NNS);
5365 NNS = NNS.getPrefix();
5368 Record->push_back(NestedNames.size());
5369 while(!NestedNames.empty()) {
5370 NNS = NestedNames.pop_back_val();
5371 NestedNameSpecifier::SpecifierKind Kind
5372 = NNS.getNestedNameSpecifier()->getKind();
5373 Record->push_back(Kind);
5375 case NestedNameSpecifier::Identifier:
5376 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5377 AddSourceRange(NNS.getLocalSourceRange());
5380 case NestedNameSpecifier::Namespace:
5381 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5382 AddSourceRange(NNS.getLocalSourceRange());
5385 case NestedNameSpecifier::NamespaceAlias:
5386 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5387 AddSourceRange(NNS.getLocalSourceRange());
5390 case NestedNameSpecifier::TypeSpec:
5391 case NestedNameSpecifier::TypeSpecWithTemplate:
5392 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5393 AddTypeLoc(NNS.getTypeLoc());
5394 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5397 case NestedNameSpecifier::Global:
5398 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5401 case NestedNameSpecifier::Super:
5402 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5403 AddSourceRange(NNS.getLocalSourceRange());
5409 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5410 TemplateName::NameKind Kind = Name.getKind();
5411 Record->push_back(Kind);
5413 case TemplateName::Template:
5414 AddDeclRef(Name.getAsTemplateDecl());
5417 case TemplateName::OverloadedTemplate: {
5418 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5419 Record->push_back(OvT->size());
5420 for (const auto &I : *OvT)
5425 case TemplateName::QualifiedTemplate: {
5426 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5427 AddNestedNameSpecifier(QualT->getQualifier());
5428 Record->push_back(QualT->hasTemplateKeyword());
5429 AddDeclRef(QualT->getTemplateDecl());
5433 case TemplateName::DependentTemplate: {
5434 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5435 AddNestedNameSpecifier(DepT->getQualifier());
5436 Record->push_back(DepT->isIdentifier());
5437 if (DepT->isIdentifier())
5438 AddIdentifierRef(DepT->getIdentifier());
5440 Record->push_back(DepT->getOperator());
5444 case TemplateName::SubstTemplateTemplateParm: {
5445 SubstTemplateTemplateParmStorage *subst
5446 = Name.getAsSubstTemplateTemplateParm();
5447 AddDeclRef(subst->getParameter());
5448 AddTemplateName(subst->getReplacement());
5452 case TemplateName::SubstTemplateTemplateParmPack: {
5453 SubstTemplateTemplateParmPackStorage *SubstPack
5454 = Name.getAsSubstTemplateTemplateParmPack();
5455 AddDeclRef(SubstPack->getParameterPack());
5456 AddTemplateArgument(SubstPack->getArgumentPack());
5462 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5463 Record->push_back(Arg.getKind());
5464 switch (Arg.getKind()) {
5465 case TemplateArgument::Null:
5467 case TemplateArgument::Type:
5468 AddTypeRef(Arg.getAsType());
5470 case TemplateArgument::Declaration:
5471 AddDeclRef(Arg.getAsDecl());
5472 AddTypeRef(Arg.getParamTypeForDecl());
5474 case TemplateArgument::NullPtr:
5475 AddTypeRef(Arg.getNullPtrType());
5477 case TemplateArgument::Integral:
5478 AddAPSInt(Arg.getAsIntegral());
5479 AddTypeRef(Arg.getIntegralType());
5481 case TemplateArgument::Template:
5482 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5484 case TemplateArgument::TemplateExpansion:
5485 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5486 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5487 Record->push_back(*NumExpansions + 1);
5489 Record->push_back(0);
5491 case TemplateArgument::Expression:
5492 AddStmt(Arg.getAsExpr());
5494 case TemplateArgument::Pack:
5495 Record->push_back(Arg.pack_size());
5496 for (const auto &P : Arg.pack_elements())
5497 AddTemplateArgument(P);
5502 void ASTRecordWriter::AddTemplateParameterList(
5503 const TemplateParameterList *TemplateParams) {
5504 assert(TemplateParams && "No TemplateParams!");
5505 AddSourceLocation(TemplateParams->getTemplateLoc());
5506 AddSourceLocation(TemplateParams->getLAngleLoc());
5507 AddSourceLocation(TemplateParams->getRAngleLoc());
5509 Record->push_back(TemplateParams->size());
5510 for (const auto &P : *TemplateParams)
5514 /// \brief Emit a template argument list.
5515 void ASTRecordWriter::AddTemplateArgumentList(
5516 const TemplateArgumentList *TemplateArgs) {
5517 assert(TemplateArgs && "No TemplateArgs!");
5518 Record->push_back(TemplateArgs->size());
5519 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5520 AddTemplateArgument(TemplateArgs->get(i));
5523 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5524 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5525 assert(ASTTemplArgList && "No ASTTemplArgList!");
5526 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5527 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5528 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5529 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5530 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5531 AddTemplateArgumentLoc(TemplArgs[i]);
5534 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5535 Record->push_back(Set.size());
5536 for (ASTUnresolvedSet::const_iterator
5537 I = Set.begin(), E = Set.end(); I != E; ++I) {
5538 AddDeclRef(I.getDecl());
5539 Record->push_back(I.getAccess());
5543 // FIXME: Move this out of the main ASTRecordWriter interface.
5544 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5545 Record->push_back(Base.isVirtual());
5546 Record->push_back(Base.isBaseOfClass());
5547 Record->push_back(Base.getAccessSpecifierAsWritten());
5548 Record->push_back(Base.getInheritConstructors());
5549 AddTypeSourceInfo(Base.getTypeSourceInfo());
5550 AddSourceRange(Base.getSourceRange());
5551 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5552 : SourceLocation());
5555 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5556 ArrayRef<CXXBaseSpecifier> Bases) {
5557 ASTWriter::RecordData Record;
5558 ASTRecordWriter Writer(W, Record);
5559 Writer.push_back(Bases.size());
5561 for (auto &Base : Bases)
5562 Writer.AddCXXBaseSpecifier(Base);
5564 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5567 // FIXME: Move this out of the main ASTRecordWriter interface.
5568 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5569 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5573 EmitCXXCtorInitializers(ASTWriter &W,
5574 ArrayRef<CXXCtorInitializer *> CtorInits) {
5575 ASTWriter::RecordData Record;
5576 ASTRecordWriter Writer(W, Record);
5577 Writer.push_back(CtorInits.size());
5579 for (auto *Init : CtorInits) {
5580 if (Init->isBaseInitializer()) {
5581 Writer.push_back(CTOR_INITIALIZER_BASE);
5582 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5583 Writer.push_back(Init->isBaseVirtual());
5584 } else if (Init->isDelegatingInitializer()) {
5585 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5586 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5587 } else if (Init->isMemberInitializer()){
5588 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5589 Writer.AddDeclRef(Init->getMember());
5591 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5592 Writer.AddDeclRef(Init->getIndirectMember());
5595 Writer.AddSourceLocation(Init->getMemberLocation());
5596 Writer.AddStmt(Init->getInit());
5597 Writer.AddSourceLocation(Init->getLParenLoc());
5598 Writer.AddSourceLocation(Init->getRParenLoc());
5599 Writer.push_back(Init->isWritten());
5600 if (Init->isWritten())
5601 Writer.push_back(Init->getSourceOrder());
5604 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5607 // FIXME: Move this out of the main ASTRecordWriter interface.
5608 void ASTRecordWriter::AddCXXCtorInitializers(
5609 ArrayRef<CXXCtorInitializer *> CtorInits) {
5610 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5613 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5614 auto &Data = D->data();
5615 Record->push_back(Data.IsLambda);
5616 Record->push_back(Data.UserDeclaredConstructor);
5617 Record->push_back(Data.UserDeclaredSpecialMembers);
5618 Record->push_back(Data.Aggregate);
5619 Record->push_back(Data.PlainOldData);
5620 Record->push_back(Data.Empty);
5621 Record->push_back(Data.Polymorphic);
5622 Record->push_back(Data.Abstract);
5623 Record->push_back(Data.IsStandardLayout);
5624 Record->push_back(Data.HasNoNonEmptyBases);
5625 Record->push_back(Data.HasPrivateFields);
5626 Record->push_back(Data.HasProtectedFields);
5627 Record->push_back(Data.HasPublicFields);
5628 Record->push_back(Data.HasMutableFields);
5629 Record->push_back(Data.HasVariantMembers);
5630 Record->push_back(Data.HasOnlyCMembers);
5631 Record->push_back(Data.HasInClassInitializer);
5632 Record->push_back(Data.HasUninitializedReferenceMember);
5633 Record->push_back(Data.HasUninitializedFields);
5634 Record->push_back(Data.HasInheritedConstructor);
5635 Record->push_back(Data.HasInheritedAssignment);
5636 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5637 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5638 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5639 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5640 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5641 Record->push_back(Data.DefaultedDestructorIsDeleted);
5642 Record->push_back(Data.HasTrivialSpecialMembers);
5643 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5644 Record->push_back(Data.HasIrrelevantDestructor);
5645 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5646 Record->push_back(Data.HasDefaultedDefaultConstructor);
5647 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5648 Record->push_back(Data.HasConstexprDefaultConstructor);
5649 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5650 Record->push_back(Data.ComputedVisibleConversions);
5651 Record->push_back(Data.UserProvidedDefaultConstructor);
5652 Record->push_back(Data.DeclaredSpecialMembers);
5653 Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5654 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5655 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5656 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5657 // IsLambda bit is already saved.
5659 Record->push_back(Data.NumBases);
5660 if (Data.NumBases > 0)
5661 AddCXXBaseSpecifiers(Data.bases());
5663 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5664 Record->push_back(Data.NumVBases);
5665 if (Data.NumVBases > 0)
5666 AddCXXBaseSpecifiers(Data.vbases());
5668 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5669 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5670 // Data.Definition is the owning decl, no need to write it.
5671 AddDeclRef(D->getFirstFriend());
5673 // Add lambda-specific data.
5674 if (Data.IsLambda) {
5675 auto &Lambda = D->getLambdaData();
5676 Record->push_back(Lambda.Dependent);
5677 Record->push_back(Lambda.IsGenericLambda);
5678 Record->push_back(Lambda.CaptureDefault);
5679 Record->push_back(Lambda.NumCaptures);
5680 Record->push_back(Lambda.NumExplicitCaptures);
5681 Record->push_back(Lambda.ManglingNumber);
5682 AddDeclRef(D->getLambdaContextDecl());
5683 AddTypeSourceInfo(Lambda.MethodTyInfo);
5684 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5685 const LambdaCapture &Capture = Lambda.Captures[I];
5686 AddSourceLocation(Capture.getLocation());
5687 Record->push_back(Capture.isImplicit());
5688 Record->push_back(Capture.getCaptureKind());
5689 switch (Capture.getCaptureKind()) {
5697 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5699 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5700 : SourceLocation());
5707 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5708 assert(Reader && "Cannot remove chain");
5709 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5710 assert(FirstDeclID == NextDeclID &&
5711 FirstTypeID == NextTypeID &&
5712 FirstIdentID == NextIdentID &&
5713 FirstMacroID == NextMacroID &&
5714 FirstSubmoduleID == NextSubmoduleID &&
5715 FirstSelectorID == NextSelectorID &&
5716 "Setting chain after writing has started.");
5720 // Note, this will get called multiple times, once one the reader starts up
5721 // and again each time it's done reading a PCH or module.
5722 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5723 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5724 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5725 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5726 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5727 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5728 NextDeclID = FirstDeclID;
5729 NextTypeID = FirstTypeID;
5730 NextIdentID = FirstIdentID;
5731 NextMacroID = FirstMacroID;
5732 NextSelectorID = FirstSelectorID;
5733 NextSubmoduleID = FirstSubmoduleID;
5736 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5737 // Always keep the highest ID. See \p TypeRead() for more information.
5738 IdentID &StoredID = IdentifierIDs[II];
5743 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5744 // Always keep the highest ID. See \p TypeRead() for more information.
5745 MacroID &StoredID = MacroIDs[MI];
5750 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5751 // Always take the highest-numbered type index. This copes with an interesting
5752 // case for chained AST writing where we schedule writing the type and then,
5753 // later, deserialize the type from another AST. In this case, we want to
5754 // keep the higher-numbered entry so that we can properly write it out to
5756 TypeIdx &StoredIdx = TypeIdxs[T];
5757 if (Idx.getIndex() >= StoredIdx.getIndex())
5761 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5762 // Always keep the highest ID. See \p TypeRead() for more information.
5763 SelectorID &StoredID = SelectorIDs[S];
5768 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5769 MacroDefinitionRecord *MD) {
5770 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5771 MacroDefinitions[MD] = ID;
5774 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5775 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5776 SubmoduleIDs[Mod] = ID;
5779 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5780 if (Chain && Chain->isProcessingUpdateRecords()) return;
5781 assert(D->isCompleteDefinition());
5782 assert(!WritingAST && "Already writing the AST!");
5783 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5784 // We are interested when a PCH decl is modified.
5785 if (RD->isFromASTFile()) {
5786 // A forward reference was mutated into a definition. Rewrite it.
5787 // FIXME: This happens during template instantiation, should we
5788 // have created a new definition decl instead ?
5789 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5790 "completed a tag from another module but not by instantiation?");
5791 DeclUpdates[RD].push_back(
5792 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5797 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5798 if (D->isFromASTFile())
5801 // The predefined __va_list_tag struct is imported if we imported any decls.
5802 // FIXME: This is a gross hack.
5803 return D == D->getASTContext().getVaListTagDecl();
5806 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5807 if (Chain && Chain->isProcessingUpdateRecords()) return;
5808 assert(DC->isLookupContext() &&
5809 "Should not add lookup results to non-lookup contexts!");
5811 // TU is handled elsewhere.
5812 if (isa<TranslationUnitDecl>(DC))
5815 // Namespaces are handled elsewhere, except for template instantiations of
5816 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5817 // local instantiations are added to an imported context. Only happens when
5818 // adding ADL lookup candidates, for example templated friends.
5819 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5820 !isa<FunctionTemplateDecl>(D))
5823 // We're only interested in cases where a local declaration is added to an
5824 // imported context.
5825 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5828 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5829 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5830 assert(!WritingAST && "Already writing the AST!");
5831 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5832 // We're adding a visible declaration to a predefined decl context. Ensure
5833 // that we write out all of its lookup results so we don't get a nasty
5834 // surprise when we try to emit its lookup table.
5835 for (auto *Child : DC->decls())
5836 DeclsToEmitEvenIfUnreferenced.push_back(Child);
5838 DeclsToEmitEvenIfUnreferenced.push_back(D);
5841 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5842 if (Chain && Chain->isProcessingUpdateRecords()) return;
5843 assert(D->isImplicit());
5845 // We're only interested in cases where a local declaration is added to an
5846 // imported context.
5847 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5850 if (!isa<CXXMethodDecl>(D))
5853 // A decl coming from PCH was modified.
5854 assert(RD->isCompleteDefinition());
5855 assert(!WritingAST && "Already writing the AST!");
5856 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5859 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5860 if (Chain && Chain->isProcessingUpdateRecords()) return;
5861 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5863 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5864 // If we don't already know the exception specification for this redecl
5865 // chain, add an update record for it.
5866 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5868 ->castAs<FunctionProtoType>()
5869 ->getExceptionSpecType()))
5870 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5874 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5875 if (Chain && Chain->isProcessingUpdateRecords()) return;
5876 assert(!WritingAST && "Already writing the AST!");
5878 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5879 DeclUpdates[D].push_back(
5880 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5884 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5885 const FunctionDecl *Delete) {
5886 if (Chain && Chain->isProcessingUpdateRecords()) return;
5887 assert(!WritingAST && "Already writing the AST!");
5888 assert(Delete && "Not given an operator delete");
5890 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5891 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5895 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5896 if (Chain && Chain->isProcessingUpdateRecords()) return;
5897 assert(!WritingAST && "Already writing the AST!");
5898 if (!D->isFromASTFile())
5899 return; // Declaration not imported from PCH.
5901 // Implicit function decl from a PCH was defined.
5902 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5905 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5906 if (Chain && Chain->isProcessingUpdateRecords()) return;
5907 assert(!WritingAST && "Already writing the AST!");
5908 if (!D->isFromASTFile())
5911 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5914 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5915 if (Chain && Chain->isProcessingUpdateRecords()) return;
5916 assert(!WritingAST && "Already writing the AST!");
5917 if (!D->isFromASTFile())
5920 // Since the actual instantiation is delayed, this really means that we need
5921 // to update the instantiation location.
5922 DeclUpdates[D].push_back(
5923 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5924 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5927 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5928 if (Chain && Chain->isProcessingUpdateRecords()) return;
5929 assert(!WritingAST && "Already writing the AST!");
5930 if (!D->isFromASTFile())
5933 DeclUpdates[D].push_back(
5934 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5937 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5938 assert(!WritingAST && "Already writing the AST!");
5939 if (!D->isFromASTFile())
5942 DeclUpdates[D].push_back(
5943 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5946 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5947 const ObjCInterfaceDecl *IFD) {
5948 if (Chain && Chain->isProcessingUpdateRecords()) return;
5949 assert(!WritingAST && "Already writing the AST!");
5950 if (!IFD->isFromASTFile())
5951 return; // Declaration not imported from PCH.
5953 assert(IFD->getDefinition() && "Category on a class without a definition?");
5954 ObjCClassesWithCategories.insert(
5955 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5958 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5959 if (Chain && Chain->isProcessingUpdateRecords()) return;
5960 assert(!WritingAST && "Already writing the AST!");
5962 // If there is *any* declaration of the entity that's not from an AST file,
5963 // we can skip writing the update record. We make sure that isUsed() triggers
5964 // completion of the redeclaration chain of the entity.
5965 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5966 if (IsLocalDecl(Prev))
5969 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5972 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5973 if (Chain && Chain->isProcessingUpdateRecords()) return;
5974 assert(!WritingAST && "Already writing the AST!");
5975 if (!D->isFromASTFile())
5978 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5981 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5983 if (Chain && Chain->isProcessingUpdateRecords()) return;
5984 assert(!WritingAST && "Already writing the AST!");
5985 if (!D->isFromASTFile())
5988 DeclUpdates[D].push_back(
5989 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
5992 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5993 if (Chain && Chain->isProcessingUpdateRecords()) return;
5994 assert(!WritingAST && "Already writing the AST!");
5995 assert(D->isHidden() && "expected a hidden declaration");
5996 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
5999 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6000 const RecordDecl *Record) {
6001 if (Chain && Chain->isProcessingUpdateRecords()) return;
6002 assert(!WritingAST && "Already writing the AST!");
6003 if (!Record->isFromASTFile())
6005 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6008 void ASTWriter::AddedCXXTemplateSpecialization(
6009 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6010 assert(!WritingAST && "Already writing the AST!");
6012 if (!TD->getFirstDecl()->isFromASTFile())
6014 if (Chain && Chain->isProcessingUpdateRecords())
6017 DeclsToEmitEvenIfUnreferenced.push_back(D);
6020 void ASTWriter::AddedCXXTemplateSpecialization(
6021 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6022 assert(!WritingAST && "Already writing the AST!");
6024 if (!TD->getFirstDecl()->isFromASTFile())
6026 if (Chain && Chain->isProcessingUpdateRecords())
6029 DeclsToEmitEvenIfUnreferenced.push_back(D);
6032 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6033 const FunctionDecl *D) {
6034 assert(!WritingAST && "Already writing the AST!");
6036 if (!TD->getFirstDecl()->isFromASTFile())
6038 if (Chain && Chain->isProcessingUpdateRecords())
6041 DeclsToEmitEvenIfUnreferenced.push_back(D);