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.AddSourceRange(TL.getExceptionSpecRange());
633 Record.AddSourceLocation(TL.getLocalRangeEnd());
634 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
635 Record.AddDeclRef(TL.getParam(i));
637 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
638 VisitFunctionTypeLoc(TL);
640 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
641 VisitFunctionTypeLoc(TL);
643 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
644 Record.AddSourceLocation(TL.getNameLoc());
646 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
647 Record.AddSourceLocation(TL.getNameLoc());
649 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
650 if (TL.getNumProtocols()) {
651 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
652 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
654 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
655 Record.AddSourceLocation(TL.getProtocolLoc(i));
657 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
658 Record.AddSourceLocation(TL.getTypeofLoc());
659 Record.AddSourceLocation(TL.getLParenLoc());
660 Record.AddSourceLocation(TL.getRParenLoc());
663 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
664 Record.AddSourceLocation(TL.getTypeofLoc());
665 Record.AddSourceLocation(TL.getLParenLoc());
666 Record.AddSourceLocation(TL.getRParenLoc());
667 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
670 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
671 Record.AddSourceLocation(TL.getNameLoc());
674 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
675 Record.AddSourceLocation(TL.getKWLoc());
676 Record.AddSourceLocation(TL.getLParenLoc());
677 Record.AddSourceLocation(TL.getRParenLoc());
678 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
681 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
682 Record.AddSourceLocation(TL.getNameLoc());
685 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
686 Record.AddSourceLocation(TL.getNameLoc());
689 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
690 Record.AddSourceLocation(TL.getNameLoc());
693 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
694 Record.AddSourceLocation(TL.getAttrNameLoc());
695 if (TL.hasAttrOperand()) {
696 SourceRange range = TL.getAttrOperandParensRange();
697 Record.AddSourceLocation(range.getBegin());
698 Record.AddSourceLocation(range.getEnd());
700 if (TL.hasAttrExprOperand()) {
701 Expr *operand = TL.getAttrExprOperand();
702 Record.push_back(operand ? 1 : 0);
703 if (operand) Record.AddStmt(operand);
704 } else if (TL.hasAttrEnumOperand()) {
705 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
709 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
710 Record.AddSourceLocation(TL.getNameLoc());
713 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
714 SubstTemplateTypeParmTypeLoc TL) {
715 Record.AddSourceLocation(TL.getNameLoc());
718 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
719 SubstTemplateTypeParmPackTypeLoc TL) {
720 Record.AddSourceLocation(TL.getNameLoc());
723 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
724 TemplateSpecializationTypeLoc TL) {
725 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
726 Record.AddSourceLocation(TL.getTemplateNameLoc());
727 Record.AddSourceLocation(TL.getLAngleLoc());
728 Record.AddSourceLocation(TL.getRAngleLoc());
729 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
730 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
731 TL.getArgLoc(i).getLocInfo());
734 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
735 Record.AddSourceLocation(TL.getLParenLoc());
736 Record.AddSourceLocation(TL.getRParenLoc());
739 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
740 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
741 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
744 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
745 Record.AddSourceLocation(TL.getNameLoc());
748 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
749 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
750 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
751 Record.AddSourceLocation(TL.getNameLoc());
754 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
755 DependentTemplateSpecializationTypeLoc TL) {
756 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
757 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
758 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
759 Record.AddSourceLocation(TL.getTemplateNameLoc());
760 Record.AddSourceLocation(TL.getLAngleLoc());
761 Record.AddSourceLocation(TL.getRAngleLoc());
762 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
763 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
764 TL.getArgLoc(I).getLocInfo());
767 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
768 Record.AddSourceLocation(TL.getEllipsisLoc());
771 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
772 Record.AddSourceLocation(TL.getNameLoc());
775 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
776 Record.push_back(TL.hasBaseTypeAsWritten());
777 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
778 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
779 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
780 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
781 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
782 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
783 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
784 Record.AddSourceLocation(TL.getProtocolLoc(i));
787 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
788 Record.AddSourceLocation(TL.getStarLoc());
791 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
792 Record.AddSourceLocation(TL.getKWLoc());
793 Record.AddSourceLocation(TL.getLParenLoc());
794 Record.AddSourceLocation(TL.getRParenLoc());
797 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
798 Record.AddSourceLocation(TL.getKWLoc());
801 void ASTWriter::WriteTypeAbbrevs() {
802 using namespace llvm;
804 std::shared_ptr<BitCodeAbbrev> Abv;
806 // Abbreviation for TYPE_EXT_QUAL
807 Abv = std::make_shared<BitCodeAbbrev>();
808 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
809 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
810 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
811 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
813 // Abbreviation for TYPE_FUNCTION_PROTO
814 Abv = std::make_shared<BitCodeAbbrev>();
815 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
817 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
818 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
819 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
820 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
821 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
822 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
824 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
825 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
826 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
827 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
828 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
829 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
830 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
831 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
832 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
835 //===----------------------------------------------------------------------===//
836 // ASTWriter Implementation
837 //===----------------------------------------------------------------------===//
839 static void EmitBlockID(unsigned ID, const char *Name,
840 llvm::BitstreamWriter &Stream,
841 ASTWriter::RecordDataImpl &Record) {
843 Record.push_back(ID);
844 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
846 // Emit the block name if present.
847 if (!Name || Name[0] == 0)
851 Record.push_back(*Name++);
852 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
855 static void EmitRecordID(unsigned ID, const char *Name,
856 llvm::BitstreamWriter &Stream,
857 ASTWriter::RecordDataImpl &Record) {
859 Record.push_back(ID);
861 Record.push_back(*Name++);
862 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
865 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
866 ASTWriter::RecordDataImpl &Record) {
867 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
869 RECORD(STMT_NULL_PTR);
870 RECORD(STMT_REF_PTR);
872 RECORD(STMT_COMPOUND);
874 RECORD(STMT_DEFAULT);
876 RECORD(STMT_ATTRIBUTED);
883 RECORD(STMT_INDIRECT_GOTO);
884 RECORD(STMT_CONTINUE);
890 RECORD(EXPR_PREDEFINED);
891 RECORD(EXPR_DECL_REF);
892 RECORD(EXPR_INTEGER_LITERAL);
893 RECORD(EXPR_FLOATING_LITERAL);
894 RECORD(EXPR_IMAGINARY_LITERAL);
895 RECORD(EXPR_STRING_LITERAL);
896 RECORD(EXPR_CHARACTER_LITERAL);
898 RECORD(EXPR_PAREN_LIST);
899 RECORD(EXPR_UNARY_OPERATOR);
900 RECORD(EXPR_SIZEOF_ALIGN_OF);
901 RECORD(EXPR_ARRAY_SUBSCRIPT);
904 RECORD(EXPR_BINARY_OPERATOR);
905 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
906 RECORD(EXPR_CONDITIONAL_OPERATOR);
907 RECORD(EXPR_IMPLICIT_CAST);
908 RECORD(EXPR_CSTYLE_CAST);
909 RECORD(EXPR_COMPOUND_LITERAL);
910 RECORD(EXPR_EXT_VECTOR_ELEMENT);
911 RECORD(EXPR_INIT_LIST);
912 RECORD(EXPR_DESIGNATED_INIT);
913 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
914 RECORD(EXPR_IMPLICIT_VALUE_INIT);
915 RECORD(EXPR_NO_INIT);
917 RECORD(EXPR_ADDR_LABEL);
920 RECORD(EXPR_GNU_NULL);
921 RECORD(EXPR_SHUFFLE_VECTOR);
923 RECORD(EXPR_GENERIC_SELECTION);
924 RECORD(EXPR_OBJC_STRING_LITERAL);
925 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
926 RECORD(EXPR_OBJC_ARRAY_LITERAL);
927 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
928 RECORD(EXPR_OBJC_ENCODE);
929 RECORD(EXPR_OBJC_SELECTOR_EXPR);
930 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
931 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
932 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
933 RECORD(EXPR_OBJC_KVC_REF_EXPR);
934 RECORD(EXPR_OBJC_MESSAGE_EXPR);
935 RECORD(STMT_OBJC_FOR_COLLECTION);
936 RECORD(STMT_OBJC_CATCH);
937 RECORD(STMT_OBJC_FINALLY);
938 RECORD(STMT_OBJC_AT_TRY);
939 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
940 RECORD(STMT_OBJC_AT_THROW);
941 RECORD(EXPR_OBJC_BOOL_LITERAL);
942 RECORD(STMT_CXX_CATCH);
943 RECORD(STMT_CXX_TRY);
944 RECORD(STMT_CXX_FOR_RANGE);
945 RECORD(EXPR_CXX_OPERATOR_CALL);
946 RECORD(EXPR_CXX_MEMBER_CALL);
947 RECORD(EXPR_CXX_CONSTRUCT);
948 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
949 RECORD(EXPR_CXX_STATIC_CAST);
950 RECORD(EXPR_CXX_DYNAMIC_CAST);
951 RECORD(EXPR_CXX_REINTERPRET_CAST);
952 RECORD(EXPR_CXX_CONST_CAST);
953 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
954 RECORD(EXPR_USER_DEFINED_LITERAL);
955 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
956 RECORD(EXPR_CXX_BOOL_LITERAL);
957 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
958 RECORD(EXPR_CXX_TYPEID_EXPR);
959 RECORD(EXPR_CXX_TYPEID_TYPE);
960 RECORD(EXPR_CXX_THIS);
961 RECORD(EXPR_CXX_THROW);
962 RECORD(EXPR_CXX_DEFAULT_ARG);
963 RECORD(EXPR_CXX_DEFAULT_INIT);
964 RECORD(EXPR_CXX_BIND_TEMPORARY);
965 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
966 RECORD(EXPR_CXX_NEW);
967 RECORD(EXPR_CXX_DELETE);
968 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
969 RECORD(EXPR_EXPR_WITH_CLEANUPS);
970 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
971 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
972 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
973 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
974 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
975 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
976 RECORD(EXPR_CXX_NOEXCEPT);
977 RECORD(EXPR_OPAQUE_VALUE);
978 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
979 RECORD(EXPR_TYPE_TRAIT);
980 RECORD(EXPR_ARRAY_TYPE_TRAIT);
981 RECORD(EXPR_PACK_EXPANSION);
982 RECORD(EXPR_SIZEOF_PACK);
983 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
984 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
985 RECORD(EXPR_FUNCTION_PARM_PACK);
986 RECORD(EXPR_MATERIALIZE_TEMPORARY);
987 RECORD(EXPR_CUDA_KERNEL_CALL);
988 RECORD(EXPR_CXX_UUIDOF_EXPR);
989 RECORD(EXPR_CXX_UUIDOF_TYPE);
994 void ASTWriter::WriteBlockInfoBlock() {
996 Stream.EnterBlockInfoBlock();
998 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
999 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1002 BLOCK(CONTROL_BLOCK);
1005 RECORD(MODULE_NAME);
1006 RECORD(MODULE_DIRECTORY);
1007 RECORD(MODULE_MAP_FILE);
1009 RECORD(ORIGINAL_FILE);
1010 RECORD(ORIGINAL_PCH_DIR);
1011 RECORD(ORIGINAL_FILE_ID);
1012 RECORD(INPUT_FILE_OFFSETS);
1014 BLOCK(OPTIONS_BLOCK);
1015 RECORD(LANGUAGE_OPTIONS);
1016 RECORD(TARGET_OPTIONS);
1017 RECORD(DIAGNOSTIC_OPTIONS);
1018 RECORD(FILE_SYSTEM_OPTIONS);
1019 RECORD(HEADER_SEARCH_OPTIONS);
1020 RECORD(PREPROCESSOR_OPTIONS);
1022 BLOCK(INPUT_FILES_BLOCK);
1025 // AST Top-Level Block.
1027 RECORD(TYPE_OFFSET);
1028 RECORD(DECL_OFFSET);
1029 RECORD(IDENTIFIER_OFFSET);
1030 RECORD(IDENTIFIER_TABLE);
1031 RECORD(EAGERLY_DESERIALIZED_DECLS);
1032 RECORD(SPECIAL_TYPES);
1034 RECORD(TENTATIVE_DEFINITIONS);
1035 RECORD(SELECTOR_OFFSETS);
1036 RECORD(METHOD_POOL);
1037 RECORD(PP_COUNTER_VALUE);
1038 RECORD(SOURCE_LOCATION_OFFSETS);
1039 RECORD(SOURCE_LOCATION_PRELOADS);
1040 RECORD(EXT_VECTOR_DECLS);
1041 RECORD(UNUSED_FILESCOPED_DECLS);
1042 RECORD(PPD_ENTITIES_OFFSETS);
1043 RECORD(VTABLE_USES);
1044 RECORD(REFERENCED_SELECTOR_POOL);
1045 RECORD(TU_UPDATE_LEXICAL);
1046 RECORD(SEMA_DECL_REFS);
1047 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1048 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1049 RECORD(UPDATE_VISIBLE);
1050 RECORD(DECL_UPDATE_OFFSETS);
1051 RECORD(DECL_UPDATES);
1052 RECORD(DIAG_PRAGMA_MAPPINGS);
1053 RECORD(CUDA_SPECIAL_DECL_REFS);
1054 RECORD(HEADER_SEARCH_TABLE);
1055 RECORD(FP_PRAGMA_OPTIONS);
1056 RECORD(OPENCL_EXTENSIONS);
1057 RECORD(OPENCL_EXTENSION_TYPES);
1058 RECORD(OPENCL_EXTENSION_DECLS);
1059 RECORD(DELEGATING_CTORS);
1060 RECORD(KNOWN_NAMESPACES);
1061 RECORD(MODULE_OFFSET_MAP);
1062 RECORD(SOURCE_MANAGER_LINE_TABLE);
1063 RECORD(OBJC_CATEGORIES_MAP);
1064 RECORD(FILE_SORTED_DECLS);
1065 RECORD(IMPORTED_MODULES);
1066 RECORD(OBJC_CATEGORIES);
1067 RECORD(MACRO_OFFSET);
1068 RECORD(INTERESTING_IDENTIFIERS);
1069 RECORD(UNDEFINED_BUT_USED);
1070 RECORD(LATE_PARSED_TEMPLATE);
1071 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1072 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1073 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1074 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1075 RECORD(DELETE_EXPRS_TO_ANALYZE);
1076 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1078 // SourceManager Block.
1079 BLOCK(SOURCE_MANAGER_BLOCK);
1080 RECORD(SM_SLOC_FILE_ENTRY);
1081 RECORD(SM_SLOC_BUFFER_ENTRY);
1082 RECORD(SM_SLOC_BUFFER_BLOB);
1083 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1084 RECORD(SM_SLOC_EXPANSION_ENTRY);
1086 // Preprocessor Block.
1087 BLOCK(PREPROCESSOR_BLOCK);
1088 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1089 RECORD(PP_MACRO_FUNCTION_LIKE);
1090 RECORD(PP_MACRO_OBJECT_LIKE);
1091 RECORD(PP_MODULE_MACRO);
1095 BLOCK(SUBMODULE_BLOCK);
1096 RECORD(SUBMODULE_METADATA);
1097 RECORD(SUBMODULE_DEFINITION);
1098 RECORD(SUBMODULE_UMBRELLA_HEADER);
1099 RECORD(SUBMODULE_HEADER);
1100 RECORD(SUBMODULE_TOPHEADER);
1101 RECORD(SUBMODULE_UMBRELLA_DIR);
1102 RECORD(SUBMODULE_IMPORTS);
1103 RECORD(SUBMODULE_EXPORTS);
1104 RECORD(SUBMODULE_REQUIRES);
1105 RECORD(SUBMODULE_EXCLUDED_HEADER);
1106 RECORD(SUBMODULE_LINK_LIBRARY);
1107 RECORD(SUBMODULE_CONFIG_MACRO);
1108 RECORD(SUBMODULE_CONFLICT);
1109 RECORD(SUBMODULE_PRIVATE_HEADER);
1110 RECORD(SUBMODULE_TEXTUAL_HEADER);
1111 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1112 RECORD(SUBMODULE_INITIALIZERS);
1115 BLOCK(COMMENTS_BLOCK);
1116 RECORD(COMMENTS_RAW_COMMENT);
1118 // Decls and Types block.
1119 BLOCK(DECLTYPES_BLOCK);
1120 RECORD(TYPE_EXT_QUAL);
1121 RECORD(TYPE_COMPLEX);
1122 RECORD(TYPE_POINTER);
1123 RECORD(TYPE_BLOCK_POINTER);
1124 RECORD(TYPE_LVALUE_REFERENCE);
1125 RECORD(TYPE_RVALUE_REFERENCE);
1126 RECORD(TYPE_MEMBER_POINTER);
1127 RECORD(TYPE_CONSTANT_ARRAY);
1128 RECORD(TYPE_INCOMPLETE_ARRAY);
1129 RECORD(TYPE_VARIABLE_ARRAY);
1130 RECORD(TYPE_VECTOR);
1131 RECORD(TYPE_EXT_VECTOR);
1132 RECORD(TYPE_FUNCTION_NO_PROTO);
1133 RECORD(TYPE_FUNCTION_PROTO);
1134 RECORD(TYPE_TYPEDEF);
1135 RECORD(TYPE_TYPEOF_EXPR);
1136 RECORD(TYPE_TYPEOF);
1137 RECORD(TYPE_RECORD);
1139 RECORD(TYPE_OBJC_INTERFACE);
1140 RECORD(TYPE_OBJC_OBJECT_POINTER);
1141 RECORD(TYPE_DECLTYPE);
1142 RECORD(TYPE_ELABORATED);
1143 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1144 RECORD(TYPE_UNRESOLVED_USING);
1145 RECORD(TYPE_INJECTED_CLASS_NAME);
1146 RECORD(TYPE_OBJC_OBJECT);
1147 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1148 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1149 RECORD(TYPE_DEPENDENT_NAME);
1150 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1151 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1153 RECORD(TYPE_PACK_EXPANSION);
1154 RECORD(TYPE_ATTRIBUTED);
1155 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1157 RECORD(TYPE_UNARY_TRANSFORM);
1158 RECORD(TYPE_ATOMIC);
1159 RECORD(TYPE_DECAYED);
1160 RECORD(TYPE_ADJUSTED);
1161 RECORD(TYPE_OBJC_TYPE_PARAM);
1162 RECORD(LOCAL_REDECLARATIONS);
1163 RECORD(DECL_TYPEDEF);
1164 RECORD(DECL_TYPEALIAS);
1166 RECORD(DECL_RECORD);
1167 RECORD(DECL_ENUM_CONSTANT);
1168 RECORD(DECL_FUNCTION);
1169 RECORD(DECL_OBJC_METHOD);
1170 RECORD(DECL_OBJC_INTERFACE);
1171 RECORD(DECL_OBJC_PROTOCOL);
1172 RECORD(DECL_OBJC_IVAR);
1173 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1174 RECORD(DECL_OBJC_CATEGORY);
1175 RECORD(DECL_OBJC_CATEGORY_IMPL);
1176 RECORD(DECL_OBJC_IMPLEMENTATION);
1177 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1178 RECORD(DECL_OBJC_PROPERTY);
1179 RECORD(DECL_OBJC_PROPERTY_IMPL);
1181 RECORD(DECL_MS_PROPERTY);
1183 RECORD(DECL_IMPLICIT_PARAM);
1184 RECORD(DECL_PARM_VAR);
1185 RECORD(DECL_FILE_SCOPE_ASM);
1187 RECORD(DECL_CONTEXT_LEXICAL);
1188 RECORD(DECL_CONTEXT_VISIBLE);
1189 RECORD(DECL_NAMESPACE);
1190 RECORD(DECL_NAMESPACE_ALIAS);
1192 RECORD(DECL_USING_SHADOW);
1193 RECORD(DECL_USING_DIRECTIVE);
1194 RECORD(DECL_UNRESOLVED_USING_VALUE);
1195 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1196 RECORD(DECL_LINKAGE_SPEC);
1197 RECORD(DECL_CXX_RECORD);
1198 RECORD(DECL_CXX_METHOD);
1199 RECORD(DECL_CXX_CONSTRUCTOR);
1200 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
1201 RECORD(DECL_CXX_DESTRUCTOR);
1202 RECORD(DECL_CXX_CONVERSION);
1203 RECORD(DECL_ACCESS_SPEC);
1204 RECORD(DECL_FRIEND);
1205 RECORD(DECL_FRIEND_TEMPLATE);
1206 RECORD(DECL_CLASS_TEMPLATE);
1207 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1208 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1209 RECORD(DECL_VAR_TEMPLATE);
1210 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1211 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1212 RECORD(DECL_FUNCTION_TEMPLATE);
1213 RECORD(DECL_TEMPLATE_TYPE_PARM);
1214 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1215 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1216 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1217 RECORD(DECL_STATIC_ASSERT);
1218 RECORD(DECL_CXX_BASE_SPECIFIERS);
1219 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1220 RECORD(DECL_INDIRECTFIELD);
1221 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1222 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1223 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1224 RECORD(DECL_IMPORT);
1225 RECORD(DECL_OMP_THREADPRIVATE);
1227 RECORD(DECL_OBJC_TYPE_PARAM);
1228 RECORD(DECL_OMP_CAPTUREDEXPR);
1229 RECORD(DECL_PRAGMA_COMMENT);
1230 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1231 RECORD(DECL_OMP_DECLARE_REDUCTION);
1233 // Statements and Exprs can occur in the Decls and Types block.
1234 AddStmtsExprs(Stream, Record);
1236 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1237 RECORD(PPD_MACRO_EXPANSION);
1238 RECORD(PPD_MACRO_DEFINITION);
1239 RECORD(PPD_INCLUSION_DIRECTIVE);
1241 // Decls and Types block.
1242 BLOCK(EXTENSION_BLOCK);
1243 RECORD(EXTENSION_METADATA);
1250 /// \brief Prepares a path for being written to an AST file by converting it
1251 /// to an absolute path and removing nested './'s.
1253 /// \return \c true if the path was changed.
1254 static bool cleanPathForOutput(FileManager &FileMgr,
1255 SmallVectorImpl<char> &Path) {
1256 bool Changed = FileMgr.makeAbsolutePath(Path);
1257 return Changed | llvm::sys::path::remove_dots(Path);
1260 /// \brief Adjusts the given filename to only write out the portion of the
1261 /// filename that is not part of the system root directory.
1263 /// \param Filename the file name to adjust.
1265 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1266 /// the returned filename will be adjusted by this root directory.
1268 /// \returns either the original filename (if it needs no adjustment) or the
1269 /// adjusted filename (which points into the @p Filename parameter).
1271 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1272 assert(Filename && "No file name to adjust?");
1274 if (BaseDir.empty())
1277 // Verify that the filename and the system root have the same prefix.
1279 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1280 if (Filename[Pos] != BaseDir[Pos])
1281 return Filename; // Prefixes don't match.
1283 // We hit the end of the filename before we hit the end of the system root.
1287 // If there's not a path separator at the end of the base directory nor
1288 // immediately after it, then this isn't within the base directory.
1289 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1290 if (!llvm::sys::path::is_separator(BaseDir.back()))
1293 // If the file name has a '/' at the current position, skip over the '/'.
1294 // We distinguish relative paths from absolute paths by the
1295 // absence of '/' at the beginning of relative paths.
1297 // FIXME: This is wrong. We distinguish them by asking if the path is
1298 // absolute, which isn't the same thing. And there might be multiple '/'s
1299 // in a row. Use a better mechanism to indicate whether we have emitted an
1300 // absolute or relative path.
1304 return Filename + Pos;
1307 static ASTFileSignature getSignature() {
1309 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1311 // Rely on GetRandomNumber to eventually return non-zero...
1315 /// \brief Write the control block.
1316 uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1317 ASTContext &Context,
1319 const std::string &OutputFile) {
1320 ASTFileSignature Signature = 0;
1322 using namespace llvm;
1323 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1327 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1328 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1329 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1330 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1331 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1332 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1333 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1334 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1335 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1336 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1337 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1338 assert((!WritingModule || isysroot.empty()) &&
1339 "writing module as a relocatable PCH?");
1341 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1342 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1343 !isysroot.empty(), IncludeTimestamps,
1344 ASTHasCompilerErrors};
1345 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1346 getClangFullRepositoryVersion());
1348 if (WritingModule) {
1349 // For implicit modules we output a signature that we can use to ensure
1350 // duplicate module builds don't collide in the cache as their output order
1351 // is non-deterministic.
1352 // FIXME: Remove this when output is deterministic.
1353 if (Context.getLangOpts().ImplicitModules) {
1354 Signature = getSignature();
1355 RecordData::value_type Record[] = {Signature};
1356 Stream.EmitRecord(SIGNATURE, Record);
1360 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1361 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1362 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1363 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1364 RecordData::value_type Record[] = {MODULE_NAME};
1365 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1368 if (WritingModule && WritingModule->Directory) {
1369 SmallString<128> BaseDir(WritingModule->Directory->getName());
1370 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1372 // If the home of the module is the current working directory, then we
1373 // want to pick up the cwd of the build process loading the module, not
1374 // our cwd, when we load this module.
1375 if (!PP.getHeaderSearchInfo()
1376 .getHeaderSearchOpts()
1377 .ModuleMapFileHomeIsCwd ||
1378 WritingModule->Directory->getName() != StringRef(".")) {
1379 // Module directory.
1380 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1381 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1383 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1385 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1386 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1389 // Write out all other paths relative to the base directory if possible.
1390 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1391 } else if (!isysroot.empty()) {
1392 // Write out paths relative to the sysroot if possible.
1393 BaseDirectory = isysroot;
1397 if (WritingModule) {
1400 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1402 // Primary module map file.
1403 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1405 // Additional module map files.
1406 if (auto *AdditionalModMaps =
1407 Map.getAdditionalModuleMapFiles(WritingModule)) {
1408 Record.push_back(AdditionalModMaps->size());
1409 for (const FileEntry *F : *AdditionalModMaps)
1410 AddPath(F->getName(), Record);
1412 Record.push_back(0);
1415 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1420 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1423 for (auto *M : Mgr) {
1424 // Skip modules that weren't directly imported.
1425 if (!M->isDirectlyImported())
1428 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1429 AddSourceLocation(M->ImportLoc, Record);
1430 Record.push_back(M->File->getSize());
1431 Record.push_back(getTimestampForOutput(M->File));
1432 Record.push_back(M->Signature);
1433 AddPath(M->FileName, Record);
1435 Stream.EmitRecord(IMPORTS, Record);
1438 // Write the options block.
1439 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1441 // Language options.
1443 const LangOptions &LangOpts = Context.getLangOpts();
1444 #define LANGOPT(Name, Bits, Default, Description) \
1445 Record.push_back(LangOpts.Name);
1446 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1447 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1448 #include "clang/Basic/LangOptions.def"
1449 #define SANITIZER(NAME, ID) \
1450 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1451 #include "clang/Basic/Sanitizers.def"
1453 Record.push_back(LangOpts.ModuleFeatures.size());
1454 for (StringRef Feature : LangOpts.ModuleFeatures)
1455 AddString(Feature, Record);
1457 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1458 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1460 AddString(LangOpts.CurrentModule, Record);
1463 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1464 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1465 AddString(I, Record);
1467 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1469 // OpenMP offloading options.
1470 Record.push_back(LangOpts.OMPTargetTriples.size());
1471 for (auto &T : LangOpts.OMPTargetTriples)
1472 AddString(T.getTriple(), Record);
1474 AddString(LangOpts.OMPHostIRFile, Record);
1476 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1480 const TargetInfo &Target = Context.getTargetInfo();
1481 const TargetOptions &TargetOpts = Target.getTargetOpts();
1482 AddString(TargetOpts.Triple, Record);
1483 AddString(TargetOpts.CPU, Record);
1484 AddString(TargetOpts.ABI, Record);
1485 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1486 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1487 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1489 Record.push_back(TargetOpts.Features.size());
1490 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1491 AddString(TargetOpts.Features[I], Record);
1493 Stream.EmitRecord(TARGET_OPTIONS, Record);
1495 // Diagnostic options.
1497 const DiagnosticOptions &DiagOpts
1498 = Context.getDiagnostics().getDiagnosticOptions();
1499 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1500 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1501 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1502 #include "clang/Basic/DiagnosticOptions.def"
1503 Record.push_back(DiagOpts.Warnings.size());
1504 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1505 AddString(DiagOpts.Warnings[I], Record);
1506 Record.push_back(DiagOpts.Remarks.size());
1507 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1508 AddString(DiagOpts.Remarks[I], Record);
1509 // Note: we don't serialize the log or serialization file names, because they
1510 // are generally transient files and will almost always be overridden.
1511 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1513 // File system options.
1515 const FileSystemOptions &FSOpts =
1516 Context.getSourceManager().getFileManager().getFileSystemOpts();
1517 AddString(FSOpts.WorkingDir, Record);
1518 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1520 // Header search options.
1522 const HeaderSearchOptions &HSOpts
1523 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1524 AddString(HSOpts.Sysroot, Record);
1527 Record.push_back(HSOpts.UserEntries.size());
1528 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1529 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1530 AddString(Entry.Path, Record);
1531 Record.push_back(static_cast<unsigned>(Entry.Group));
1532 Record.push_back(Entry.IsFramework);
1533 Record.push_back(Entry.IgnoreSysRoot);
1536 // System header prefixes.
1537 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1538 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1539 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1540 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1543 AddString(HSOpts.ResourceDir, Record);
1544 AddString(HSOpts.ModuleCachePath, Record);
1545 AddString(HSOpts.ModuleUserBuildPath, Record);
1546 Record.push_back(HSOpts.DisableModuleHash);
1547 Record.push_back(HSOpts.UseBuiltinIncludes);
1548 Record.push_back(HSOpts.UseStandardSystemIncludes);
1549 Record.push_back(HSOpts.UseStandardCXXIncludes);
1550 Record.push_back(HSOpts.UseLibcxx);
1551 // Write out the specific module cache path that contains the module files.
1552 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1553 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1555 // Preprocessor options.
1557 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1559 // Macro definitions.
1560 Record.push_back(PPOpts.Macros.size());
1561 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1562 AddString(PPOpts.Macros[I].first, Record);
1563 Record.push_back(PPOpts.Macros[I].second);
1567 Record.push_back(PPOpts.Includes.size());
1568 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1569 AddString(PPOpts.Includes[I], Record);
1572 Record.push_back(PPOpts.MacroIncludes.size());
1573 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1574 AddString(PPOpts.MacroIncludes[I], Record);
1576 Record.push_back(PPOpts.UsePredefines);
1577 // Detailed record is important since it is used for the module cache hash.
1578 Record.push_back(PPOpts.DetailedRecord);
1579 AddString(PPOpts.ImplicitPCHInclude, Record);
1580 AddString(PPOpts.ImplicitPTHInclude, Record);
1581 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1582 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1584 // Leave the options block.
1587 // Original file name and file ID
1588 SourceManager &SM = Context.getSourceManager();
1589 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1590 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1591 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1592 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1593 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1594 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1597 Record.push_back(ORIGINAL_FILE);
1598 Record.push_back(SM.getMainFileID().getOpaqueValue());
1599 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1603 Record.push_back(SM.getMainFileID().getOpaqueValue());
1604 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1606 // Original PCH directory
1607 if (!OutputFile.empty() && OutputFile != "-") {
1608 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1609 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1611 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1613 SmallString<128> OutputPath(OutputFile);
1615 SM.getFileManager().makeAbsolutePath(OutputPath);
1616 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1618 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1619 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1622 WriteInputFiles(Context.SourceMgr,
1623 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1624 PP.getLangOpts().Modules);
1631 /// \brief An input file.
1632 struct InputFileEntry {
1633 const FileEntry *File;
1636 bool BufferOverridden;
1639 } // end anonymous namespace
1641 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1642 HeaderSearchOptions &HSOpts,
1644 using namespace llvm;
1645 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1647 // Create input-file abbreviation.
1648 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1649 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1650 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1651 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1652 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1653 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1654 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1655 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1656 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1658 // Get all ContentCache objects for files, sorted by whether the file is a
1659 // system one or not. System files go at the back, users files at the front.
1660 std::deque<InputFileEntry> SortedFiles;
1661 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1662 // Get this source location entry.
1663 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1664 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1666 // We only care about file entries that were not overridden.
1667 if (!SLoc->isFile())
1669 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1670 if (!Cache->OrigEntry)
1673 InputFileEntry Entry;
1674 Entry.File = Cache->OrigEntry;
1675 Entry.IsSystemFile = Cache->IsSystemFile;
1676 Entry.IsTransient = Cache->IsTransient;
1677 Entry.BufferOverridden = Cache->BufferOverridden;
1678 if (Cache->IsSystemFile)
1679 SortedFiles.push_back(Entry);
1681 SortedFiles.push_front(Entry);
1684 unsigned UserFilesNum = 0;
1685 // Write out all of the input files.
1686 std::vector<uint64_t> InputFileOffsets;
1687 for (const auto &Entry : SortedFiles) {
1688 uint32_t &InputFileID = InputFileIDs[Entry.File];
1689 if (InputFileID != 0)
1690 continue; // already recorded this file.
1692 // Record this entry's offset.
1693 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1695 InputFileID = InputFileOffsets.size();
1697 if (!Entry.IsSystemFile)
1700 // Emit size/modification time for this file.
1701 // And whether this file was overridden.
1702 RecordData::value_type Record[] = {
1704 InputFileOffsets.size(),
1705 (uint64_t)Entry.File->getSize(),
1706 (uint64_t)getTimestampForOutput(Entry.File),
1707 Entry.BufferOverridden,
1710 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1715 // Create input file offsets abbreviation.
1716 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1717 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1718 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1719 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1721 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1722 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1724 // Write input file offsets.
1725 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1726 InputFileOffsets.size(), UserFilesNum};
1727 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1730 //===----------------------------------------------------------------------===//
1731 // Source Manager Serialization
1732 //===----------------------------------------------------------------------===//
1734 /// \brief Create an abbreviation for the SLocEntry that refers to a
1736 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1737 using namespace llvm;
1739 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1740 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1744 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1745 // FileEntry fields.
1746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1750 return Stream.EmitAbbrev(std::move(Abbrev));
1753 /// \brief Create an abbreviation for the SLocEntry that refers to a
1755 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1756 using namespace llvm;
1758 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1759 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1765 return Stream.EmitAbbrev(std::move(Abbrev));
1768 /// \brief Create an abbreviation for the SLocEntry that refers to a
1770 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1772 using namespace llvm;
1774 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1775 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1776 : SM_SLOC_BUFFER_BLOB));
1778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1780 return Stream.EmitAbbrev(std::move(Abbrev));
1783 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1785 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1786 using namespace llvm;
1788 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1789 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1790 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1791 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1792 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1793 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1795 return Stream.EmitAbbrev(std::move(Abbrev));
1800 // Trait used for the on-disk hash table of header search information.
1801 class HeaderFileInfoTrait {
1803 const HeaderSearch &HS;
1805 // Keep track of the framework names we've used during serialization.
1806 SmallVector<char, 128> FrameworkStringData;
1807 llvm::StringMap<unsigned> FrameworkNameOffset;
1810 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1811 : Writer(Writer), HS(HS) { }
1814 const FileEntry *FE;
1817 typedef const key_type &key_type_ref;
1819 typedef HeaderFileInfo data_type;
1820 typedef const data_type &data_type_ref;
1821 typedef unsigned hash_value_type;
1822 typedef unsigned offset_type;
1824 hash_value_type ComputeHash(key_type_ref key) {
1825 // The hash is based only on size/time of the file, so that the reader can
1826 // match even when symlinking or excess path elements ("foo/../", "../")
1827 // change the form of the name. However, complete path is still the key.
1828 return llvm::hash_combine(key.FE->getSize(),
1829 Writer.getTimestampForOutput(key.FE));
1832 std::pair<unsigned,unsigned>
1833 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1834 using namespace llvm::support;
1835 endian::Writer<little> LE(Out);
1836 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1837 LE.write<uint16_t>(KeyLen);
1838 unsigned DataLen = 1 + 2 + 4 + 4;
1839 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1840 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1842 LE.write<uint8_t>(DataLen);
1843 return std::make_pair(KeyLen, DataLen);
1846 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1847 using namespace llvm::support;
1848 endian::Writer<little> LE(Out);
1849 LE.write<uint64_t>(key.FE->getSize());
1851 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
1853 Out.write(key.Filename.data(), KeyLen);
1856 void EmitData(raw_ostream &Out, key_type_ref key,
1857 data_type_ref Data, unsigned DataLen) {
1858 using namespace llvm::support;
1859 endian::Writer<little> LE(Out);
1860 uint64_t Start = Out.tell(); (void)Start;
1862 unsigned char Flags = (Data.isImport << 4)
1863 | (Data.isPragmaOnce << 3)
1864 | (Data.DirInfo << 1)
1865 | Data.IndexHeaderMapHeader;
1866 LE.write<uint8_t>(Flags);
1867 LE.write<uint16_t>(Data.NumIncludes);
1869 if (!Data.ControllingMacro)
1870 LE.write<uint32_t>(Data.ControllingMacroID);
1872 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1874 unsigned Offset = 0;
1875 if (!Data.Framework.empty()) {
1876 // If this header refers into a framework, save the framework name.
1877 llvm::StringMap<unsigned>::iterator Pos
1878 = FrameworkNameOffset.find(Data.Framework);
1879 if (Pos == FrameworkNameOffset.end()) {
1880 Offset = FrameworkStringData.size() + 1;
1881 FrameworkStringData.append(Data.Framework.begin(),
1882 Data.Framework.end());
1883 FrameworkStringData.push_back(0);
1885 FrameworkNameOffset[Data.Framework] = Offset;
1887 Offset = Pos->second;
1889 LE.write<uint32_t>(Offset);
1891 // FIXME: If the header is excluded, we should write out some
1892 // record of that fact.
1893 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1894 if (uint32_t ModID =
1895 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1896 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1897 assert((Value >> 2) == ModID && "overflow in header module info");
1898 LE.write<uint32_t>(Value);
1902 assert(Out.tell() - Start == DataLen && "Wrong data length");
1905 const char *strings_begin() const { return FrameworkStringData.begin(); }
1906 const char *strings_end() const { return FrameworkStringData.end(); }
1909 } // end anonymous namespace
1911 /// \brief Write the header search block for the list of files that
1913 /// \param HS The header search structure to save.
1914 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1915 SmallVector<const FileEntry *, 16> FilesByUID;
1916 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1918 if (FilesByUID.size() > HS.header_file_size())
1919 FilesByUID.resize(HS.header_file_size());
1921 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1922 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1923 SmallVector<const char *, 4> SavedStrings;
1924 unsigned NumHeaderSearchEntries = 0;
1925 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1926 const FileEntry *File = FilesByUID[UID];
1930 // Get the file info. This will load info from the external source if
1931 // necessary. Skip emitting this file if we have no information on it
1932 // as a header file (in which case HFI will be null) or if it hasn't
1933 // changed since it was loaded. Also skip it if it's for a modular header
1934 // from a different module; in that case, we rely on the module(s)
1935 // containing the header to provide this information.
1936 const HeaderFileInfo *HFI =
1937 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1938 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1941 // Massage the file path into an appropriate form.
1942 StringRef Filename = File->getName();
1943 SmallString<128> FilenameTmp(Filename);
1944 if (PreparePathForOutput(FilenameTmp)) {
1945 // If we performed any translation on the file name at all, we need to
1946 // save this string, since the generator will refer to it later.
1947 Filename = StringRef(strdup(FilenameTmp.c_str()));
1948 SavedStrings.push_back(Filename.data());
1951 HeaderFileInfoTrait::key_type key = { File, Filename };
1952 Generator.insert(key, *HFI, GeneratorTrait);
1953 ++NumHeaderSearchEntries;
1956 // Create the on-disk hash table in a buffer.
1957 SmallString<4096> TableData;
1958 uint32_t BucketOffset;
1960 using namespace llvm::support;
1961 llvm::raw_svector_ostream Out(TableData);
1962 // Make sure that no bucket is at offset 0
1963 endian::Writer<little>(Out).write<uint32_t>(0);
1964 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1967 // Create a blob abbreviation
1968 using namespace llvm;
1970 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1971 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1972 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1973 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1974 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1975 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1976 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1978 // Write the header search table
1979 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1980 NumHeaderSearchEntries, TableData.size()};
1981 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1982 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1984 // Free all of the strings we had to duplicate.
1985 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1986 free(const_cast<char *>(SavedStrings[I]));
1989 /// \brief Writes the block containing the serialized form of the
1992 /// TODO: We should probably use an on-disk hash table (stored in a
1993 /// blob), indexed based on the file name, so that we only create
1994 /// entries for files that we actually need. In the common case (no
1995 /// errors), we probably won't have to create file entries for any of
1996 /// the files in the AST.
1997 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1998 const Preprocessor &PP) {
2001 // Enter the source manager block.
2002 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2004 // Abbreviations for the various kinds of source-location entries.
2005 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2006 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2007 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2008 unsigned SLocBufferBlobCompressedAbbrv =
2009 CreateSLocBufferBlobAbbrev(Stream, true);
2010 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2012 // Write out the source location entry table. We skip the first
2013 // entry, which is always the same dummy entry.
2014 std::vector<uint32_t> SLocEntryOffsets;
2015 RecordData PreloadSLocs;
2016 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2017 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2019 // Get this source location entry.
2020 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2021 FileID FID = FileID::get(I);
2022 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2024 // Record the offset of this source-location entry.
2025 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2027 // Figure out which record code to use.
2029 if (SLoc->isFile()) {
2030 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2031 if (Cache->OrigEntry) {
2032 Code = SM_SLOC_FILE_ENTRY;
2034 Code = SM_SLOC_BUFFER_ENTRY;
2036 Code = SM_SLOC_EXPANSION_ENTRY;
2038 Record.push_back(Code);
2040 // Starting offset of this entry within this module, so skip the dummy.
2041 Record.push_back(SLoc->getOffset() - 2);
2042 if (SLoc->isFile()) {
2043 const SrcMgr::FileInfo &File = SLoc->getFile();
2044 AddSourceLocation(File.getIncludeLoc(), Record);
2045 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2046 Record.push_back(File.hasLineDirectives());
2048 const SrcMgr::ContentCache *Content = File.getContentCache();
2049 bool EmitBlob = false;
2050 if (Content->OrigEntry) {
2051 assert(Content->OrigEntry == Content->ContentsEntry &&
2052 "Writing to AST an overridden file is not supported");
2054 // The source location entry is a file. Emit input file ID.
2055 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2056 Record.push_back(InputFileIDs[Content->OrigEntry]);
2058 Record.push_back(File.NumCreatedFIDs);
2060 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2061 if (FDI != FileDeclIDs.end()) {
2062 Record.push_back(FDI->second->FirstDeclIndex);
2063 Record.push_back(FDI->second->DeclIDs.size());
2065 Record.push_back(0);
2066 Record.push_back(0);
2069 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2071 if (Content->BufferOverridden || Content->IsTransient)
2074 // The source location entry is a buffer. The blob associated
2075 // with this entry contains the contents of the buffer.
2077 // We add one to the size so that we capture the trailing NULL
2078 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2079 // the reader side).
2080 const llvm::MemoryBuffer *Buffer
2081 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2082 StringRef Name = Buffer->getBufferIdentifier();
2083 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2084 StringRef(Name.data(), Name.size() + 1));
2087 if (Name == "<built-in>")
2088 PreloadSLocs.push_back(SLocEntryOffsets.size());
2092 // Include the implicit terminating null character in the on-disk buffer
2093 // if we're writing it uncompressed.
2094 const llvm::MemoryBuffer *Buffer =
2095 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2096 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2098 // Compress the buffer if possible. We expect that almost all PCM
2099 // consumers will not want its contents.
2100 SmallString<0> CompressedBuffer;
2101 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2102 llvm::zlib::StatusOK) {
2103 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2105 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2108 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2109 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2113 // The source location entry is a macro expansion.
2114 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2115 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2116 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2117 AddSourceLocation(Expansion.isMacroArgExpansion()
2119 : Expansion.getExpansionLocEnd(),
2122 // Compute the token length for this macro expansion.
2123 unsigned NextOffset = SourceMgr.getNextLocalOffset();
2125 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2126 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2127 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2133 if (SLocEntryOffsets.empty())
2136 // Write the source-location offsets table into the AST block. This
2137 // table is used for lazily loading source-location information.
2138 using namespace llvm;
2140 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2141 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2142 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2143 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2144 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2145 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2147 RecordData::value_type Record[] = {
2148 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2149 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2150 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2151 bytes(SLocEntryOffsets));
2153 // Write the source location entry preloads array, telling the AST
2154 // reader which source locations entries it should load eagerly.
2155 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2157 // Write the line table. It depends on remapping working, so it must come
2158 // after the source location offsets.
2159 if (SourceMgr.hasLineTable()) {
2160 LineTableInfo &LineTable = SourceMgr.getLineTable();
2164 // Emit the needed file names.
2165 llvm::DenseMap<int, int> FilenameMap;
2166 for (const auto &L : LineTable) {
2169 for (auto &LE : L.second) {
2170 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2171 FilenameMap.size())).second)
2172 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2175 Record.push_back(0);
2177 // Emit the line entries
2178 for (const auto &L : LineTable) {
2179 // Only emit entries for local files.
2184 Record.push_back(L.first.ID);
2186 // Emit the line entries
2187 Record.push_back(L.second.size());
2188 for (const auto &LE : L.second) {
2189 Record.push_back(LE.FileOffset);
2190 Record.push_back(LE.LineNo);
2191 Record.push_back(FilenameMap[LE.FilenameID]);
2192 Record.push_back((unsigned)LE.FileKind);
2193 Record.push_back(LE.IncludeOffset);
2197 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2201 //===----------------------------------------------------------------------===//
2202 // Preprocessor Serialization
2203 //===----------------------------------------------------------------------===//
2205 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2206 const Preprocessor &PP) {
2207 if (MacroInfo *MI = MD->getMacroInfo())
2208 if (MI->isBuiltinMacro())
2212 SourceLocation Loc = MD->getLocation();
2213 if (Loc.isInvalid())
2215 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2222 /// \brief Writes the block containing the serialized form of the
2225 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2226 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2228 WritePreprocessorDetail(*PPRec);
2231 RecordData ModuleMacroRecord;
2233 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2234 if (PP.getCounterValue() != 0) {
2235 RecordData::value_type Record[] = {PP.getCounterValue()};
2236 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2239 // Enter the preprocessor block.
2240 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2242 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2243 // FIXME: Include a location for the use, and say which one was used.
2244 if (PP.SawDateOrTime())
2245 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2247 // Loop over all the macro directives that are live at the end of the file,
2248 // emitting each to the PP section.
2250 // Construct the list of identifiers with macro directives that need to be
2252 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2253 for (auto &Id : PP.getIdentifierTable())
2254 if (Id.second->hadMacroDefinition() &&
2255 (!Id.second->isFromAST() ||
2256 Id.second->hasChangedSinceDeserialization()))
2257 MacroIdentifiers.push_back(Id.second);
2258 // Sort the set of macro definitions that need to be serialized by the
2259 // name of the macro, to provide a stable ordering.
2260 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2261 llvm::less_ptr<IdentifierInfo>());
2263 // Emit the macro directives as a list and associate the offset with the
2264 // identifier they belong to.
2265 for (const IdentifierInfo *Name : MacroIdentifiers) {
2266 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2267 auto StartOffset = Stream.GetCurrentBitNo();
2269 // Emit the macro directives in reverse source order.
2270 for (; MD; MD = MD->getPrevious()) {
2271 // Once we hit an ignored macro, we're done: the rest of the chain
2272 // will all be ignored macros.
2273 if (shouldIgnoreMacro(MD, IsModule, PP))
2276 AddSourceLocation(MD->getLocation(), Record);
2277 Record.push_back(MD->getKind());
2278 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2279 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2280 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2281 Record.push_back(VisMD->isPublic());
2285 // Write out any exported module macros.
2286 bool EmittedModuleMacros = false;
2287 // We write out exported module macros for PCH as well.
2288 auto Leafs = PP.getLeafModuleMacros(Name);
2289 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2290 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2291 while (!Worklist.empty()) {
2292 auto *Macro = Worklist.pop_back_val();
2294 // Emit a record indicating this submodule exports this macro.
2295 ModuleMacroRecord.push_back(
2296 getSubmoduleID(Macro->getOwningModule()));
2297 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2298 for (auto *M : Macro->overrides())
2299 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2301 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2302 ModuleMacroRecord.clear();
2304 // Enqueue overridden macros once we've visited all their ancestors.
2305 for (auto *M : Macro->overrides())
2306 if (++Visits[M] == M->getNumOverridingMacros())
2307 Worklist.push_back(M);
2309 EmittedModuleMacros = true;
2312 if (Record.empty() && !EmittedModuleMacros)
2315 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2316 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2320 /// \brief Offsets of each of the macros into the bitstream, indexed by
2321 /// the local macro ID
2323 /// For each identifier that is associated with a macro, this map
2324 /// provides the offset into the bitstream where that macro is
2326 std::vector<uint32_t> MacroOffsets;
2328 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2329 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2330 MacroInfo *MI = MacroInfosToEmit[I].MI;
2331 MacroID ID = MacroInfosToEmit[I].ID;
2333 if (ID < FirstMacroID) {
2334 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2338 // Record the local offset of this macro.
2339 unsigned Index = ID - FirstMacroID;
2340 if (Index == MacroOffsets.size())
2341 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2343 if (Index > MacroOffsets.size())
2344 MacroOffsets.resize(Index + 1);
2346 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2349 AddIdentifierRef(Name, Record);
2350 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2351 AddSourceLocation(MI->getDefinitionLoc(), Record);
2352 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2353 Record.push_back(MI->isUsed());
2354 Record.push_back(MI->isUsedForHeaderGuard());
2356 if (MI->isObjectLike()) {
2357 Code = PP_MACRO_OBJECT_LIKE;
2359 Code = PP_MACRO_FUNCTION_LIKE;
2361 Record.push_back(MI->isC99Varargs());
2362 Record.push_back(MI->isGNUVarargs());
2363 Record.push_back(MI->hasCommaPasting());
2364 Record.push_back(MI->getNumArgs());
2365 for (const IdentifierInfo *Arg : MI->args())
2366 AddIdentifierRef(Arg, Record);
2369 // If we have a detailed preprocessing record, record the macro definition
2370 // ID that corresponds to this macro.
2372 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2374 Stream.EmitRecord(Code, Record);
2377 // Emit the tokens array.
2378 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2379 // Note that we know that the preprocessor does not have any annotation
2380 // tokens in it because they are created by the parser, and thus can't
2381 // be in a macro definition.
2382 const Token &Tok = MI->getReplacementToken(TokNo);
2383 AddToken(Tok, Record);
2384 Stream.EmitRecord(PP_TOKEN, Record);
2392 // Write the offsets table for macro IDs.
2393 using namespace llvm;
2395 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2396 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2397 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2401 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2403 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2404 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2405 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2409 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2410 if (PPRec.local_begin() == PPRec.local_end())
2413 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2415 // Enter the preprocessor block.
2416 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2418 // If the preprocessor has a preprocessing record, emit it.
2419 unsigned NumPreprocessingRecords = 0;
2420 using namespace llvm;
2422 // Set up the abbreviation for
2423 unsigned InclusionAbbrev = 0;
2425 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2426 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2432 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2435 unsigned FirstPreprocessorEntityID
2436 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2437 + NUM_PREDEF_PP_ENTITY_IDS;
2438 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2440 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2441 EEnd = PPRec.local_end();
2443 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2446 PreprocessedEntityOffsets.push_back(
2447 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2449 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2450 // Record this macro definition's ID.
2451 MacroDefinitions[MD] = NextPreprocessorEntityID;
2453 AddIdentifierRef(MD->getName(), Record);
2454 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2458 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2459 Record.push_back(ME->isBuiltinMacro());
2460 if (ME->isBuiltinMacro())
2461 AddIdentifierRef(ME->getName(), Record);
2463 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2464 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2468 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2469 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2470 Record.push_back(ID->getFileName().size());
2471 Record.push_back(ID->wasInQuotes());
2472 Record.push_back(static_cast<unsigned>(ID->getKind()));
2473 Record.push_back(ID->importedModule());
2474 SmallString<64> Buffer;
2475 Buffer += ID->getFileName();
2476 // Check that the FileEntry is not null because it was not resolved and
2477 // we create a PCH even with compiler errors.
2479 Buffer += ID->getFile()->getName();
2480 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2484 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2488 // Write the offsets table for the preprocessing record.
2489 if (NumPreprocessingRecords > 0) {
2490 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2492 // Write the offsets table for identifier IDs.
2493 using namespace llvm;
2495 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2496 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2499 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2501 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2502 FirstPreprocessorEntityID -
2503 NUM_PREDEF_PP_ENTITY_IDS};
2504 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2505 bytes(PreprocessedEntityOffsets));
2509 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2513 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2514 if (Known != SubmoduleIDs.end())
2515 return Known->second;
2517 auto *Top = Mod->getTopLevelModule();
2518 if (Top != WritingModule &&
2519 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule)))
2522 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2525 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2526 // FIXME: This can easily happen, if we have a reference to a submodule that
2527 // did not result in us loading a module file for that submodule. For
2528 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2529 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2530 assert((ID || !Mod) &&
2531 "asked for module ID for non-local, non-imported module");
2535 /// \brief Compute the number of modules within the given tree (including the
2537 static unsigned getNumberOfModules(Module *Mod) {
2538 unsigned ChildModules = 0;
2539 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2540 Sub != SubEnd; ++Sub)
2541 ChildModules += getNumberOfModules(*Sub);
2543 return ChildModules + 1;
2546 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2547 // Enter the submodule description block.
2548 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2550 // Write the abbreviations needed for the submodules block.
2551 using namespace llvm;
2553 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2554 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2560 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2566 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2568 Abbrev = std::make_shared<BitCodeAbbrev>();
2569 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2571 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2573 Abbrev = std::make_shared<BitCodeAbbrev>();
2574 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2576 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2578 Abbrev = std::make_shared<BitCodeAbbrev>();
2579 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2580 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2581 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2583 Abbrev = std::make_shared<BitCodeAbbrev>();
2584 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2585 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2586 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2588 Abbrev = std::make_shared<BitCodeAbbrev>();
2589 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2590 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2591 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2592 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2594 Abbrev = std::make_shared<BitCodeAbbrev>();
2595 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2596 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2597 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2599 Abbrev = std::make_shared<BitCodeAbbrev>();
2600 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2602 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2604 Abbrev = std::make_shared<BitCodeAbbrev>();
2605 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2607 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2609 Abbrev = std::make_shared<BitCodeAbbrev>();
2610 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2611 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2612 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2614 Abbrev = std::make_shared<BitCodeAbbrev>();
2615 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2617 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2618 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2620 Abbrev = std::make_shared<BitCodeAbbrev>();
2621 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2622 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2623 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2625 Abbrev = std::make_shared<BitCodeAbbrev>();
2626 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2628 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2629 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2631 // Write the submodule metadata block.
2632 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2634 NUM_PREDEF_SUBMODULE_IDS};
2635 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2637 // Write all of the submodules.
2638 std::queue<Module *> Q;
2639 Q.push(WritingModule);
2640 while (!Q.empty()) {
2641 Module *Mod = Q.front();
2643 unsigned ID = getSubmoduleID(Mod);
2645 uint64_t ParentID = 0;
2647 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2648 ParentID = SubmoduleIDs[Mod->Parent];
2651 // Emit the definition of the block.
2653 RecordData::value_type Record[] = {
2654 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2655 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2656 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2657 Mod->ConfigMacrosExhaustive};
2658 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2661 // Emit the requirements.
2662 for (const auto &R : Mod->Requirements) {
2663 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2664 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2667 // Emit the umbrella header, if there is one.
2668 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2669 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2670 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2671 UmbrellaHeader.NameAsWritten);
2672 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2673 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2674 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2675 UmbrellaDir.NameAsWritten);
2678 // Emit the headers.
2680 unsigned RecordKind;
2682 Module::HeaderKind HeaderKind;
2684 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2685 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2686 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2687 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2688 Module::HK_PrivateTextual},
2689 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2691 for (auto &HL : HeaderLists) {
2692 RecordData::value_type Record[] = {HL.RecordKind};
2693 for (auto &H : Mod->Headers[HL.HeaderKind])
2694 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2697 // Emit the top headers.
2699 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2700 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2701 for (auto *H : TopHeaders)
2702 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2705 // Emit the imports.
2706 if (!Mod->Imports.empty()) {
2708 for (auto *I : Mod->Imports)
2709 Record.push_back(getSubmoduleID(I));
2710 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2713 // Emit the exports.
2714 if (!Mod->Exports.empty()) {
2716 for (const auto &E : Mod->Exports) {
2717 // FIXME: This may fail; we don't require that all exported modules
2718 // are local or imported.
2719 Record.push_back(getSubmoduleID(E.getPointer()));
2720 Record.push_back(E.getInt());
2722 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2725 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2726 // Might be unnecessary as use declarations are only used to build the
2729 // Emit the link libraries.
2730 for (const auto &LL : Mod->LinkLibraries) {
2731 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2733 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2736 // Emit the conflicts.
2737 for (const auto &C : Mod->Conflicts) {
2738 // FIXME: This may fail; we don't require that all conflicting modules
2739 // are local or imported.
2740 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2741 getSubmoduleID(C.Other)};
2742 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2745 // Emit the configuration macros.
2746 for (const auto &CM : Mod->ConfigMacros) {
2747 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2748 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2751 // Emit the initializers, if any.
2753 for (Decl *D : Context->getModuleInitializers(Mod))
2754 Inits.push_back(GetDeclRef(D));
2756 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2758 // Queue up the submodules of this module.
2759 for (auto *M : Mod->submodules())
2765 assert((NextSubmoduleID - FirstSubmoduleID ==
2766 getNumberOfModules(WritingModule)) &&
2767 "Wrong # of submodules; found a reference to a non-local, "
2768 "non-imported submodule?");
2771 serialization::SubmoduleID
2772 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2773 if (Loc.isInvalid() || !WritingModule)
2774 return 0; // No submodule
2776 // Find the module that owns this location.
2777 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2779 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2783 // Check whether this submodule is part of our own module.
2784 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2787 return getSubmoduleID(OwningMod);
2790 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2792 // Make sure set diagnostic pragmas don't affect the translation unit that
2793 // imports the module.
2794 // FIXME: Make diagnostic pragma sections work properly with modules.
2798 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2800 unsigned CurrID = 0;
2801 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2803 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2804 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2806 const DiagnosticsEngine::DiagStatePoint &point = *I;
2807 if (point.Loc.isInvalid())
2810 AddSourceLocation(point.Loc, Record);
2811 unsigned &DiagStateID = DiagStateIDMap[point.State];
2812 Record.push_back(DiagStateID);
2814 if (DiagStateID == 0) {
2815 DiagStateID = ++CurrID;
2816 for (const auto &I : *(point.State)) {
2817 if (I.second.isPragma()) {
2818 Record.push_back(I.first);
2819 Record.push_back((unsigned)I.second.getSeverity());
2822 Record.push_back(-1); // mark the end of the diag/map pairs for this
2827 if (!Record.empty())
2828 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2831 //===----------------------------------------------------------------------===//
2832 // Type Serialization
2833 //===----------------------------------------------------------------------===//
2835 /// \brief Write the representation of a type to the AST stream.
2836 void ASTWriter::WriteType(QualType T) {
2837 TypeIdx &IdxRef = TypeIdxs[T];
2838 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2839 IdxRef = TypeIdx(NextTypeID++);
2840 TypeIdx Idx = IdxRef;
2842 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2846 // Emit the type's representation.
2847 ASTTypeWriter W(*this, Record);
2849 uint64_t Offset = W.Emit();
2851 // Record the offset for this type.
2852 unsigned Index = Idx.getIndex() - FirstTypeID;
2853 if (TypeOffsets.size() == Index)
2854 TypeOffsets.push_back(Offset);
2855 else if (TypeOffsets.size() < Index) {
2856 TypeOffsets.resize(Index + 1);
2857 TypeOffsets[Index] = Offset;
2859 llvm_unreachable("Types emitted in wrong order");
2863 //===----------------------------------------------------------------------===//
2864 // Declaration Serialization
2865 //===----------------------------------------------------------------------===//
2867 /// \brief Write the block containing all of the declaration IDs
2868 /// lexically declared within the given DeclContext.
2870 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2871 /// bistream, or 0 if no block was written.
2872 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2874 if (DC->decls_empty())
2877 uint64_t Offset = Stream.GetCurrentBitNo();
2878 SmallVector<uint32_t, 128> KindDeclPairs;
2879 for (const auto *D : DC->decls()) {
2880 KindDeclPairs.push_back(D->getKind());
2881 KindDeclPairs.push_back(GetDeclRef(D));
2884 ++NumLexicalDeclContexts;
2885 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
2886 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2887 bytes(KindDeclPairs));
2891 void ASTWriter::WriteTypeDeclOffsets() {
2892 using namespace llvm;
2894 // Write the type offsets array
2895 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2896 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2899 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2900 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2902 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2903 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2904 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2907 // Write the declaration offsets array
2908 Abbrev = std::make_shared<BitCodeAbbrev>();
2909 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2910 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2911 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2912 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2913 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2915 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2916 FirstDeclID - NUM_PREDEF_DECL_IDS};
2917 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2921 void ASTWriter::WriteFileDeclIDsMap() {
2922 using namespace llvm;
2924 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2925 FileDeclIDs.begin(), FileDeclIDs.end());
2926 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2927 llvm::less_first());
2929 // Join the vectors of DeclIDs from all files.
2930 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2931 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2932 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2933 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2934 for (auto &LocDeclEntry : Info.DeclIDs)
2935 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2938 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2939 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2940 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2941 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2942 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
2943 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2944 FileGroupedDeclIDs.size()};
2945 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2948 void ASTWriter::WriteComments() {
2949 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2950 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2952 for (const auto *I : RawComments) {
2954 AddSourceRange(I->getSourceRange(), Record);
2955 Record.push_back(I->getKind());
2956 Record.push_back(I->isTrailingComment());
2957 Record.push_back(I->isAlmostTrailingComment());
2958 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2963 //===----------------------------------------------------------------------===//
2964 // Global Method Pool and Selector Serialization
2965 //===----------------------------------------------------------------------===//
2969 // Trait used for the on-disk hash table used in the method pool.
2970 class ASTMethodPoolTrait {
2974 typedef Selector key_type;
2975 typedef key_type key_type_ref;
2979 ObjCMethodList Instance, Factory;
2981 typedef const data_type& data_type_ref;
2983 typedef unsigned hash_value_type;
2984 typedef unsigned offset_type;
2986 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2988 static hash_value_type ComputeHash(Selector Sel) {
2989 return serialization::ComputeHash(Sel);
2992 std::pair<unsigned,unsigned>
2993 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2994 data_type_ref Methods) {
2995 using namespace llvm::support;
2996 endian::Writer<little> LE(Out);
2997 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2998 LE.write<uint16_t>(KeyLen);
2999 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3000 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3001 Method = Method->getNext())
3002 if (Method->getMethod())
3004 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3005 Method = Method->getNext())
3006 if (Method->getMethod())
3008 LE.write<uint16_t>(DataLen);
3009 return std::make_pair(KeyLen, DataLen);
3012 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3013 using namespace llvm::support;
3014 endian::Writer<little> LE(Out);
3015 uint64_t Start = Out.tell();
3016 assert((Start >> 32) == 0 && "Selector key offset too large");
3017 Writer.SetSelectorOffset(Sel, Start);
3018 unsigned N = Sel.getNumArgs();
3019 LE.write<uint16_t>(N);
3022 for (unsigned I = 0; I != N; ++I)
3024 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3027 void EmitData(raw_ostream& Out, key_type_ref,
3028 data_type_ref Methods, unsigned DataLen) {
3029 using namespace llvm::support;
3030 endian::Writer<little> LE(Out);
3031 uint64_t Start = Out.tell(); (void)Start;
3032 LE.write<uint32_t>(Methods.ID);
3033 unsigned NumInstanceMethods = 0;
3034 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3035 Method = Method->getNext())
3036 if (Method->getMethod())
3037 ++NumInstanceMethods;
3039 unsigned NumFactoryMethods = 0;
3040 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3041 Method = Method->getNext())
3042 if (Method->getMethod())
3043 ++NumFactoryMethods;
3045 unsigned InstanceBits = Methods.Instance.getBits();
3046 assert(InstanceBits < 4);
3047 unsigned InstanceHasMoreThanOneDeclBit =
3048 Methods.Instance.hasMoreThanOneDecl();
3049 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3050 (InstanceHasMoreThanOneDeclBit << 2) |
3052 unsigned FactoryBits = Methods.Factory.getBits();
3053 assert(FactoryBits < 4);
3054 unsigned FactoryHasMoreThanOneDeclBit =
3055 Methods.Factory.hasMoreThanOneDecl();
3056 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3057 (FactoryHasMoreThanOneDeclBit << 2) |
3059 LE.write<uint16_t>(FullInstanceBits);
3060 LE.write<uint16_t>(FullFactoryBits);
3061 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3062 Method = Method->getNext())
3063 if (Method->getMethod())
3064 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3065 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3066 Method = Method->getNext())
3067 if (Method->getMethod())
3068 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3070 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3074 } // end anonymous namespace
3076 /// \brief Write ObjC data: selectors and the method pool.
3078 /// The method pool contains both instance and factory methods, stored
3079 /// in an on-disk hash table indexed by the selector. The hash table also
3080 /// contains an empty entry for every other selector known to Sema.
3081 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3082 using namespace llvm;
3084 // Do we have to do anything at all?
3085 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3087 unsigned NumTableEntries = 0;
3088 // Create and write out the blob that contains selectors and the method pool.
3090 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3091 ASTMethodPoolTrait Trait(*this);
3093 // Create the on-disk hash table representation. We walk through every
3094 // selector we've seen and look it up in the method pool.
3095 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3096 for (auto &SelectorAndID : SelectorIDs) {
3097 Selector S = SelectorAndID.first;
3098 SelectorID ID = SelectorAndID.second;
3099 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3100 ASTMethodPoolTrait::data_type Data = {
3105 if (F != SemaRef.MethodPool.end()) {
3106 Data.Instance = F->second.first;
3107 Data.Factory = F->second.second;
3109 // Only write this selector if it's not in an existing AST or something
3111 if (Chain && ID < FirstSelectorID) {
3112 // Selector already exists. Did it change?
3113 bool changed = false;
3114 for (ObjCMethodList *M = &Data.Instance;
3115 !changed && M && M->getMethod(); M = M->getNext()) {
3116 if (!M->getMethod()->isFromASTFile())
3119 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3121 if (!M->getMethod()->isFromASTFile())
3126 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3127 // A new method pool entry.
3130 Generator.insert(S, Data, Trait);
3133 // Create the on-disk hash table in a buffer.
3134 SmallString<4096> MethodPool;
3135 uint32_t BucketOffset;
3137 using namespace llvm::support;
3138 ASTMethodPoolTrait Trait(*this);
3139 llvm::raw_svector_ostream Out(MethodPool);
3140 // Make sure that no bucket is at offset 0
3141 endian::Writer<little>(Out).write<uint32_t>(0);
3142 BucketOffset = Generator.Emit(Out, Trait);
3145 // Create a blob abbreviation
3146 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3147 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3148 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3149 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3150 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3151 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3153 // Write the method pool
3155 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3157 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3160 // Create a blob abbreviation for the selector table offsets.
3161 Abbrev = std::make_shared<BitCodeAbbrev>();
3162 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3166 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3168 // Write the selector offsets table.
3170 RecordData::value_type Record[] = {
3171 SELECTOR_OFFSETS, SelectorOffsets.size(),
3172 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3173 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3174 bytes(SelectorOffsets));
3179 /// \brief Write the selectors referenced in @selector expression into AST file.
3180 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3181 using namespace llvm;
3182 if (SemaRef.ReferencedSelectors.empty())
3186 ASTRecordWriter Writer(*this, Record);
3188 // Note: this writes out all references even for a dependent AST. But it is
3189 // very tricky to fix, and given that @selector shouldn't really appear in
3190 // headers, probably not worth it. It's not a correctness issue.
3191 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3192 Selector Sel = SelectorAndLocation.first;
3193 SourceLocation Loc = SelectorAndLocation.second;
3194 Writer.AddSelectorRef(Sel);
3195 Writer.AddSourceLocation(Loc);
3197 Writer.Emit(REFERENCED_SELECTOR_POOL);
3200 //===----------------------------------------------------------------------===//
3201 // Identifier Table Serialization
3202 //===----------------------------------------------------------------------===//
3204 /// Determine the declaration that should be put into the name lookup table to
3205 /// represent the given declaration in this module. This is usually D itself,
3206 /// but if D was imported and merged into a local declaration, we want the most
3207 /// recent local declaration instead. The chosen declaration will be the most
3208 /// recent declaration in any module that imports this one.
3209 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3211 if (!LangOpts.Modules || !D->isFromASTFile())
3214 if (Decl *Redecl = D->getPreviousDecl()) {
3215 // For Redeclarable decls, a prior declaration might be local.
3216 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3217 // If we find a local decl, we're done.
3218 if (!Redecl->isFromASTFile()) {
3219 // Exception: in very rare cases (for injected-class-names), not all
3220 // redeclarations are in the same semantic context. Skip ones in a
3221 // different context. They don't go in this lookup table at all.
3222 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3223 D->getDeclContext()->getRedeclContext()))
3225 return cast<NamedDecl>(Redecl);
3228 // If we find a decl from a (chained-)PCH stop since we won't find a
3230 if (Redecl->getOwningModuleID() == 0)
3233 } else if (Decl *First = D->getCanonicalDecl()) {
3234 // For Mergeable decls, the first decl might be local.
3235 if (!First->isFromASTFile())
3236 return cast<NamedDecl>(First);
3239 // All declarations are imported. Our most recent declaration will also be
3240 // the most recent one in anyone who imports us.
3246 class ASTIdentifierTableTrait {
3249 IdentifierResolver &IdResolver;
3252 ASTWriter::RecordData *InterestingIdentifierOffsets;
3254 /// \brief Determines whether this is an "interesting" identifier that needs a
3255 /// full IdentifierInfo structure written into the hash table. Notably, this
3256 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3258 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3261 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3262 II->hasRevertedTokenIDToIdentifier() ||
3263 (NeedDecls && II->getFETokenInfo<void>()))
3270 typedef IdentifierInfo* key_type;
3271 typedef key_type key_type_ref;
3273 typedef IdentID data_type;
3274 typedef data_type data_type_ref;
3276 typedef unsigned hash_value_type;
3277 typedef unsigned offset_type;
3279 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3280 IdentifierResolver &IdResolver, bool IsModule,
3281 ASTWriter::RecordData *InterestingIdentifierOffsets)
3282 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3283 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3284 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3286 bool needDecls() const { return NeedDecls; }
3288 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3289 return llvm::HashString(II->getName());
3292 bool isInterestingIdentifier(const IdentifierInfo *II) {
3293 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3294 return isInterestingIdentifier(II, MacroOffset);
3297 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3298 return isInterestingIdentifier(II, 0);
3301 std::pair<unsigned,unsigned>
3302 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3303 unsigned KeyLen = II->getLength() + 1;
3304 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3305 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3306 if (isInterestingIdentifier(II, MacroOffset)) {
3307 DataLen += 2; // 2 bytes for builtin ID
3308 DataLen += 2; // 2 bytes for flags
3310 DataLen += 4; // MacroDirectives offset.
3313 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3314 DEnd = IdResolver.end();
3319 using namespace llvm::support;
3320 endian::Writer<little> LE(Out);
3322 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3323 LE.write<uint16_t>(DataLen);
3324 // We emit the key length after the data length so that every
3325 // string is preceded by a 16-bit length. This matches the PTH
3326 // format for storing identifiers.
3327 LE.write<uint16_t>(KeyLen);
3328 return std::make_pair(KeyLen, DataLen);
3331 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3333 // Record the location of the key data. This is used when generating
3334 // the mapping from persistent IDs to strings.
3335 Writer.SetIdentifierOffset(II, Out.tell());
3337 // Emit the offset of the key/data length information to the interesting
3338 // identifiers table if necessary.
3339 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3340 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3342 Out.write(II->getNameStart(), KeyLen);
3345 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3346 IdentID ID, unsigned) {
3347 using namespace llvm::support;
3348 endian::Writer<little> LE(Out);
3350 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3351 if (!isInterestingIdentifier(II, MacroOffset)) {
3352 LE.write<uint32_t>(ID << 1);
3356 LE.write<uint32_t>((ID << 1) | 0x01);
3357 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3358 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3359 LE.write<uint16_t>(Bits);
3361 bool HadMacroDefinition = MacroOffset != 0;
3362 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3363 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3364 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3365 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3366 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3367 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3368 LE.write<uint16_t>(Bits);
3370 if (HadMacroDefinition)
3371 LE.write<uint32_t>(MacroOffset);
3374 // Emit the declaration IDs in reverse order, because the
3375 // IdentifierResolver provides the declarations as they would be
3376 // visible (e.g., the function "stat" would come before the struct
3377 // "stat"), but the ASTReader adds declarations to the end of the list
3378 // (so we need to see the struct "stat" before the function "stat").
3379 // Only emit declarations that aren't from a chained PCH, though.
3380 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3382 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3383 DEnd = Decls.rend();
3386 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3391 } // end anonymous namespace
3393 /// \brief Write the identifier table into the AST file.
3395 /// The identifier table consists of a blob containing string data
3396 /// (the actual identifiers themselves) and a separate "offsets" index
3397 /// that maps identifier IDs to locations within the blob.
3398 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3399 IdentifierResolver &IdResolver,
3401 using namespace llvm;
3403 RecordData InterestingIdents;
3405 // Create and write out the blob that contains the identifier
3408 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3409 ASTIdentifierTableTrait Trait(
3410 *this, PP, IdResolver, IsModule,
3411 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3413 // Look for any identifiers that were named while processing the
3414 // headers, but are otherwise not needed. We add these to the hash
3415 // table to enable checking of the predefines buffer in the case
3416 // where the user adds new macro definitions when building the AST
3418 SmallVector<const IdentifierInfo *, 128> IIs;
3419 for (const auto &ID : PP.getIdentifierTable())
3420 IIs.push_back(ID.second);
3421 // Sort the identifiers lexicographically before getting them references so
3422 // that their order is stable.
3423 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3424 for (const IdentifierInfo *II : IIs)
3425 if (Trait.isInterestingNonMacroIdentifier(II))
3426 getIdentifierRef(II);
3428 // Create the on-disk hash table representation. We only store offsets
3429 // for identifiers that appear here for the first time.
3430 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3431 for (auto IdentIDPair : IdentifierIDs) {
3432 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3433 IdentID ID = IdentIDPair.second;
3434 assert(II && "NULL identifier in identifier table");
3435 // Write out identifiers if either the ID is local or the identifier has
3436 // changed since it was loaded.
3437 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3438 || II->hasChangedSinceDeserialization() ||
3439 (Trait.needDecls() &&
3440 II->hasFETokenInfoChangedSinceDeserialization()))
3441 Generator.insert(II, ID, Trait);
3444 // Create the on-disk hash table in a buffer.
3445 SmallString<4096> IdentifierTable;
3446 uint32_t BucketOffset;
3448 using namespace llvm::support;
3449 llvm::raw_svector_ostream Out(IdentifierTable);
3450 // Make sure that no bucket is at offset 0
3451 endian::Writer<little>(Out).write<uint32_t>(0);
3452 BucketOffset = Generator.Emit(Out, Trait);
3455 // Create a blob abbreviation
3456 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3457 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3460 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3462 // Write the identifier table
3463 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3464 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3467 // Write the offsets table for identifier IDs.
3468 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3469 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3470 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3472 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3473 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3476 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3477 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3480 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3481 IdentifierOffsets.size(),
3482 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3483 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3484 bytes(IdentifierOffsets));
3486 // In C++, write the list of interesting identifiers (those that are
3487 // defined as macros, poisoned, or similar unusual things).
3488 if (!InterestingIdents.empty())
3489 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3492 //===----------------------------------------------------------------------===//
3493 // DeclContext's Name Lookup Table Serialization
3494 //===----------------------------------------------------------------------===//
3498 // Trait used for the on-disk hash table used in the method pool.
3499 class ASTDeclContextNameLookupTrait {
3501 llvm::SmallVector<DeclID, 64> DeclIDs;
3504 typedef DeclarationNameKey key_type;
3505 typedef key_type key_type_ref;
3507 /// A start and end index into DeclIDs, representing a sequence of decls.
3508 typedef std::pair<unsigned, unsigned> data_type;
3509 typedef const data_type& data_type_ref;
3511 typedef unsigned hash_value_type;
3512 typedef unsigned offset_type;
3514 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3516 template<typename Coll>
3517 data_type getData(const Coll &Decls) {
3518 unsigned Start = DeclIDs.size();
3519 for (NamedDecl *D : Decls) {
3521 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3523 return std::make_pair(Start, DeclIDs.size());
3526 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3527 unsigned Start = DeclIDs.size();
3528 for (auto ID : FromReader)
3529 DeclIDs.push_back(ID);
3530 return std::make_pair(Start, DeclIDs.size());
3533 static bool EqualKey(key_type_ref a, key_type_ref b) {
3537 hash_value_type ComputeHash(DeclarationNameKey Name) {
3538 return Name.getHash();
3541 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3542 assert(Writer.hasChain() &&
3543 "have reference to loaded module file but no chain?");
3545 using namespace llvm::support;
3546 endian::Writer<little>(Out)
3547 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3550 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3551 DeclarationNameKey Name,
3552 data_type_ref Lookup) {
3553 using namespace llvm::support;
3554 endian::Writer<little> LE(Out);
3555 unsigned KeyLen = 1;
3556 switch (Name.getKind()) {
3557 case DeclarationName::Identifier:
3558 case DeclarationName::ObjCZeroArgSelector:
3559 case DeclarationName::ObjCOneArgSelector:
3560 case DeclarationName::ObjCMultiArgSelector:
3561 case DeclarationName::CXXLiteralOperatorName:
3564 case DeclarationName::CXXOperatorName:
3567 case DeclarationName::CXXConstructorName:
3568 case DeclarationName::CXXDestructorName:
3569 case DeclarationName::CXXConversionFunctionName:
3570 case DeclarationName::CXXUsingDirective:
3573 LE.write<uint16_t>(KeyLen);
3575 // 4 bytes for each DeclID.
3576 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3577 assert(uint16_t(DataLen) == DataLen &&
3578 "too many decls for serialized lookup result");
3579 LE.write<uint16_t>(DataLen);
3581 return std::make_pair(KeyLen, DataLen);
3584 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3585 using namespace llvm::support;
3586 endian::Writer<little> LE(Out);
3587 LE.write<uint8_t>(Name.getKind());
3588 switch (Name.getKind()) {
3589 case DeclarationName::Identifier:
3590 case DeclarationName::CXXLiteralOperatorName:
3591 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3593 case DeclarationName::ObjCZeroArgSelector:
3594 case DeclarationName::ObjCOneArgSelector:
3595 case DeclarationName::ObjCMultiArgSelector:
3596 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3598 case DeclarationName::CXXOperatorName:
3599 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3600 "Invalid operator?");
3601 LE.write<uint8_t>(Name.getOperatorKind());
3603 case DeclarationName::CXXConstructorName:
3604 case DeclarationName::CXXDestructorName:
3605 case DeclarationName::CXXConversionFunctionName:
3606 case DeclarationName::CXXUsingDirective:
3610 llvm_unreachable("Invalid name kind?");
3613 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3615 using namespace llvm::support;
3616 endian::Writer<little> LE(Out);
3617 uint64_t Start = Out.tell(); (void)Start;
3618 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3619 LE.write<uint32_t>(DeclIDs[I]);
3620 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3624 } // end anonymous namespace
3626 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3628 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3631 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3633 for (auto *D : Result.getLookupResult())
3634 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3641 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3642 llvm::SmallVectorImpl<char> &LookupTable) {
3643 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3644 !ConstDC->HasLazyExternalLexicalLookups &&
3645 "must call buildLookups first");
3647 // FIXME: We need to build the lookups table, which is logically const.
3648 auto *DC = const_cast<DeclContext*>(ConstDC);
3649 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3651 // Create the on-disk hash table representation.
3652 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3653 ASTDeclContextNameLookupTrait> Generator;
3654 ASTDeclContextNameLookupTrait Trait(*this);
3656 // The first step is to collect the declaration names which we need to
3657 // serialize into the name lookup table, and to collect them in a stable
3659 SmallVector<DeclarationName, 16> Names;
3661 // We also build up small sets of the constructor and conversion function
3662 // names which are visible.
3663 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3665 for (auto &Lookup : *DC->buildLookup()) {
3666 auto &Name = Lookup.first;
3667 auto &Result = Lookup.second;
3669 // If there are no local declarations in our lookup result, we
3670 // don't need to write an entry for the name at all. If we can't
3671 // write out a lookup set without performing more deserialization,
3672 // just skip this entry.
3673 if (isLookupResultExternal(Result, DC) &&
3674 isLookupResultEntirelyExternal(Result, DC))
3677 // We also skip empty results. If any of the results could be external and
3678 // the currently available results are empty, then all of the results are
3679 // external and we skip it above. So the only way we get here with an empty
3680 // results is when no results could have been external *and* we have
3681 // external results.
3683 // FIXME: While we might want to start emitting on-disk entries for negative
3684 // lookups into a decl context as an optimization, today we *have* to skip
3685 // them because there are names with empty lookup results in decl contexts
3686 // which we can't emit in any stable ordering: we lookup constructors and
3687 // conversion functions in the enclosing namespace scope creating empty
3688 // results for them. This in almost certainly a bug in Clang's name lookup,
3689 // but that is likely to be hard or impossible to fix and so we tolerate it
3690 // here by omitting lookups with empty results.
3691 if (Lookup.second.getLookupResult().empty())
3694 switch (Lookup.first.getNameKind()) {
3696 Names.push_back(Lookup.first);
3699 case DeclarationName::CXXConstructorName:
3700 assert(isa<CXXRecordDecl>(DC) &&
3701 "Cannot have a constructor name outside of a class!");
3702 ConstructorNameSet.insert(Name);
3705 case DeclarationName::CXXConversionFunctionName:
3706 assert(isa<CXXRecordDecl>(DC) &&
3707 "Cannot have a conversion function name outside of a class!");
3708 ConversionNameSet.insert(Name);
3713 // Sort the names into a stable order.
3714 std::sort(Names.begin(), Names.end());
3716 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3717 // We need to establish an ordering of constructor and conversion function
3718 // names, and they don't have an intrinsic ordering.
3720 // First we try the easy case by forming the current context's constructor
3721 // name and adding that name first. This is a very useful optimization to
3722 // avoid walking the lexical declarations in many cases, and it also
3723 // handles the only case where a constructor name can come from some other
3724 // lexical context -- when that name is an implicit constructor merged from
3725 // another declaration in the redecl chain. Any non-implicit constructor or
3726 // conversion function which doesn't occur in all the lexical contexts
3727 // would be an ODR violation.
3728 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3729 Context->getCanonicalType(Context->getRecordType(D)));
3730 if (ConstructorNameSet.erase(ImplicitCtorName))
3731 Names.push_back(ImplicitCtorName);
3733 // If we still have constructors or conversion functions, we walk all the
3734 // names in the decl and add the constructors and conversion functions
3735 // which are visible in the order they lexically occur within the context.
3736 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3737 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3738 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3739 auto Name = ChildND->getDeclName();
3740 switch (Name.getNameKind()) {
3744 case DeclarationName::CXXConstructorName:
3745 if (ConstructorNameSet.erase(Name))
3746 Names.push_back(Name);
3749 case DeclarationName::CXXConversionFunctionName:
3750 if (ConversionNameSet.erase(Name))
3751 Names.push_back(Name);
3755 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3759 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3760 "constructors by walking all the "
3761 "lexical members of the context.");
3762 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3763 "conversion functions by walking all "
3764 "the lexical members of the context.");
3767 // Next we need to do a lookup with each name into this decl context to fully
3768 // populate any results from external sources. We don't actually use the
3769 // results of these lookups because we only want to use the results after all
3770 // results have been loaded and the pointers into them will be stable.
3771 for (auto &Name : Names)
3774 // Now we need to insert the results for each name into the hash table. For
3775 // constructor names and conversion function names, we actually need to merge
3776 // all of the results for them into one list of results each and insert
3778 SmallVector<NamedDecl *, 8> ConstructorDecls;
3779 SmallVector<NamedDecl *, 8> ConversionDecls;
3781 // Now loop over the names, either inserting them or appending for the two
3783 for (auto &Name : Names) {
3784 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3786 switch (Name.getNameKind()) {
3788 Generator.insert(Name, Trait.getData(Result), Trait);
3791 case DeclarationName::CXXConstructorName:
3792 ConstructorDecls.append(Result.begin(), Result.end());
3795 case DeclarationName::CXXConversionFunctionName:
3796 ConversionDecls.append(Result.begin(), Result.end());
3801 // Handle our two special cases if we ended up having any. We arbitrarily use
3802 // the first declaration's name here because the name itself isn't part of
3803 // the key, only the kind of name is used.
3804 if (!ConstructorDecls.empty())
3805 Generator.insert(ConstructorDecls.front()->getDeclName(),
3806 Trait.getData(ConstructorDecls), Trait);
3807 if (!ConversionDecls.empty())
3808 Generator.insert(ConversionDecls.front()->getDeclName(),
3809 Trait.getData(ConversionDecls), Trait);
3811 // Create the on-disk hash table. Also emit the existing imported and
3812 // merged table if there is one.
3813 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3814 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3817 /// \brief Write the block containing all of the declaration IDs
3818 /// visible from the given DeclContext.
3820 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3821 /// bitstream, or 0 if no block was written.
3822 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3824 // If we imported a key declaration of this namespace, write the visible
3825 // lookup results as an update record for it rather than including them
3826 // on this declaration. We will only look at key declarations on reload.
3827 if (isa<NamespaceDecl>(DC) && Chain &&
3828 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3829 // Only do this once, for the first local declaration of the namespace.
3830 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3831 Prev = Prev->getPreviousDecl())
3832 if (!Prev->isFromASTFile())
3835 // Note that we need to emit an update record for the primary context.
3836 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3838 // Make sure all visible decls are written. They will be recorded later. We
3839 // do this using a side data structure so we can sort the names into
3840 // a deterministic order.
3841 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3842 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3845 LookupResults.reserve(Map->size());
3846 for (auto &Entry : *Map)
3847 LookupResults.push_back(
3848 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3851 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3852 for (auto &NameAndResult : LookupResults) {
3853 DeclarationName Name = NameAndResult.first;
3854 DeclContext::lookup_result Result = NameAndResult.second;
3855 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3856 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3857 // We have to work around a name lookup bug here where negative lookup
3858 // results for these names get cached in namespace lookup tables (these
3859 // names should never be looked up in a namespace).
3860 assert(Result.empty() && "Cannot have a constructor or conversion "
3861 "function name in a namespace!");
3865 for (NamedDecl *ND : Result)
3866 if (!ND->isFromASTFile())
3873 if (DC->getPrimaryContext() != DC)
3876 // Skip contexts which don't support name lookup.
3877 if (!DC->isLookupContext())
3880 // If not in C++, we perform name lookup for the translation unit via the
3881 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3882 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3885 // Serialize the contents of the mapping used for lookup. Note that,
3886 // although we have two very different code paths, the serialized
3887 // representation is the same for both cases: a declaration name,
3888 // followed by a size, followed by references to the visible
3889 // declarations that have that name.
3890 uint64_t Offset = Stream.GetCurrentBitNo();
3891 StoredDeclsMap *Map = DC->buildLookup();
3892 if (!Map || Map->empty())
3895 // Create the on-disk hash table in a buffer.
3896 SmallString<4096> LookupTable;
3897 GenerateNameLookupTable(DC, LookupTable);
3899 // Write the lookup table
3900 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3901 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3903 ++NumVisibleDeclContexts;
3907 /// \brief Write an UPDATE_VISIBLE block for the given context.
3909 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3910 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3911 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3912 /// enumeration members (in C++11).
3913 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3914 StoredDeclsMap *Map = DC->getLookupPtr();
3915 if (!Map || Map->empty())
3918 // Create the on-disk hash table in a buffer.
3919 SmallString<4096> LookupTable;
3920 GenerateNameLookupTable(DC, LookupTable);
3922 // If we're updating a namespace, select a key declaration as the key for the
3923 // update record; those are the only ones that will be checked on reload.
3924 if (isa<NamespaceDecl>(DC))
3925 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3927 // Write the lookup table
3928 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3929 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3932 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3933 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3934 RecordData::value_type Record[] = {Opts.fp_contract};
3935 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3938 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3939 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3940 if (!SemaRef.Context.getLangOpts().OpenCL)
3943 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3945 for (const auto &I:Opts.OptMap) {
3946 AddString(I.getKey(), Record);
3947 auto V = I.getValue();
3948 Record.push_back(V.Supported ? 1 : 0);
3949 Record.push_back(V.Enabled ? 1 : 0);
3950 Record.push_back(V.Avail);
3951 Record.push_back(V.Core);
3953 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3956 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3957 if (!SemaRef.Context.getLangOpts().OpenCL)
3961 for (const auto &I : SemaRef.OpenCLTypeExtMap) {
3963 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
3964 Record.push_back(I.second.size());
3965 for (auto Ext : I.second)
3966 AddString(Ext, Record);
3968 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3971 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3972 if (!SemaRef.Context.getLangOpts().OpenCL)
3976 for (const auto &I : SemaRef.OpenCLDeclExtMap) {
3977 Record.push_back(getDeclID(I.first));
3978 Record.push_back(static_cast<unsigned>(I.second.size()));
3979 for (auto Ext : I.second)
3980 AddString(Ext, Record);
3982 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
3985 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3986 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3987 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3988 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
3992 void ASTWriter::WriteObjCCategories() {
3993 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3994 RecordData Categories;
3996 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3998 unsigned StartIndex = Categories.size();
4000 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4002 // Allocate space for the size.
4003 Categories.push_back(0);
4005 // Add the categories.
4006 for (ObjCInterfaceDecl::known_categories_iterator
4007 Cat = Class->known_categories_begin(),
4008 CatEnd = Class->known_categories_end();
4009 Cat != CatEnd; ++Cat, ++Size) {
4010 assert(getDeclID(*Cat) != 0 && "Bogus category");
4011 AddDeclRef(*Cat, Categories);
4015 Categories[StartIndex] = Size;
4017 // Record this interface -> category map.
4018 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4019 CategoriesMap.push_back(CatInfo);
4022 // Sort the categories map by the definition ID, since the reader will be
4023 // performing binary searches on this information.
4024 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4026 // Emit the categories map.
4027 using namespace llvm;
4029 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4030 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4031 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4032 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4033 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4035 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4036 Stream.EmitRecordWithBlob(AbbrevID, Record,
4037 reinterpret_cast<char *>(CategoriesMap.data()),
4038 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4040 // Emit the category lists.
4041 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4044 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4045 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4051 for (auto &LPTMapEntry : LPTMap) {
4052 const FunctionDecl *FD = LPTMapEntry.first;
4053 LateParsedTemplate &LPT = *LPTMapEntry.second;
4054 AddDeclRef(FD, Record);
4055 AddDeclRef(LPT.D, Record);
4056 Record.push_back(LPT.Toks.size());
4058 for (const auto &Tok : LPT.Toks) {
4059 AddToken(Tok, Record);
4062 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4065 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4066 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4068 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4069 AddSourceLocation(PragmaLoc, Record);
4070 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4073 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
4074 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4076 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4077 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4080 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
4082 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4084 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4085 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4086 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4089 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4090 ModuleFileExtensionWriter &Writer) {
4091 // Enter the extension block.
4092 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4094 // Emit the metadata record abbreviation.
4095 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4096 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
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::VBR, 6));
4101 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4102 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4104 // Emit the metadata record.
4106 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4107 Record.push_back(EXTENSION_METADATA);
4108 Record.push_back(Metadata.MajorVersion);
4109 Record.push_back(Metadata.MinorVersion);
4110 Record.push_back(Metadata.BlockName.size());
4111 Record.push_back(Metadata.UserInfo.size());
4112 SmallString<64> Buffer;
4113 Buffer += Metadata.BlockName;
4114 Buffer += Metadata.UserInfo;
4115 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4117 // Emit the contents of the extension block.
4118 Writer.writeExtensionContents(SemaRef, Stream);
4120 // Exit the extension block.
4124 //===----------------------------------------------------------------------===//
4125 // General Serialization Routines
4126 //===----------------------------------------------------------------------===//
4128 /// \brief Emit the list of attributes to the specified record.
4129 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4130 auto &Record = *this;
4131 Record.push_back(Attrs.size());
4132 for (const auto *A : Attrs) {
4133 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4134 Record.AddSourceRange(A->getRange());
4136 #include "clang/Serialization/AttrPCHWrite.inc"
4141 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4142 AddSourceLocation(Tok.getLocation(), Record);
4143 Record.push_back(Tok.getLength());
4145 // FIXME: When reading literal tokens, reconstruct the literal pointer
4147 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4148 // FIXME: Should translate token kind to a stable encoding.
4149 Record.push_back(Tok.getKind());
4150 // FIXME: Should translate token flags to a stable encoding.
4151 Record.push_back(Tok.getFlags());
4154 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4155 Record.push_back(Str.size());
4156 Record.insert(Record.end(), Str.begin(), Str.end());
4159 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4160 assert(Context && "should have context when outputting path");
4163 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4165 // Remove a prefix to make the path relative, if relevant.
4166 const char *PathBegin = Path.data();
4167 const char *PathPtr =
4168 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4169 if (PathPtr != PathBegin) {
4170 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4177 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4178 SmallString<128> FilePath(Path);
4179 PreparePathForOutput(FilePath);
4180 AddString(FilePath, Record);
4183 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4185 SmallString<128> FilePath(Path);
4186 PreparePathForOutput(FilePath);
4187 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4190 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4191 RecordDataImpl &Record) {
4192 Record.push_back(Version.getMajor());
4193 if (Optional<unsigned> Minor = Version.getMinor())
4194 Record.push_back(*Minor + 1);
4196 Record.push_back(0);
4197 if (Optional<unsigned> Subminor = Version.getSubminor())
4198 Record.push_back(*Subminor + 1);
4200 Record.push_back(0);
4203 /// \brief Note that the identifier II occurs at the given offset
4204 /// within the identifier table.
4205 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4206 IdentID ID = IdentifierIDs[II];
4207 // Only store offsets new to this AST file. Other identifier names are looked
4208 // up earlier in the chain and thus don't need an offset.
4209 if (ID >= FirstIdentID)
4210 IdentifierOffsets[ID - FirstIdentID] = Offset;
4213 /// \brief Note that the selector Sel occurs at the given offset
4214 /// within the method pool/selector table.
4215 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4216 unsigned ID = SelectorIDs[Sel];
4217 assert(ID && "Unknown selector");
4218 // Don't record offsets for selectors that are also available in a different
4220 if (ID < FirstSelectorID)
4222 SelectorOffsets[ID - FirstSelectorID] = Offset;
4225 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4226 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4227 bool IncludeTimestamps)
4228 : Stream(Stream), IncludeTimestamps(IncludeTimestamps) {
4229 for (const auto &Ext : Extensions) {
4230 if (auto Writer = Ext->createExtensionWriter(*this))
4231 ModuleFileExtensionWriters.push_back(std::move(Writer));
4235 ASTWriter::~ASTWriter() {
4236 llvm::DeleteContainerSeconds(FileDeclIDs);
4239 const LangOptions &ASTWriter::getLangOpts() const {
4240 assert(WritingAST && "can't determine lang opts when not writing AST");
4241 return Context->getLangOpts();
4244 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4245 return IncludeTimestamps ? E->getModificationTime() : 0;
4248 uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4249 Module *WritingModule, StringRef isysroot,
4253 ASTHasCompilerErrors = hasErrors;
4255 // Emit the file header.
4256 Stream.Emit((unsigned)'C', 8);
4257 Stream.Emit((unsigned)'P', 8);
4258 Stream.Emit((unsigned)'C', 8);
4259 Stream.Emit((unsigned)'H', 8);
4261 WriteBlockInfoBlock();
4263 Context = &SemaRef.Context;
4265 this->WritingModule = WritingModule;
4266 ASTFileSignature Signature =
4267 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4270 this->WritingModule = nullptr;
4271 this->BaseDirectory.clear();
4277 template<typename Vector>
4278 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4279 ASTWriter::RecordData &Record) {
4280 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4282 Writer.AddDeclRef(*I, Record);
4286 uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4287 const std::string &OutputFile,
4288 Module *WritingModule) {
4289 using namespace llvm;
4291 bool isModule = WritingModule != nullptr;
4293 // Make sure that the AST reader knows to finalize itself.
4295 Chain->finalizeForWriting();
4297 ASTContext &Context = SemaRef.Context;
4298 Preprocessor &PP = SemaRef.PP;
4300 // Set up predefined declaration IDs.
4301 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4303 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4307 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4308 PREDEF_DECL_TRANSLATION_UNIT_ID);
4309 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4310 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4311 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4312 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4313 PREDEF_DECL_OBJC_PROTOCOL_ID);
4314 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4315 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4316 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4317 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4318 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4319 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4320 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4321 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4322 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4323 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4324 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4325 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4326 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4327 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4328 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4329 RegisterPredefDecl(Context.TypePackElementDecl,
4330 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4332 // Build a record containing all of the tentative definitions in this file, in
4333 // TentativeDefinitions order. Generally, this record will be empty for
4335 RecordData TentativeDefinitions;
4336 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4338 // Build a record containing all of the file scoped decls in this file.
4339 RecordData UnusedFileScopedDecls;
4341 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4342 UnusedFileScopedDecls);
4344 // Build a record containing all of the delegating constructors we still need
4346 RecordData DelegatingCtorDecls;
4348 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4350 // Write the set of weak, undeclared identifiers. We always write the
4351 // entire table, since later PCH files in a PCH chain are only interested in
4352 // the results at the end of the chain.
4353 RecordData WeakUndeclaredIdentifiers;
4354 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4355 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4356 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4357 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4358 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4359 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4360 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4363 // Build a record containing all of the ext_vector declarations.
4364 RecordData ExtVectorDecls;
4365 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4367 // Build a record containing all of the VTable uses information.
4368 RecordData VTableUses;
4369 if (!SemaRef.VTableUses.empty()) {
4370 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4371 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4372 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4373 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4377 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4378 RecordData UnusedLocalTypedefNameCandidates;
4379 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4380 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4382 // Build a record containing all of pending implicit instantiations.
4383 RecordData PendingInstantiations;
4384 for (const auto &I : SemaRef.PendingInstantiations) {
4385 AddDeclRef(I.first, PendingInstantiations);
4386 AddSourceLocation(I.second, PendingInstantiations);
4388 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4389 "There are local ones at end of translation unit!");
4391 // Build a record containing some declaration references.
4392 RecordData SemaDeclRefs;
4393 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4394 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4395 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4396 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4399 RecordData CUDASpecialDeclRefs;
4400 if (Context.getcudaConfigureCallDecl()) {
4401 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4404 // Build a record containing all of the known namespaces.
4405 RecordData KnownNamespaces;
4406 for (const auto &I : SemaRef.KnownNamespaces) {
4408 AddDeclRef(I.first, KnownNamespaces);
4411 // Build a record of all used, undefined objects that require definitions.
4412 RecordData UndefinedButUsed;
4414 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4415 SemaRef.getUndefinedButUsed(Undefined);
4416 for (const auto &I : Undefined) {
4417 AddDeclRef(I.first, UndefinedButUsed);
4418 AddSourceLocation(I.second, UndefinedButUsed);
4421 // Build a record containing all delete-expressions that we would like to
4422 // analyze later in AST.
4423 RecordData DeleteExprsToAnalyze;
4425 for (const auto &DeleteExprsInfo :
4426 SemaRef.getMismatchingDeleteExpressions()) {
4427 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4428 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4429 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4430 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4431 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4435 // Write the control block
4436 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
4438 // Write the remaining AST contents.
4439 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4441 // This is so that older clang versions, before the introduction
4442 // of the control block, can read and reject the newer PCH format.
4444 RecordData Record = {VERSION_MAJOR};
4445 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4448 // Create a lexical update block containing all of the declarations in the
4449 // translation unit that do not come from other AST files.
4450 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4451 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4452 for (const auto *D : TU->noload_decls()) {
4453 if (!D->isFromASTFile()) {
4454 NewGlobalKindDeclPairs.push_back(D->getKind());
4455 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4459 auto Abv = std::make_shared<BitCodeAbbrev>();
4460 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4461 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4462 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4464 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4465 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4466 bytes(NewGlobalKindDeclPairs));
4469 // And a visible updates block for the translation unit.
4470 Abv = std::make_shared<BitCodeAbbrev>();
4471 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4472 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4473 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4474 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4475 WriteDeclContextVisibleUpdate(TU);
4477 // If we have any extern "C" names, write out a visible update for them.
4478 if (Context.ExternCContext)
4479 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4481 // If the translation unit has an anonymous namespace, and we don't already
4482 // have an update block for it, write it as an update block.
4483 // FIXME: Why do we not do this if there's already an update block?
4484 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4485 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4487 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4490 // Add update records for all mangling numbers and static local numbers.
4491 // These aren't really update records, but this is a convenient way of
4492 // tagging this rare extra data onto the declarations.
4493 for (const auto &Number : Context.MangleNumbers)
4494 if (!Number.first->isFromASTFile())
4495 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4497 for (const auto &Number : Context.StaticLocalNumbers)
4498 if (!Number.first->isFromASTFile())
4499 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4502 // Make sure visible decls, added to DeclContexts previously loaded from
4503 // an AST file, are registered for serialization. Likewise for template
4504 // specializations added to imported templates.
4505 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4509 // Make sure all decls associated with an identifier are registered for
4510 // serialization, if we're storing decls with identifiers.
4511 if (!WritingModule || !getLangOpts().CPlusPlus) {
4512 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4513 for (const auto &ID : PP.getIdentifierTable()) {
4514 const IdentifierInfo *II = ID.second;
4515 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4518 // Sort the identifiers to visit based on their name.
4519 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4520 for (const IdentifierInfo *II : IIs) {
4521 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4522 DEnd = SemaRef.IdResolver.end();
4529 // For method pool in the module, if it contains an entry for a selector,
4530 // the entry should be complete, containing everything introduced by that
4531 // module and all modules it imports. It's possible that the entry is out of
4532 // date, so we need to pull in the new content here.
4534 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4535 // safe, we copy all selectors out.
4536 llvm::SmallVector<Selector, 256> AllSelectors;
4537 for (auto &SelectorAndID : SelectorIDs)
4538 AllSelectors.push_back(SelectorAndID.first);
4539 for (auto &Selector : AllSelectors)
4540 SemaRef.updateOutOfDateSelector(Selector);
4542 // Form the record of special types.
4543 RecordData SpecialTypes;
4544 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4545 AddTypeRef(Context.getFILEType(), SpecialTypes);
4546 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4547 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4548 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4549 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4550 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4551 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4554 // Write the mapping information describing our module dependencies and how
4555 // each of those modules were mapped into our own offset/ID space, so that
4556 // the reader can build the appropriate mapping to its own offset/ID space.
4557 // The map consists solely of a blob with the following format:
4558 // *(module-name-len:i16 module-name:len*i8
4559 // source-location-offset:i32
4560 // identifier-id:i32
4561 // preprocessed-entity-id:i32
4562 // macro-definition-id:i32
4565 // declaration-id:i32
4566 // c++-base-specifiers-id:i32
4569 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4570 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4572 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4573 SmallString<2048> Buffer;
4575 llvm::raw_svector_ostream Out(Buffer);
4576 for (ModuleFile *M : Chain->ModuleMgr) {
4577 using namespace llvm::support;
4578 endian::Writer<little> LE(Out);
4579 StringRef FileName = M->FileName;
4580 LE.write<uint16_t>(FileName.size());
4581 Out.write(FileName.data(), FileName.size());
4583 // Note: if a base ID was uint max, it would not be possible to load
4584 // another module after it or have more than one entity inside it.
4585 uint32_t None = std::numeric_limits<uint32_t>::max();
4587 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4588 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4590 LE.write<uint32_t>(BaseID);
4592 LE.write<uint32_t>(None);
4595 // These values should be unique within a chain, since they will be read
4596 // as keys into ContinuousRangeMaps.
4597 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4598 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4599 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4600 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4601 M->NumPreprocessedEntities);
4602 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4603 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4604 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4605 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4608 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4609 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4610 Buffer.data(), Buffer.size());
4613 RecordData DeclUpdatesOffsetsRecord;
4615 // Keep writing types, declarations, and declaration update records
4616 // until we've emitted all of them.
4617 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4621 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4622 while (!DeclTypesToEmit.empty()) {
4623 DeclOrType DOT = DeclTypesToEmit.front();
4624 DeclTypesToEmit.pop();
4626 WriteType(DOT.getType());
4628 WriteDecl(Context, DOT.getDecl());
4630 } while (!DeclUpdates.empty());
4633 DoneWritingDeclsAndTypes = true;
4635 // These things can only be done once we've written out decls and types.
4636 WriteTypeDeclOffsets();
4637 if (!DeclUpdatesOffsetsRecord.empty())
4638 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4639 WriteFileDeclIDsMap();
4640 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4642 WritePreprocessor(PP, isModule);
4643 WriteHeaderSearch(PP.getHeaderSearchInfo());
4644 WriteSelectors(SemaRef);
4645 WriteReferencedSelectorsPool(SemaRef);
4646 WriteLateParsedTemplates(SemaRef);
4647 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4648 WriteFPPragmaOptions(SemaRef.getFPOptions());
4649 WriteOpenCLExtensions(SemaRef);
4650 WriteOpenCLExtensionTypes(SemaRef);
4651 WriteOpenCLExtensionDecls(SemaRef);
4652 WriteCUDAPragmas(SemaRef);
4653 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4655 // If we're emitting a module, write out the submodule information.
4657 WriteSubmodules(WritingModule);
4659 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4661 // Write the record containing external, unnamed definitions.
4662 if (!EagerlyDeserializedDecls.empty())
4663 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4665 // Write the record containing tentative definitions.
4666 if (!TentativeDefinitions.empty())
4667 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4669 // Write the record containing unused file scoped decls.
4670 if (!UnusedFileScopedDecls.empty())
4671 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4673 // Write the record containing weak undeclared identifiers.
4674 if (!WeakUndeclaredIdentifiers.empty())
4675 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4676 WeakUndeclaredIdentifiers);
4678 // Write the record containing ext_vector type names.
4679 if (!ExtVectorDecls.empty())
4680 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4682 // Write the record containing VTable uses information.
4683 if (!VTableUses.empty())
4684 Stream.EmitRecord(VTABLE_USES, VTableUses);
4686 // Write the record containing potentially unused local typedefs.
4687 if (!UnusedLocalTypedefNameCandidates.empty())
4688 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4689 UnusedLocalTypedefNameCandidates);
4691 // Write the record containing pending implicit instantiations.
4692 if (!PendingInstantiations.empty())
4693 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4695 // Write the record containing declaration references of Sema.
4696 if (!SemaDeclRefs.empty())
4697 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4699 // Write the record containing CUDA-specific declaration references.
4700 if (!CUDASpecialDeclRefs.empty())
4701 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4703 // Write the delegating constructors.
4704 if (!DelegatingCtorDecls.empty())
4705 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4707 // Write the known namespaces.
4708 if (!KnownNamespaces.empty())
4709 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4711 // Write the undefined internal functions and variables, and inline functions.
4712 if (!UndefinedButUsed.empty())
4713 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4715 if (!DeleteExprsToAnalyze.empty())
4716 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4718 // Write the visible updates to DeclContexts.
4719 for (auto *DC : UpdatedDeclContexts)
4720 WriteDeclContextVisibleUpdate(DC);
4722 if (!WritingModule) {
4723 // Write the submodules that were imported, if any.
4727 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4729 llvm::SmallVector<ModuleInfo, 64> Imports;
4730 for (const auto *I : Context.local_imports()) {
4731 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4732 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4733 I->getImportedModule()));
4736 if (!Imports.empty()) {
4737 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4740 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4741 return A.ID == B.ID;
4744 // Sort and deduplicate module IDs.
4745 std::sort(Imports.begin(), Imports.end(), Cmp);
4746 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4749 RecordData ImportedModules;
4750 for (const auto &Import : Imports) {
4751 ImportedModules.push_back(Import.ID);
4752 // FIXME: If the module has macros imported then later has declarations
4753 // imported, this location won't be the right one as a location for the
4754 // declaration imports.
4755 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4758 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4762 WriteObjCCategories();
4763 if(!WritingModule) {
4764 WriteOptimizePragmaOptions(SemaRef);
4765 WriteMSStructPragmaOptions(SemaRef);
4766 WriteMSPointersToMembersPragmaOptions(SemaRef);
4769 // Some simple statistics
4770 RecordData::value_type Record[] = {
4771 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4772 Stream.EmitRecord(STATISTICS, Record);
4775 // Write the module file extension blocks.
4776 for (const auto &ExtWriter : ModuleFileExtensionWriters)
4777 WriteModuleFileExtension(SemaRef, *ExtWriter);
4782 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4783 if (DeclUpdates.empty())
4786 DeclUpdateMap LocalUpdates;
4787 LocalUpdates.swap(DeclUpdates);
4789 for (auto &DeclUpdate : LocalUpdates) {
4790 const Decl *D = DeclUpdate.first;
4792 bool HasUpdatedBody = false;
4793 RecordData RecordData;
4794 ASTRecordWriter Record(*this, RecordData);
4795 for (auto &Update : DeclUpdate.second) {
4796 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4798 // An updated body is emitted last, so that the reader doesn't need
4799 // to skip over the lazy body to reach statements for other records.
4800 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4801 HasUpdatedBody = true;
4803 Record.push_back(Kind);
4806 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4807 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4808 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4809 assert(Update.getDecl() && "no decl to add?");
4810 Record.push_back(GetDeclRef(Update.getDecl()));
4813 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4816 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4817 Record.AddSourceLocation(Update.getLoc());
4820 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4821 Record.AddStmt(const_cast<Expr *>(
4822 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4825 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4827 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4830 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4831 auto *RD = cast<CXXRecordDecl>(D);
4832 UpdatedDeclContexts.insert(RD->getPrimaryContext());
4833 Record.AddCXXDefinitionData(RD);
4834 Record.AddOffset(WriteDeclContextLexicalBlock(
4835 *Context, const_cast<CXXRecordDecl *>(RD)));
4837 // This state is sometimes updated by template instantiation, when we
4838 // switch from the specialization referring to the template declaration
4839 // to it referring to the template definition.
4840 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4841 Record.push_back(MSInfo->getTemplateSpecializationKind());
4842 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4844 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4845 Record.push_back(Spec->getTemplateSpecializationKind());
4846 Record.AddSourceLocation(Spec->getPointOfInstantiation());
4848 // The instantiation might have been resolved to a partial
4849 // specialization. If so, record which one.
4850 auto From = Spec->getInstantiatedFrom();
4851 if (auto PartialSpec =
4852 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4853 Record.push_back(true);
4854 Record.AddDeclRef(PartialSpec);
4855 Record.AddTemplateArgumentList(
4856 &Spec->getTemplateInstantiationArgs());
4858 Record.push_back(false);
4861 Record.push_back(RD->getTagKind());
4862 Record.AddSourceLocation(RD->getLocation());
4863 Record.AddSourceLocation(RD->getLocStart());
4864 Record.AddSourceRange(RD->getBraceRange());
4866 // Instantiation may change attributes; write them all out afresh.
4867 Record.push_back(D->hasAttrs());
4869 Record.AddAttributes(D->getAttrs());
4871 // FIXME: Ensure we don't get here for explicit instantiations.
4875 case UPD_CXX_RESOLVED_DTOR_DELETE:
4876 Record.AddDeclRef(Update.getDecl());
4879 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4881 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4885 case UPD_CXX_DEDUCED_RETURN_TYPE:
4886 Record.push_back(GetOrCreateTypeID(Update.getType()));
4889 case UPD_DECL_MARKED_USED:
4892 case UPD_MANGLING_NUMBER:
4893 case UPD_STATIC_LOCAL_NUMBER:
4894 Record.push_back(Update.getNumber());
4897 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4898 Record.AddSourceRange(
4899 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
4902 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4903 Record.AddSourceRange(
4904 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4907 case UPD_DECL_EXPORTED:
4908 Record.push_back(getSubmoduleID(Update.getModule()));
4911 case UPD_ADDED_ATTR_TO_RECORD:
4912 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
4917 if (HasUpdatedBody) {
4918 const auto *Def = cast<FunctionDecl>(D);
4919 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4920 Record.push_back(Def->isInlined());
4921 Record.AddSourceLocation(Def->getInnerLocStart());
4922 Record.AddFunctionDefinition(Def);
4925 OffsetsRecord.push_back(GetDeclRef(D));
4926 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
4930 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4931 uint32_t Raw = Loc.getRawEncoding();
4932 Record.push_back((Raw << 1) | (Raw >> 31));
4935 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4936 AddSourceLocation(Range.getBegin(), Record);
4937 AddSourceLocation(Range.getEnd(), Record);
4940 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4941 Record->push_back(Value.getBitWidth());
4942 const uint64_t *Words = Value.getRawData();
4943 Record->append(Words, Words + Value.getNumWords());
4946 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4947 Record->push_back(Value.isUnsigned());
4951 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4952 AddAPInt(Value.bitcastToAPInt());
4955 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4956 Record.push_back(getIdentifierRef(II));
4959 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4963 IdentID &ID = IdentifierIDs[II];
4969 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4970 // Don't emit builtin macros like __LINE__ to the AST file unless they
4971 // have been redefined by the header (in which case they are not
4973 if (!MI || MI->isBuiltinMacro())
4976 MacroID &ID = MacroIDs[MI];
4979 MacroInfoToEmitData Info = { Name, MI, ID };
4980 MacroInfosToEmit.push_back(Info);
4985 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4986 if (!MI || MI->isBuiltinMacro())
4989 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4990 return MacroIDs[MI];
4993 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4994 return IdentMacroDirectivesOffsetMap.lookup(Name);
4997 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
4998 Record->push_back(Writer->getSelectorRef(SelRef));
5001 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5002 if (Sel.getAsOpaquePtr() == nullptr) {
5006 SelectorID SID = SelectorIDs[Sel];
5007 if (SID == 0 && Chain) {
5008 // This might trigger a ReadSelector callback, which will set the ID for
5010 Chain->LoadSelector(Sel);
5011 SID = SelectorIDs[Sel];
5014 SID = NextSelectorID++;
5015 SelectorIDs[Sel] = SID;
5020 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5021 AddDeclRef(Temp->getDestructor());
5024 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5025 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5027 case TemplateArgument::Expression:
5028 AddStmt(Arg.getAsExpr());
5030 case TemplateArgument::Type:
5031 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5033 case TemplateArgument::Template:
5034 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5035 AddSourceLocation(Arg.getTemplateNameLoc());
5037 case TemplateArgument::TemplateExpansion:
5038 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5039 AddSourceLocation(Arg.getTemplateNameLoc());
5040 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5042 case TemplateArgument::Null:
5043 case TemplateArgument::Integral:
5044 case TemplateArgument::Declaration:
5045 case TemplateArgument::NullPtr:
5046 case TemplateArgument::Pack:
5047 // FIXME: Is this right?
5052 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5053 AddTemplateArgument(Arg.getArgument());
5055 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5056 bool InfoHasSameExpr
5057 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5058 Record->push_back(InfoHasSameExpr);
5059 if (InfoHasSameExpr)
5060 return; // Avoid storing the same expr twice.
5062 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5065 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5067 AddTypeRef(QualType());
5071 AddTypeLoc(TInfo->getTypeLoc());
5074 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5075 AddTypeRef(TL.getType());
5077 TypeLocWriter TLW(*this);
5078 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5082 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5083 Record.push_back(GetOrCreateTypeID(T));
5086 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5088 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5091 assert(!T.getLocalFastQualifiers());
5093 TypeIdx &Idx = TypeIdxs[T];
5094 if (Idx.getIndex() == 0) {
5095 if (DoneWritingDeclsAndTypes) {
5096 assert(0 && "New type seen after serializing all the types to emit!");
5100 // We haven't seen this type before. Assign it a new ID and put it
5101 // into the queue of types to emit.
5102 Idx = TypeIdx(NextTypeID++);
5103 DeclTypesToEmit.push(T);
5109 TypeID ASTWriter::getTypeID(QualType T) const {
5111 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5114 assert(!T.getLocalFastQualifiers());
5116 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5117 assert(I != TypeIdxs.end() && "Type not emitted!");
5122 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5123 Record.push_back(GetDeclRef(D));
5126 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5127 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5133 // If D comes from an AST file, its declaration ID is already known and
5135 if (D->isFromASTFile())
5136 return D->getGlobalID();
5138 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5139 DeclID &ID = DeclIDs[D];
5141 if (DoneWritingDeclsAndTypes) {
5142 assert(0 && "New decl seen after serializing all the decls to emit!");
5146 // We haven't seen this declaration before. Give it a new ID and
5147 // enqueue it in the list of declarations to emit.
5149 DeclTypesToEmit.push(const_cast<Decl *>(D));
5155 DeclID ASTWriter::getDeclID(const Decl *D) {
5159 // If D comes from an AST file, its declaration ID is already known and
5161 if (D->isFromASTFile())
5162 return D->getGlobalID();
5164 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5168 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5172 SourceLocation Loc = D->getLocation();
5173 if (Loc.isInvalid())
5176 // We only keep track of the file-level declarations of each file.
5177 if (!D->getLexicalDeclContext()->isFileContext())
5179 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5180 // a function/objc method, should not have TU as lexical context.
5181 if (isa<ParmVarDecl>(D))
5184 SourceManager &SM = Context->getSourceManager();
5185 SourceLocation FileLoc = SM.getFileLoc(Loc);
5186 assert(SM.isLocalSourceLocation(FileLoc));
5189 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5190 if (FID.isInvalid())
5192 assert(SM.getSLocEntry(FID).isFile());
5194 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5196 Info = new DeclIDInFileInfo();
5198 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5199 LocDeclIDsTy &Decls = Info->DeclIDs;
5201 if (Decls.empty() || Decls.back().first <= Offset) {
5202 Decls.push_back(LocDecl);
5206 LocDeclIDsTy::iterator I =
5207 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5209 Decls.insert(I, LocDecl);
5212 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5213 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5214 Record->push_back(Name.getNameKind());
5215 switch (Name.getNameKind()) {
5216 case DeclarationName::Identifier:
5217 AddIdentifierRef(Name.getAsIdentifierInfo());
5220 case DeclarationName::ObjCZeroArgSelector:
5221 case DeclarationName::ObjCOneArgSelector:
5222 case DeclarationName::ObjCMultiArgSelector:
5223 AddSelectorRef(Name.getObjCSelector());
5226 case DeclarationName::CXXConstructorName:
5227 case DeclarationName::CXXDestructorName:
5228 case DeclarationName::CXXConversionFunctionName:
5229 AddTypeRef(Name.getCXXNameType());
5232 case DeclarationName::CXXOperatorName:
5233 Record->push_back(Name.getCXXOverloadedOperator());
5236 case DeclarationName::CXXLiteralOperatorName:
5237 AddIdentifierRef(Name.getCXXLiteralIdentifier());
5240 case DeclarationName::CXXUsingDirective:
5241 // No extra data to emit
5246 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5247 assert(needsAnonymousDeclarationNumber(D) &&
5248 "expected an anonymous declaration");
5250 // Number the anonymous declarations within this context, if we've not
5252 auto It = AnonymousDeclarationNumbers.find(D);
5253 if (It == AnonymousDeclarationNumbers.end()) {
5254 auto *DC = D->getLexicalDeclContext();
5255 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5256 AnonymousDeclarationNumbers[ND] = Number;
5259 It = AnonymousDeclarationNumbers.find(D);
5260 assert(It != AnonymousDeclarationNumbers.end() &&
5261 "declaration not found within its lexical context");
5267 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5268 DeclarationName Name) {
5269 switch (Name.getNameKind()) {
5270 case DeclarationName::CXXConstructorName:
5271 case DeclarationName::CXXDestructorName:
5272 case DeclarationName::CXXConversionFunctionName:
5273 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5276 case DeclarationName::CXXOperatorName:
5277 AddSourceLocation(SourceLocation::getFromRawEncoding(
5278 DNLoc.CXXOperatorName.BeginOpNameLoc));
5280 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5283 case DeclarationName::CXXLiteralOperatorName:
5284 AddSourceLocation(SourceLocation::getFromRawEncoding(
5285 DNLoc.CXXLiteralOperatorName.OpNameLoc));
5288 case DeclarationName::Identifier:
5289 case DeclarationName::ObjCZeroArgSelector:
5290 case DeclarationName::ObjCOneArgSelector:
5291 case DeclarationName::ObjCMultiArgSelector:
5292 case DeclarationName::CXXUsingDirective:
5297 void ASTRecordWriter::AddDeclarationNameInfo(
5298 const DeclarationNameInfo &NameInfo) {
5299 AddDeclarationName(NameInfo.getName());
5300 AddSourceLocation(NameInfo.getLoc());
5301 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5304 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5305 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5306 Record->push_back(Info.NumTemplParamLists);
5307 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5308 AddTemplateParameterList(Info.TemplParamLists[i]);
5311 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5312 // Nested name specifiers usually aren't too long. I think that 8 would
5313 // typically accommodate the vast majority.
5314 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5316 // Push each of the NNS's onto a stack for serialization in reverse order.
5318 NestedNames.push_back(NNS);
5319 NNS = NNS->getPrefix();
5322 Record->push_back(NestedNames.size());
5323 while(!NestedNames.empty()) {
5324 NNS = NestedNames.pop_back_val();
5325 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5326 Record->push_back(Kind);
5328 case NestedNameSpecifier::Identifier:
5329 AddIdentifierRef(NNS->getAsIdentifier());
5332 case NestedNameSpecifier::Namespace:
5333 AddDeclRef(NNS->getAsNamespace());
5336 case NestedNameSpecifier::NamespaceAlias:
5337 AddDeclRef(NNS->getAsNamespaceAlias());
5340 case NestedNameSpecifier::TypeSpec:
5341 case NestedNameSpecifier::TypeSpecWithTemplate:
5342 AddTypeRef(QualType(NNS->getAsType(), 0));
5343 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5346 case NestedNameSpecifier::Global:
5347 // Don't need to write an associated value.
5350 case NestedNameSpecifier::Super:
5351 AddDeclRef(NNS->getAsRecordDecl());
5357 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5358 // Nested name specifiers usually aren't too long. I think that 8 would
5359 // typically accommodate the vast majority.
5360 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5362 // Push each of the nested-name-specifiers's onto a stack for
5363 // serialization in reverse order.
5365 NestedNames.push_back(NNS);
5366 NNS = NNS.getPrefix();
5369 Record->push_back(NestedNames.size());
5370 while(!NestedNames.empty()) {
5371 NNS = NestedNames.pop_back_val();
5372 NestedNameSpecifier::SpecifierKind Kind
5373 = NNS.getNestedNameSpecifier()->getKind();
5374 Record->push_back(Kind);
5376 case NestedNameSpecifier::Identifier:
5377 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5378 AddSourceRange(NNS.getLocalSourceRange());
5381 case NestedNameSpecifier::Namespace:
5382 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5383 AddSourceRange(NNS.getLocalSourceRange());
5386 case NestedNameSpecifier::NamespaceAlias:
5387 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5388 AddSourceRange(NNS.getLocalSourceRange());
5391 case NestedNameSpecifier::TypeSpec:
5392 case NestedNameSpecifier::TypeSpecWithTemplate:
5393 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5394 AddTypeLoc(NNS.getTypeLoc());
5395 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5398 case NestedNameSpecifier::Global:
5399 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5402 case NestedNameSpecifier::Super:
5403 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5404 AddSourceRange(NNS.getLocalSourceRange());
5410 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5411 TemplateName::NameKind Kind = Name.getKind();
5412 Record->push_back(Kind);
5414 case TemplateName::Template:
5415 AddDeclRef(Name.getAsTemplateDecl());
5418 case TemplateName::OverloadedTemplate: {
5419 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5420 Record->push_back(OvT->size());
5421 for (const auto &I : *OvT)
5426 case TemplateName::QualifiedTemplate: {
5427 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5428 AddNestedNameSpecifier(QualT->getQualifier());
5429 Record->push_back(QualT->hasTemplateKeyword());
5430 AddDeclRef(QualT->getTemplateDecl());
5434 case TemplateName::DependentTemplate: {
5435 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5436 AddNestedNameSpecifier(DepT->getQualifier());
5437 Record->push_back(DepT->isIdentifier());
5438 if (DepT->isIdentifier())
5439 AddIdentifierRef(DepT->getIdentifier());
5441 Record->push_back(DepT->getOperator());
5445 case TemplateName::SubstTemplateTemplateParm: {
5446 SubstTemplateTemplateParmStorage *subst
5447 = Name.getAsSubstTemplateTemplateParm();
5448 AddDeclRef(subst->getParameter());
5449 AddTemplateName(subst->getReplacement());
5453 case TemplateName::SubstTemplateTemplateParmPack: {
5454 SubstTemplateTemplateParmPackStorage *SubstPack
5455 = Name.getAsSubstTemplateTemplateParmPack();
5456 AddDeclRef(SubstPack->getParameterPack());
5457 AddTemplateArgument(SubstPack->getArgumentPack());
5463 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5464 Record->push_back(Arg.getKind());
5465 switch (Arg.getKind()) {
5466 case TemplateArgument::Null:
5468 case TemplateArgument::Type:
5469 AddTypeRef(Arg.getAsType());
5471 case TemplateArgument::Declaration:
5472 AddDeclRef(Arg.getAsDecl());
5473 AddTypeRef(Arg.getParamTypeForDecl());
5475 case TemplateArgument::NullPtr:
5476 AddTypeRef(Arg.getNullPtrType());
5478 case TemplateArgument::Integral:
5479 AddAPSInt(Arg.getAsIntegral());
5480 AddTypeRef(Arg.getIntegralType());
5482 case TemplateArgument::Template:
5483 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5485 case TemplateArgument::TemplateExpansion:
5486 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5487 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5488 Record->push_back(*NumExpansions + 1);
5490 Record->push_back(0);
5492 case TemplateArgument::Expression:
5493 AddStmt(Arg.getAsExpr());
5495 case TemplateArgument::Pack:
5496 Record->push_back(Arg.pack_size());
5497 for (const auto &P : Arg.pack_elements())
5498 AddTemplateArgument(P);
5503 void ASTRecordWriter::AddTemplateParameterList(
5504 const TemplateParameterList *TemplateParams) {
5505 assert(TemplateParams && "No TemplateParams!");
5506 AddSourceLocation(TemplateParams->getTemplateLoc());
5507 AddSourceLocation(TemplateParams->getLAngleLoc());
5508 AddSourceLocation(TemplateParams->getRAngleLoc());
5510 Record->push_back(TemplateParams->size());
5511 for (const auto &P : *TemplateParams)
5515 /// \brief Emit a template argument list.
5516 void ASTRecordWriter::AddTemplateArgumentList(
5517 const TemplateArgumentList *TemplateArgs) {
5518 assert(TemplateArgs && "No TemplateArgs!");
5519 Record->push_back(TemplateArgs->size());
5520 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5521 AddTemplateArgument(TemplateArgs->get(i));
5524 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5525 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5526 assert(ASTTemplArgList && "No ASTTemplArgList!");
5527 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5528 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5529 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5530 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5531 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5532 AddTemplateArgumentLoc(TemplArgs[i]);
5535 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5536 Record->push_back(Set.size());
5537 for (ASTUnresolvedSet::const_iterator
5538 I = Set.begin(), E = Set.end(); I != E; ++I) {
5539 AddDeclRef(I.getDecl());
5540 Record->push_back(I.getAccess());
5544 // FIXME: Move this out of the main ASTRecordWriter interface.
5545 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5546 Record->push_back(Base.isVirtual());
5547 Record->push_back(Base.isBaseOfClass());
5548 Record->push_back(Base.getAccessSpecifierAsWritten());
5549 Record->push_back(Base.getInheritConstructors());
5550 AddTypeSourceInfo(Base.getTypeSourceInfo());
5551 AddSourceRange(Base.getSourceRange());
5552 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5553 : SourceLocation());
5556 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5557 ArrayRef<CXXBaseSpecifier> Bases) {
5558 ASTWriter::RecordData Record;
5559 ASTRecordWriter Writer(W, Record);
5560 Writer.push_back(Bases.size());
5562 for (auto &Base : Bases)
5563 Writer.AddCXXBaseSpecifier(Base);
5565 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5568 // FIXME: Move this out of the main ASTRecordWriter interface.
5569 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5570 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5574 EmitCXXCtorInitializers(ASTWriter &W,
5575 ArrayRef<CXXCtorInitializer *> CtorInits) {
5576 ASTWriter::RecordData Record;
5577 ASTRecordWriter Writer(W, Record);
5578 Writer.push_back(CtorInits.size());
5580 for (auto *Init : CtorInits) {
5581 if (Init->isBaseInitializer()) {
5582 Writer.push_back(CTOR_INITIALIZER_BASE);
5583 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5584 Writer.push_back(Init->isBaseVirtual());
5585 } else if (Init->isDelegatingInitializer()) {
5586 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5587 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5588 } else if (Init->isMemberInitializer()){
5589 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5590 Writer.AddDeclRef(Init->getMember());
5592 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5593 Writer.AddDeclRef(Init->getIndirectMember());
5596 Writer.AddSourceLocation(Init->getMemberLocation());
5597 Writer.AddStmt(Init->getInit());
5598 Writer.AddSourceLocation(Init->getLParenLoc());
5599 Writer.AddSourceLocation(Init->getRParenLoc());
5600 Writer.push_back(Init->isWritten());
5601 if (Init->isWritten())
5602 Writer.push_back(Init->getSourceOrder());
5605 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5608 // FIXME: Move this out of the main ASTRecordWriter interface.
5609 void ASTRecordWriter::AddCXXCtorInitializers(
5610 ArrayRef<CXXCtorInitializer *> CtorInits) {
5611 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5614 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5615 auto &Data = D->data();
5616 Record->push_back(Data.IsLambda);
5617 Record->push_back(Data.UserDeclaredConstructor);
5618 Record->push_back(Data.UserDeclaredSpecialMembers);
5619 Record->push_back(Data.Aggregate);
5620 Record->push_back(Data.PlainOldData);
5621 Record->push_back(Data.Empty);
5622 Record->push_back(Data.Polymorphic);
5623 Record->push_back(Data.Abstract);
5624 Record->push_back(Data.IsStandardLayout);
5625 Record->push_back(Data.HasNoNonEmptyBases);
5626 Record->push_back(Data.HasPrivateFields);
5627 Record->push_back(Data.HasProtectedFields);
5628 Record->push_back(Data.HasPublicFields);
5629 Record->push_back(Data.HasMutableFields);
5630 Record->push_back(Data.HasVariantMembers);
5631 Record->push_back(Data.HasOnlyCMembers);
5632 Record->push_back(Data.HasInClassInitializer);
5633 Record->push_back(Data.HasUninitializedReferenceMember);
5634 Record->push_back(Data.HasUninitializedFields);
5635 Record->push_back(Data.HasInheritedConstructor);
5636 Record->push_back(Data.HasInheritedAssignment);
5637 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5638 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5639 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5640 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5641 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5642 Record->push_back(Data.DefaultedDestructorIsDeleted);
5643 Record->push_back(Data.HasTrivialSpecialMembers);
5644 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5645 Record->push_back(Data.HasIrrelevantDestructor);
5646 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5647 Record->push_back(Data.HasDefaultedDefaultConstructor);
5648 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5649 Record->push_back(Data.HasConstexprDefaultConstructor);
5650 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5651 Record->push_back(Data.ComputedVisibleConversions);
5652 Record->push_back(Data.UserProvidedDefaultConstructor);
5653 Record->push_back(Data.DeclaredSpecialMembers);
5654 Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5655 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5656 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5657 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5658 // IsLambda bit is already saved.
5660 Record->push_back(Data.NumBases);
5661 if (Data.NumBases > 0)
5662 AddCXXBaseSpecifiers(Data.bases());
5664 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5665 Record->push_back(Data.NumVBases);
5666 if (Data.NumVBases > 0)
5667 AddCXXBaseSpecifiers(Data.vbases());
5669 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5670 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5671 // Data.Definition is the owning decl, no need to write it.
5672 AddDeclRef(D->getFirstFriend());
5674 // Add lambda-specific data.
5675 if (Data.IsLambda) {
5676 auto &Lambda = D->getLambdaData();
5677 Record->push_back(Lambda.Dependent);
5678 Record->push_back(Lambda.IsGenericLambda);
5679 Record->push_back(Lambda.CaptureDefault);
5680 Record->push_back(Lambda.NumCaptures);
5681 Record->push_back(Lambda.NumExplicitCaptures);
5682 Record->push_back(Lambda.ManglingNumber);
5683 AddDeclRef(D->getLambdaContextDecl());
5684 AddTypeSourceInfo(Lambda.MethodTyInfo);
5685 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5686 const LambdaCapture &Capture = Lambda.Captures[I];
5687 AddSourceLocation(Capture.getLocation());
5688 Record->push_back(Capture.isImplicit());
5689 Record->push_back(Capture.getCaptureKind());
5690 switch (Capture.getCaptureKind()) {
5698 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5700 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5701 : SourceLocation());
5708 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5709 assert(Reader && "Cannot remove chain");
5710 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5711 assert(FirstDeclID == NextDeclID &&
5712 FirstTypeID == NextTypeID &&
5713 FirstIdentID == NextIdentID &&
5714 FirstMacroID == NextMacroID &&
5715 FirstSubmoduleID == NextSubmoduleID &&
5716 FirstSelectorID == NextSelectorID &&
5717 "Setting chain after writing has started.");
5721 // Note, this will get called multiple times, once one the reader starts up
5722 // and again each time it's done reading a PCH or module.
5723 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5724 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5725 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5726 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5727 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5728 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5729 NextDeclID = FirstDeclID;
5730 NextTypeID = FirstTypeID;
5731 NextIdentID = FirstIdentID;
5732 NextMacroID = FirstMacroID;
5733 NextSelectorID = FirstSelectorID;
5734 NextSubmoduleID = FirstSubmoduleID;
5737 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5738 // Always keep the highest ID. See \p TypeRead() for more information.
5739 IdentID &StoredID = IdentifierIDs[II];
5744 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5745 // Always keep the highest ID. See \p TypeRead() for more information.
5746 MacroID &StoredID = MacroIDs[MI];
5751 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5752 // Always take the highest-numbered type index. This copes with an interesting
5753 // case for chained AST writing where we schedule writing the type and then,
5754 // later, deserialize the type from another AST. In this case, we want to
5755 // keep the higher-numbered entry so that we can properly write it out to
5757 TypeIdx &StoredIdx = TypeIdxs[T];
5758 if (Idx.getIndex() >= StoredIdx.getIndex())
5762 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5763 // Always keep the highest ID. See \p TypeRead() for more information.
5764 SelectorID &StoredID = SelectorIDs[S];
5769 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5770 MacroDefinitionRecord *MD) {
5771 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5772 MacroDefinitions[MD] = ID;
5775 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5776 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5777 SubmoduleIDs[Mod] = ID;
5780 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5781 if (Chain && Chain->isProcessingUpdateRecords()) return;
5782 assert(D->isCompleteDefinition());
5783 assert(!WritingAST && "Already writing the AST!");
5784 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5785 // We are interested when a PCH decl is modified.
5786 if (RD->isFromASTFile()) {
5787 // A forward reference was mutated into a definition. Rewrite it.
5788 // FIXME: This happens during template instantiation, should we
5789 // have created a new definition decl instead ?
5790 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5791 "completed a tag from another module but not by instantiation?");
5792 DeclUpdates[RD].push_back(
5793 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5798 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5799 if (D->isFromASTFile())
5802 // The predefined __va_list_tag struct is imported if we imported any decls.
5803 // FIXME: This is a gross hack.
5804 return D == D->getASTContext().getVaListTagDecl();
5807 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5808 if (Chain && Chain->isProcessingUpdateRecords()) return;
5809 assert(DC->isLookupContext() &&
5810 "Should not add lookup results to non-lookup contexts!");
5812 // TU is handled elsewhere.
5813 if (isa<TranslationUnitDecl>(DC))
5816 // Namespaces are handled elsewhere, except for template instantiations of
5817 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5818 // local instantiations are added to an imported context. Only happens when
5819 // adding ADL lookup candidates, for example templated friends.
5820 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5821 !isa<FunctionTemplateDecl>(D))
5824 // We're only interested in cases where a local declaration is added to an
5825 // imported context.
5826 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5829 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5830 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5831 assert(!WritingAST && "Already writing the AST!");
5832 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5833 // We're adding a visible declaration to a predefined decl context. Ensure
5834 // that we write out all of its lookup results so we don't get a nasty
5835 // surprise when we try to emit its lookup table.
5836 for (auto *Child : DC->decls())
5837 DeclsToEmitEvenIfUnreferenced.push_back(Child);
5839 DeclsToEmitEvenIfUnreferenced.push_back(D);
5842 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5843 if (Chain && Chain->isProcessingUpdateRecords()) return;
5844 assert(D->isImplicit());
5846 // We're only interested in cases where a local declaration is added to an
5847 // imported context.
5848 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5851 if (!isa<CXXMethodDecl>(D))
5854 // A decl coming from PCH was modified.
5855 assert(RD->isCompleteDefinition());
5856 assert(!WritingAST && "Already writing the AST!");
5857 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5860 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5861 if (Chain && Chain->isProcessingUpdateRecords()) return;
5862 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5864 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5865 // If we don't already know the exception specification for this redecl
5866 // chain, add an update record for it.
5867 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5869 ->castAs<FunctionProtoType>()
5870 ->getExceptionSpecType()))
5871 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5875 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5876 if (Chain && Chain->isProcessingUpdateRecords()) return;
5877 assert(!WritingAST && "Already writing the AST!");
5879 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5880 DeclUpdates[D].push_back(
5881 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5885 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5886 const FunctionDecl *Delete) {
5887 if (Chain && Chain->isProcessingUpdateRecords()) return;
5888 assert(!WritingAST && "Already writing the AST!");
5889 assert(Delete && "Not given an operator delete");
5891 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5892 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5896 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5897 if (Chain && Chain->isProcessingUpdateRecords()) return;
5898 assert(!WritingAST && "Already writing the AST!");
5899 if (!D->isFromASTFile())
5900 return; // Declaration not imported from PCH.
5902 // Implicit function decl from a PCH was defined.
5903 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5906 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5907 if (Chain && Chain->isProcessingUpdateRecords()) return;
5908 assert(!WritingAST && "Already writing the AST!");
5909 if (!D->isFromASTFile())
5912 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5915 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5916 if (Chain && Chain->isProcessingUpdateRecords()) return;
5917 assert(!WritingAST && "Already writing the AST!");
5918 if (!D->isFromASTFile())
5921 // Since the actual instantiation is delayed, this really means that we need
5922 // to update the instantiation location.
5923 DeclUpdates[D].push_back(
5924 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5925 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5928 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5929 if (Chain && Chain->isProcessingUpdateRecords()) return;
5930 assert(!WritingAST && "Already writing the AST!");
5931 if (!D->isFromASTFile())
5934 DeclUpdates[D].push_back(
5935 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5938 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5939 assert(!WritingAST && "Already writing the AST!");
5940 if (!D->isFromASTFile())
5943 DeclUpdates[D].push_back(
5944 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5947 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5948 const ObjCInterfaceDecl *IFD) {
5949 if (Chain && Chain->isProcessingUpdateRecords()) return;
5950 assert(!WritingAST && "Already writing the AST!");
5951 if (!IFD->isFromASTFile())
5952 return; // Declaration not imported from PCH.
5954 assert(IFD->getDefinition() && "Category on a class without a definition?");
5955 ObjCClassesWithCategories.insert(
5956 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5959 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5960 if (Chain && Chain->isProcessingUpdateRecords()) return;
5961 assert(!WritingAST && "Already writing the AST!");
5963 // If there is *any* declaration of the entity that's not from an AST file,
5964 // we can skip writing the update record. We make sure that isUsed() triggers
5965 // completion of the redeclaration chain of the entity.
5966 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5967 if (IsLocalDecl(Prev))
5970 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5973 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5974 if (Chain && Chain->isProcessingUpdateRecords()) return;
5975 assert(!WritingAST && "Already writing the AST!");
5976 if (!D->isFromASTFile())
5979 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5982 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5984 if (Chain && Chain->isProcessingUpdateRecords()) return;
5985 assert(!WritingAST && "Already writing the AST!");
5986 if (!D->isFromASTFile())
5989 DeclUpdates[D].push_back(
5990 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
5993 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5994 if (Chain && Chain->isProcessingUpdateRecords()) return;
5995 assert(!WritingAST && "Already writing the AST!");
5996 assert(D->isHidden() && "expected a hidden declaration");
5997 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6000 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6001 const RecordDecl *Record) {
6002 if (Chain && Chain->isProcessingUpdateRecords()) return;
6003 assert(!WritingAST && "Already writing the AST!");
6004 if (!Record->isFromASTFile())
6006 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6009 void ASTWriter::AddedCXXTemplateSpecialization(
6010 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6011 assert(!WritingAST && "Already writing the AST!");
6013 if (!TD->getFirstDecl()->isFromASTFile())
6015 if (Chain && Chain->isProcessingUpdateRecords())
6018 DeclsToEmitEvenIfUnreferenced.push_back(D);
6021 void ASTWriter::AddedCXXTemplateSpecialization(
6022 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6023 assert(!WritingAST && "Already writing the AST!");
6025 if (!TD->getFirstDecl()->isFromASTFile())
6027 if (Chain && Chain->isProcessingUpdateRecords())
6030 DeclsToEmitEvenIfUnreferenced.push_back(D);
6033 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6034 const FunctionDecl *D) {
6035 assert(!WritingAST && "Already writing the AST!");
6037 if (!TD->getFirstDecl()->isFromASTFile())
6039 if (Chain && Chain->isProcessingUpdateRecords())
6042 DeclsToEmitEvenIfUnreferenced.push_back(D);