xref: /freebsd/contrib/llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp (revision 56b17de1e8360fe131d425de20b5e75ff3ea897c)
1 //===--- ASTWriterDecl.cpp - Declaration Serialization --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements serialization for Declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/OpenMPClause.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Serialization/ASTReader.h"
23 #include "clang/Serialization/ASTRecordWriter.h"
24 #include "llvm/Bitstream/BitstreamWriter.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <optional>
27 using namespace clang;
28 using namespace serialization;
29 
30 //===----------------------------------------------------------------------===//
31 // Declaration serialization
32 //===----------------------------------------------------------------------===//
33 
34 namespace clang {
35   class ASTDeclWriter : public DeclVisitor<ASTDeclWriter, void> {
36     ASTWriter &Writer;
37     ASTContext &Context;
38     ASTRecordWriter Record;
39 
40     serialization::DeclCode Code;
41     unsigned AbbrevToUse;
42 
43     bool GeneratingReducedBMI = false;
44 
45   public:
46     ASTDeclWriter(ASTWriter &Writer, ASTContext &Context,
47                   ASTWriter::RecordDataImpl &Record, bool GeneratingReducedBMI)
48         : Writer(Writer), Context(Context), Record(Writer, Record),
49           Code((serialization::DeclCode)0), AbbrevToUse(0),
50           GeneratingReducedBMI(GeneratingReducedBMI) {}
51 
52     uint64_t Emit(Decl *D) {
53       if (!Code)
54         llvm::report_fatal_error(StringRef("unexpected declaration kind '") +
55             D->getDeclKindName() + "'");
56       return Record.Emit(Code, AbbrevToUse);
57     }
58 
59     void Visit(Decl *D);
60 
61     void VisitDecl(Decl *D);
62     void VisitPragmaCommentDecl(PragmaCommentDecl *D);
63     void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
64     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
65     void VisitNamedDecl(NamedDecl *D);
66     void VisitLabelDecl(LabelDecl *LD);
67     void VisitNamespaceDecl(NamespaceDecl *D);
68     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
69     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
70     void VisitTypeDecl(TypeDecl *D);
71     void VisitTypedefNameDecl(TypedefNameDecl *D);
72     void VisitTypedefDecl(TypedefDecl *D);
73     void VisitTypeAliasDecl(TypeAliasDecl *D);
74     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
75     void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
76     void VisitTagDecl(TagDecl *D);
77     void VisitEnumDecl(EnumDecl *D);
78     void VisitRecordDecl(RecordDecl *D);
79     void VisitCXXRecordDecl(CXXRecordDecl *D);
80     void VisitClassTemplateSpecializationDecl(
81                                             ClassTemplateSpecializationDecl *D);
82     void VisitClassTemplatePartialSpecializationDecl(
83                                      ClassTemplatePartialSpecializationDecl *D);
84     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
85     void VisitVarTemplatePartialSpecializationDecl(
86         VarTemplatePartialSpecializationDecl *D);
87     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
88     void VisitValueDecl(ValueDecl *D);
89     void VisitEnumConstantDecl(EnumConstantDecl *D);
90     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
91     void VisitDeclaratorDecl(DeclaratorDecl *D);
92     void VisitFunctionDecl(FunctionDecl *D);
93     void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
94     void VisitCXXMethodDecl(CXXMethodDecl *D);
95     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
96     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
97     void VisitCXXConversionDecl(CXXConversionDecl *D);
98     void VisitFieldDecl(FieldDecl *D);
99     void VisitMSPropertyDecl(MSPropertyDecl *D);
100     void VisitMSGuidDecl(MSGuidDecl *D);
101     void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);
102     void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
103     void VisitIndirectFieldDecl(IndirectFieldDecl *D);
104     void VisitVarDecl(VarDecl *D);
105     void VisitImplicitParamDecl(ImplicitParamDecl *D);
106     void VisitParmVarDecl(ParmVarDecl *D);
107     void VisitDecompositionDecl(DecompositionDecl *D);
108     void VisitBindingDecl(BindingDecl *D);
109     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
110     void VisitTemplateDecl(TemplateDecl *D);
111     void VisitConceptDecl(ConceptDecl *D);
112     void VisitImplicitConceptSpecializationDecl(
113         ImplicitConceptSpecializationDecl *D);
114     void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
115     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
116     void VisitClassTemplateDecl(ClassTemplateDecl *D);
117     void VisitVarTemplateDecl(VarTemplateDecl *D);
118     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
119     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
120     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
121     void VisitUsingDecl(UsingDecl *D);
122     void VisitUsingEnumDecl(UsingEnumDecl *D);
123     void VisitUsingPackDecl(UsingPackDecl *D);
124     void VisitUsingShadowDecl(UsingShadowDecl *D);
125     void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
126     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
127     void VisitExportDecl(ExportDecl *D);
128     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
129     void VisitTopLevelStmtDecl(TopLevelStmtDecl *D);
130     void VisitImportDecl(ImportDecl *D);
131     void VisitAccessSpecDecl(AccessSpecDecl *D);
132     void VisitFriendDecl(FriendDecl *D);
133     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
134     void VisitStaticAssertDecl(StaticAssertDecl *D);
135     void VisitBlockDecl(BlockDecl *D);
136     void VisitCapturedDecl(CapturedDecl *D);
137     void VisitEmptyDecl(EmptyDecl *D);
138     void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
139     void VisitDeclContext(DeclContext *DC);
140     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
141     void VisitHLSLBufferDecl(HLSLBufferDecl *D);
142 
143     // FIXME: Put in the same order is DeclNodes.td?
144     void VisitObjCMethodDecl(ObjCMethodDecl *D);
145     void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
146     void VisitObjCContainerDecl(ObjCContainerDecl *D);
147     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
148     void VisitObjCIvarDecl(ObjCIvarDecl *D);
149     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
150     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
151     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
152     void VisitObjCImplDecl(ObjCImplDecl *D);
153     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
154     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
155     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
156     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
157     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
158     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
159     void VisitOMPAllocateDecl(OMPAllocateDecl *D);
160     void VisitOMPRequiresDecl(OMPRequiresDecl *D);
161     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
162     void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
163     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
164 
165     /// Add an Objective-C type parameter list to the given record.
166     void AddObjCTypeParamList(ObjCTypeParamList *typeParams) {
167       // Empty type parameter list.
168       if (!typeParams) {
169         Record.push_back(0);
170         return;
171       }
172 
173       Record.push_back(typeParams->size());
174       for (auto *typeParam : *typeParams) {
175         Record.AddDeclRef(typeParam);
176       }
177       Record.AddSourceLocation(typeParams->getLAngleLoc());
178       Record.AddSourceLocation(typeParams->getRAngleLoc());
179     }
180 
181     /// Add to the record the first declaration from each module file that
182     /// provides a declaration of D. The intent is to provide a sufficient
183     /// set such that reloading this set will load all current redeclarations.
184     void AddFirstDeclFromEachModule(const Decl *D, bool IncludeLocal) {
185       llvm::MapVector<ModuleFile*, const Decl*> Firsts;
186       // FIXME: We can skip entries that we know are implied by others.
187       for (const Decl *R = D->getMostRecentDecl(); R; R = R->getPreviousDecl()) {
188         if (R->isFromASTFile())
189           Firsts[Writer.Chain->getOwningModuleFile(R)] = R;
190         else if (IncludeLocal)
191           Firsts[nullptr] = R;
192       }
193       for (const auto &F : Firsts)
194         Record.AddDeclRef(F.second);
195     }
196 
197     /// Get the specialization decl from an entry in the specialization list.
198     template <typename EntryType>
199     typename RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::DeclType *
200     getSpecializationDecl(EntryType &T) {
201       return RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::getDecl(&T);
202     }
203 
204     /// Get the list of partial specializations from a template's common ptr.
205     template<typename T>
206     decltype(T::PartialSpecializations) &getPartialSpecializations(T *Common) {
207       return Common->PartialSpecializations;
208     }
209     ArrayRef<Decl> getPartialSpecializations(FunctionTemplateDecl::Common *) {
210       return std::nullopt;
211     }
212 
213     template<typename DeclTy>
214     void AddTemplateSpecializations(DeclTy *D) {
215       auto *Common = D->getCommonPtr();
216 
217       // If we have any lazy specializations, and the external AST source is
218       // our chained AST reader, we can just write out the DeclIDs. Otherwise,
219       // we need to resolve them to actual declarations.
220       if (Writer.Chain != Writer.Context->getExternalSource() &&
221           Common->LazySpecializations) {
222         D->LoadLazySpecializations();
223         assert(!Common->LazySpecializations);
224       }
225 
226       ArrayRef<GlobalDeclID> LazySpecializations;
227       if (auto *LS = Common->LazySpecializations)
228         LazySpecializations = llvm::ArrayRef(LS + 1, LS[0].getRawValue());
229 
230       // Add a slot to the record for the number of specializations.
231       unsigned I = Record.size();
232       Record.push_back(0);
233 
234       // AddFirstDeclFromEachModule might trigger deserialization, invalidating
235       // *Specializations iterators.
236       llvm::SmallVector<const Decl*, 16> Specs;
237       for (auto &Entry : Common->Specializations)
238         Specs.push_back(getSpecializationDecl(Entry));
239       for (auto &Entry : getPartialSpecializations(Common))
240         Specs.push_back(getSpecializationDecl(Entry));
241 
242       for (auto *D : Specs) {
243         assert(D->isCanonicalDecl() && "non-canonical decl in set");
244         AddFirstDeclFromEachModule(D, /*IncludeLocal*/true);
245       }
246       Record.append(
247           DeclIDIterator<GlobalDeclID, DeclID>(LazySpecializations.begin()),
248           DeclIDIterator<GlobalDeclID, DeclID>(LazySpecializations.end()));
249 
250       // Update the size entry we added earlier.
251       Record[I] = Record.size() - I - 1;
252     }
253 
254     /// Ensure that this template specialization is associated with the specified
255     /// template on reload.
256     void RegisterTemplateSpecialization(const Decl *Template,
257                                         const Decl *Specialization) {
258       Template = Template->getCanonicalDecl();
259 
260       // If the canonical template is local, we'll write out this specialization
261       // when we emit it.
262       // FIXME: We can do the same thing if there is any local declaration of
263       // the template, to avoid emitting an update record.
264       if (!Template->isFromASTFile())
265         return;
266 
267       // We only need to associate the first local declaration of the
268       // specialization. The other declarations will get pulled in by it.
269       if (Writer.getFirstLocalDecl(Specialization) != Specialization)
270         return;
271 
272       Writer.DeclUpdates[Template].push_back(ASTWriter::DeclUpdate(
273           UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, Specialization));
274     }
275   };
276 }
277 
278 bool clang::CanElideDeclDef(const Decl *D) {
279   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
280     if (FD->isInlined() || FD->isConstexpr())
281       return false;
282 
283     if (FD->isDependentContext())
284       return false;
285 
286     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
287       return false;
288   }
289 
290   if (auto *VD = dyn_cast<VarDecl>(D)) {
291     if (!VD->getDeclContext()->getRedeclContext()->isFileContext() ||
292         VD->isInline() || VD->isConstexpr() || isa<ParmVarDecl>(VD) ||
293         // Constant initialized variable may not affect the ABI, but they
294         // may be used in constant evaluation in the frontend, so we have
295         // to remain them.
296         VD->hasConstantInitialization())
297       return false;
298 
299     if (VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
300       return false;
301   }
302 
303   return true;
304 }
305 
306 void ASTDeclWriter::Visit(Decl *D) {
307   DeclVisitor<ASTDeclWriter>::Visit(D);
308 
309   // Source locations require array (variable-length) abbreviations.  The
310   // abbreviation infrastructure requires that arrays are encoded last, so
311   // we handle it here in the case of those classes derived from DeclaratorDecl
312   if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
313     if (auto *TInfo = DD->getTypeSourceInfo())
314       Record.AddTypeLoc(TInfo->getTypeLoc());
315   }
316 
317   // Handle FunctionDecl's body here and write it after all other Stmts/Exprs
318   // have been written. We want it last because we will not read it back when
319   // retrieving it from the AST, we'll just lazily set the offset.
320   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
321     if (!GeneratingReducedBMI || !CanElideDeclDef(FD)) {
322       Record.push_back(FD->doesThisDeclarationHaveABody());
323       if (FD->doesThisDeclarationHaveABody())
324         Record.AddFunctionDefinition(FD);
325     } else
326       Record.push_back(0);
327   }
328 
329   // Similar to FunctionDecls, handle VarDecl's initializer here and write it
330   // after all other Stmts/Exprs. We will not read the initializer until after
331   // we have finished recursive deserialization, because it can recursively
332   // refer back to the variable.
333   if (auto *VD = dyn_cast<VarDecl>(D)) {
334     if (!GeneratingReducedBMI || !CanElideDeclDef(VD))
335       Record.AddVarDeclInit(VD);
336     else
337       Record.push_back(0);
338   }
339 
340   // And similarly for FieldDecls. We already serialized whether there is a
341   // default member initializer.
342   if (auto *FD = dyn_cast<FieldDecl>(D)) {
343     if (FD->hasInClassInitializer()) {
344       if (Expr *Init = FD->getInClassInitializer()) {
345         Record.push_back(1);
346         Record.AddStmt(Init);
347       } else {
348         Record.push_back(0);
349         // Initializer has not been instantiated yet.
350       }
351     }
352   }
353 
354   // If this declaration is also a DeclContext, write blocks for the
355   // declarations that lexically stored inside its context and those
356   // declarations that are visible from its context.
357   if (auto *DC = dyn_cast<DeclContext>(D))
358     VisitDeclContext(DC);
359 }
360 
361 void ASTDeclWriter::VisitDecl(Decl *D) {
362   BitsPacker DeclBits;
363 
364   // The order matters here. It will be better to put the bit with higher
365   // probability to be 0 in the end of the bits.
366   //
367   // Since we're using VBR6 format to store it.
368   // It will be pretty effient if all the higher bits are 0.
369   // For example, if we need to pack 8 bits into a value and the stored value
370   // is 0xf0, the actual stored value will be 0b000111'110000, which takes 12
371   // bits actually. However, if we changed the order to be 0x0f, then we can
372   // store it as 0b001111, which takes 6 bits only now.
373   DeclBits.addBits((uint64_t)D->getModuleOwnershipKind(), /*BitWidth=*/3);
374   DeclBits.addBit(D->isReferenced());
375   DeclBits.addBit(D->isUsed(false));
376   DeclBits.addBits(D->getAccess(), /*BitWidth=*/2);
377   DeclBits.addBit(D->isImplicit());
378   DeclBits.addBit(D->getDeclContext() != D->getLexicalDeclContext());
379   DeclBits.addBit(D->hasAttrs());
380   DeclBits.addBit(D->isTopLevelDeclInObjCContainer());
381   DeclBits.addBit(D->isInvalidDecl());
382   Record.push_back(DeclBits);
383 
384   Record.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()));
385   if (D->getDeclContext() != D->getLexicalDeclContext())
386     Record.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()));
387 
388   if (D->hasAttrs())
389     Record.AddAttributes(D->getAttrs());
390 
391   Record.push_back(Writer.getSubmoduleID(D->getOwningModule()));
392 
393   // If this declaration injected a name into a context different from its
394   // lexical context, and that context is an imported namespace, we need to
395   // update its visible declarations to include this name.
396   //
397   // This happens when we instantiate a class with a friend declaration or a
398   // function with a local extern declaration, for instance.
399   //
400   // FIXME: Can we handle this in AddedVisibleDecl instead?
401   if (D->isOutOfLine()) {
402     auto *DC = D->getDeclContext();
403     while (auto *NS = dyn_cast<NamespaceDecl>(DC->getRedeclContext())) {
404       if (!NS->isFromASTFile())
405         break;
406       Writer.UpdatedDeclContexts.insert(NS->getPrimaryContext());
407       if (!NS->isInlineNamespace())
408         break;
409       DC = NS->getParent();
410     }
411   }
412 }
413 
414 void ASTDeclWriter::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
415   StringRef Arg = D->getArg();
416   Record.push_back(Arg.size());
417   VisitDecl(D);
418   Record.AddSourceLocation(D->getBeginLoc());
419   Record.push_back(D->getCommentKind());
420   Record.AddString(Arg);
421   Code = serialization::DECL_PRAGMA_COMMENT;
422 }
423 
424 void ASTDeclWriter::VisitPragmaDetectMismatchDecl(
425     PragmaDetectMismatchDecl *D) {
426   StringRef Name = D->getName();
427   StringRef Value = D->getValue();
428   Record.push_back(Name.size() + 1 + Value.size());
429   VisitDecl(D);
430   Record.AddSourceLocation(D->getBeginLoc());
431   Record.AddString(Name);
432   Record.AddString(Value);
433   Code = serialization::DECL_PRAGMA_DETECT_MISMATCH;
434 }
435 
436 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
437   llvm_unreachable("Translation units aren't directly serialized");
438 }
439 
440 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
441   VisitDecl(D);
442   Record.AddDeclarationName(D->getDeclName());
443   Record.push_back(needsAnonymousDeclarationNumber(D)
444                        ? Writer.getAnonymousDeclarationNumber(D)
445                        : 0);
446 }
447 
448 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
449   VisitNamedDecl(D);
450   Record.AddSourceLocation(D->getBeginLoc());
451   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
452 }
453 
454 void ASTDeclWriter::VisitTypedefNameDecl(TypedefNameDecl *D) {
455   VisitRedeclarable(D);
456   VisitTypeDecl(D);
457   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
458   Record.push_back(D->isModed());
459   if (D->isModed())
460     Record.AddTypeRef(D->getUnderlyingType());
461   Record.AddDeclRef(D->getAnonDeclWithTypedefName(false));
462 }
463 
464 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
465   VisitTypedefNameDecl(D);
466   if (D->getDeclContext() == D->getLexicalDeclContext() &&
467       !D->hasAttrs() &&
468       !D->isImplicit() &&
469       D->getFirstDecl() == D->getMostRecentDecl() &&
470       !D->isInvalidDecl() &&
471       !D->isTopLevelDeclInObjCContainer() &&
472       !D->isModulePrivate() &&
473       !needsAnonymousDeclarationNumber(D) &&
474       D->getDeclName().getNameKind() == DeclarationName::Identifier)
475     AbbrevToUse = Writer.getDeclTypedefAbbrev();
476 
477   Code = serialization::DECL_TYPEDEF;
478 }
479 
480 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
481   VisitTypedefNameDecl(D);
482   Record.AddDeclRef(D->getDescribedAliasTemplate());
483   Code = serialization::DECL_TYPEALIAS;
484 }
485 
486 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
487   static_assert(DeclContext::NumTagDeclBits == 23,
488                 "You need to update the serializer after you change the "
489                 "TagDeclBits");
490 
491   VisitRedeclarable(D);
492   VisitTypeDecl(D);
493   Record.push_back(D->getIdentifierNamespace());
494 
495   BitsPacker TagDeclBits;
496   TagDeclBits.addBits(llvm::to_underlying(D->getTagKind()), /*BitWidth=*/3);
497   TagDeclBits.addBit(!isa<CXXRecordDecl>(D) ? D->isCompleteDefinition() : 0);
498   TagDeclBits.addBit(D->isEmbeddedInDeclarator());
499   TagDeclBits.addBit(D->isFreeStanding());
500   TagDeclBits.addBit(D->isCompleteDefinitionRequired());
501   TagDeclBits.addBits(
502       D->hasExtInfo() ? 1 : (D->getTypedefNameForAnonDecl() ? 2 : 0),
503       /*BitWidth=*/2);
504   Record.push_back(TagDeclBits);
505 
506   Record.AddSourceRange(D->getBraceRange());
507 
508   if (D->hasExtInfo()) {
509     Record.AddQualifierInfo(*D->getExtInfo());
510   } else if (auto *TD = D->getTypedefNameForAnonDecl()) {
511     Record.AddDeclRef(TD);
512     Record.AddIdentifierRef(TD->getDeclName().getAsIdentifierInfo());
513   }
514 }
515 
516 void ASTDeclWriter::VisitEnumDecl(EnumDecl *D) {
517   static_assert(DeclContext::NumEnumDeclBits == 43,
518                 "You need to update the serializer after you change the "
519                 "EnumDeclBits");
520 
521   VisitTagDecl(D);
522   Record.AddTypeSourceInfo(D->getIntegerTypeSourceInfo());
523   if (!D->getIntegerTypeSourceInfo())
524     Record.AddTypeRef(D->getIntegerType());
525   Record.AddTypeRef(D->getPromotionType());
526 
527   BitsPacker EnumDeclBits;
528   EnumDeclBits.addBits(D->getNumPositiveBits(), /*BitWidth=*/8);
529   EnumDeclBits.addBits(D->getNumNegativeBits(), /*BitWidth=*/8);
530   EnumDeclBits.addBit(D->isScoped());
531   EnumDeclBits.addBit(D->isScopedUsingClassTag());
532   EnumDeclBits.addBit(D->isFixed());
533   Record.push_back(EnumDeclBits);
534 
535   Record.push_back(D->getODRHash());
536 
537   if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
538     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
539     Record.push_back(MemberInfo->getTemplateSpecializationKind());
540     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
541   } else {
542     Record.AddDeclRef(nullptr);
543   }
544 
545   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
546       !D->isInvalidDecl() && !D->isImplicit() && !D->hasExtInfo() &&
547       !D->getTypedefNameForAnonDecl() &&
548       D->getFirstDecl() == D->getMostRecentDecl() &&
549       !D->isTopLevelDeclInObjCContainer() &&
550       !CXXRecordDecl::classofKind(D->getKind()) &&
551       !D->getIntegerTypeSourceInfo() && !D->getMemberSpecializationInfo() &&
552       !needsAnonymousDeclarationNumber(D) &&
553       D->getDeclName().getNameKind() == DeclarationName::Identifier)
554     AbbrevToUse = Writer.getDeclEnumAbbrev();
555 
556   Code = serialization::DECL_ENUM;
557 }
558 
559 void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
560   static_assert(DeclContext::NumRecordDeclBits == 64,
561                 "You need to update the serializer after you change the "
562                 "RecordDeclBits");
563 
564   VisitTagDecl(D);
565 
566   BitsPacker RecordDeclBits;
567   RecordDeclBits.addBit(D->hasFlexibleArrayMember());
568   RecordDeclBits.addBit(D->isAnonymousStructOrUnion());
569   RecordDeclBits.addBit(D->hasObjectMember());
570   RecordDeclBits.addBit(D->hasVolatileMember());
571   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveDefaultInitialize());
572   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveCopy());
573   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveDestroy());
574   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDefaultInitializeCUnion());
575   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDestructCUnion());
576   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveCopyCUnion());
577   RecordDeclBits.addBit(D->isParamDestroyedInCallee());
578   RecordDeclBits.addBits(llvm::to_underlying(D->getArgPassingRestrictions()), 2);
579   Record.push_back(RecordDeclBits);
580 
581   // Only compute this for C/Objective-C, in C++ this is computed as part
582   // of CXXRecordDecl.
583   if (!isa<CXXRecordDecl>(D))
584     Record.push_back(D->getODRHash());
585 
586   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
587       !D->isImplicit() && !D->isInvalidDecl() && !D->hasExtInfo() &&
588       !D->getTypedefNameForAnonDecl() &&
589       D->getFirstDecl() == D->getMostRecentDecl() &&
590       !D->isTopLevelDeclInObjCContainer() &&
591       !CXXRecordDecl::classofKind(D->getKind()) &&
592       !needsAnonymousDeclarationNumber(D) &&
593       D->getDeclName().getNameKind() == DeclarationName::Identifier)
594     AbbrevToUse = Writer.getDeclRecordAbbrev();
595 
596   Code = serialization::DECL_RECORD;
597 }
598 
599 void ASTDeclWriter::VisitValueDecl(ValueDecl *D) {
600   VisitNamedDecl(D);
601   Record.AddTypeRef(D->getType());
602 }
603 
604 void ASTDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
605   VisitValueDecl(D);
606   Record.push_back(D->getInitExpr()? 1 : 0);
607   if (D->getInitExpr())
608     Record.AddStmt(D->getInitExpr());
609   Record.AddAPSInt(D->getInitVal());
610 
611   Code = serialization::DECL_ENUM_CONSTANT;
612 }
613 
614 void ASTDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) {
615   VisitValueDecl(D);
616   Record.AddSourceLocation(D->getInnerLocStart());
617   Record.push_back(D->hasExtInfo());
618   if (D->hasExtInfo()) {
619     DeclaratorDecl::ExtInfo *Info = D->getExtInfo();
620     Record.AddQualifierInfo(*Info);
621     Record.AddStmt(Info->TrailingRequiresClause);
622   }
623   // The location information is deferred until the end of the record.
624   Record.AddTypeRef(D->getTypeSourceInfo() ? D->getTypeSourceInfo()->getType()
625                                            : QualType());
626 }
627 
628 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
629   static_assert(DeclContext::NumFunctionDeclBits == 44,
630                 "You need to update the serializer after you change the "
631                 "FunctionDeclBits");
632 
633   VisitRedeclarable(D);
634 
635   Record.push_back(D->getTemplatedKind());
636   switch (D->getTemplatedKind()) {
637   case FunctionDecl::TK_NonTemplate:
638     break;
639   case FunctionDecl::TK_DependentNonTemplate:
640     Record.AddDeclRef(D->getInstantiatedFromDecl());
641     break;
642   case FunctionDecl::TK_FunctionTemplate:
643     Record.AddDeclRef(D->getDescribedFunctionTemplate());
644     break;
645   case FunctionDecl::TK_MemberSpecialization: {
646     MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo();
647     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
648     Record.push_back(MemberInfo->getTemplateSpecializationKind());
649     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
650     break;
651   }
652   case FunctionDecl::TK_FunctionTemplateSpecialization: {
653     FunctionTemplateSpecializationInfo *
654       FTSInfo = D->getTemplateSpecializationInfo();
655 
656     RegisterTemplateSpecialization(FTSInfo->getTemplate(), D);
657 
658     Record.AddDeclRef(FTSInfo->getTemplate());
659     Record.push_back(FTSInfo->getTemplateSpecializationKind());
660 
661     // Template arguments.
662     Record.AddTemplateArgumentList(FTSInfo->TemplateArguments);
663 
664     // Template args as written.
665     Record.push_back(FTSInfo->TemplateArgumentsAsWritten != nullptr);
666     if (FTSInfo->TemplateArgumentsAsWritten)
667       Record.AddASTTemplateArgumentListInfo(
668           FTSInfo->TemplateArgumentsAsWritten);
669 
670     Record.AddSourceLocation(FTSInfo->getPointOfInstantiation());
671 
672     if (MemberSpecializationInfo *MemberInfo =
673         FTSInfo->getMemberSpecializationInfo()) {
674       Record.push_back(1);
675       Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
676       Record.push_back(MemberInfo->getTemplateSpecializationKind());
677       Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
678     } else {
679       Record.push_back(0);
680     }
681 
682     if (D->isCanonicalDecl()) {
683       // Write the template that contains the specializations set. We will
684       // add a FunctionTemplateSpecializationInfo to it when reading.
685       Record.AddDeclRef(FTSInfo->getTemplate()->getCanonicalDecl());
686     }
687     break;
688   }
689   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
690     DependentFunctionTemplateSpecializationInfo *
691       DFTSInfo = D->getDependentSpecializationInfo();
692 
693     // Candidates.
694     Record.push_back(DFTSInfo->getCandidates().size());
695     for (FunctionTemplateDecl *FTD : DFTSInfo->getCandidates())
696       Record.AddDeclRef(FTD);
697 
698     // Templates args.
699     Record.push_back(DFTSInfo->TemplateArgumentsAsWritten != nullptr);
700     if (DFTSInfo->TemplateArgumentsAsWritten)
701       Record.AddASTTemplateArgumentListInfo(
702           DFTSInfo->TemplateArgumentsAsWritten);
703     break;
704   }
705   }
706 
707   VisitDeclaratorDecl(D);
708   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
709   Record.push_back(D->getIdentifierNamespace());
710 
711   // The order matters here. It will be better to put the bit with higher
712   // probability to be 0 in the end of the bits. See the comments in VisitDecl
713   // for details.
714   BitsPacker FunctionDeclBits;
715   // FIXME: stable encoding
716   FunctionDeclBits.addBits(llvm::to_underlying(D->getLinkageInternal()), 3);
717   FunctionDeclBits.addBits((uint32_t)D->getStorageClass(), /*BitWidth=*/3);
718   FunctionDeclBits.addBit(D->isInlineSpecified());
719   FunctionDeclBits.addBit(D->isInlined());
720   FunctionDeclBits.addBit(D->hasSkippedBody());
721   FunctionDeclBits.addBit(D->isVirtualAsWritten());
722   FunctionDeclBits.addBit(D->isPureVirtual());
723   FunctionDeclBits.addBit(D->hasInheritedPrototype());
724   FunctionDeclBits.addBit(D->hasWrittenPrototype());
725   FunctionDeclBits.addBit(D->isDeletedBit());
726   FunctionDeclBits.addBit(D->isTrivial());
727   FunctionDeclBits.addBit(D->isTrivialForCall());
728   FunctionDeclBits.addBit(D->isDefaulted());
729   FunctionDeclBits.addBit(D->isExplicitlyDefaulted());
730   FunctionDeclBits.addBit(D->isIneligibleOrNotSelected());
731   FunctionDeclBits.addBits((uint64_t)(D->getConstexprKind()), /*BitWidth=*/2);
732   FunctionDeclBits.addBit(D->hasImplicitReturnZero());
733   FunctionDeclBits.addBit(D->isMultiVersion());
734   FunctionDeclBits.addBit(D->isLateTemplateParsed());
735   FunctionDeclBits.addBit(D->FriendConstraintRefersToEnclosingTemplate());
736   FunctionDeclBits.addBit(D->usesSEHTry());
737   Record.push_back(FunctionDeclBits);
738 
739   Record.AddSourceLocation(D->getEndLoc());
740   if (D->isExplicitlyDefaulted())
741     Record.AddSourceLocation(D->getDefaultLoc());
742 
743   Record.push_back(D->getODRHash());
744 
745   if (D->isDefaulted() || D->isDeletedAsWritten()) {
746     if (auto *FDI = D->getDefalutedOrDeletedInfo()) {
747       // Store both that there is an DefaultedOrDeletedInfo and whether it
748       // contains a DeletedMessage.
749       StringLiteral *DeletedMessage = FDI->getDeletedMessage();
750       Record.push_back(1 | (DeletedMessage ? 2 : 0));
751       if (DeletedMessage)
752         Record.AddStmt(DeletedMessage);
753 
754       Record.push_back(FDI->getUnqualifiedLookups().size());
755       for (DeclAccessPair P : FDI->getUnqualifiedLookups()) {
756         Record.AddDeclRef(P.getDecl());
757         Record.push_back(P.getAccess());
758       }
759     } else {
760       Record.push_back(0);
761     }
762   }
763 
764   Record.push_back(D->param_size());
765   for (auto *P : D->parameters())
766     Record.AddDeclRef(P);
767   Code = serialization::DECL_FUNCTION;
768 }
769 
770 static void addExplicitSpecifier(ExplicitSpecifier ES,
771                                  ASTRecordWriter &Record) {
772   uint64_t Kind = static_cast<uint64_t>(ES.getKind());
773   Kind = Kind << 1 | static_cast<bool>(ES.getExpr());
774   Record.push_back(Kind);
775   if (ES.getExpr()) {
776     Record.AddStmt(ES.getExpr());
777   }
778 }
779 
780 void ASTDeclWriter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
781   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
782   Record.AddDeclRef(D->Ctor);
783   VisitFunctionDecl(D);
784   Record.push_back(static_cast<unsigned char>(D->getDeductionCandidateKind()));
785   Code = serialization::DECL_CXX_DEDUCTION_GUIDE;
786 }
787 
788 void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
789   static_assert(DeclContext::NumObjCMethodDeclBits == 37,
790                 "You need to update the serializer after you change the "
791                 "ObjCMethodDeclBits");
792 
793   VisitNamedDecl(D);
794   // FIXME: convert to LazyStmtPtr?
795   // Unlike C/C++, method bodies will never be in header files.
796   bool HasBodyStuff = D->getBody() != nullptr;
797   Record.push_back(HasBodyStuff);
798   if (HasBodyStuff) {
799     Record.AddStmt(D->getBody());
800   }
801   Record.AddDeclRef(D->getSelfDecl());
802   Record.AddDeclRef(D->getCmdDecl());
803   Record.push_back(D->isInstanceMethod());
804   Record.push_back(D->isVariadic());
805   Record.push_back(D->isPropertyAccessor());
806   Record.push_back(D->isSynthesizedAccessorStub());
807   Record.push_back(D->isDefined());
808   Record.push_back(D->isOverriding());
809   Record.push_back(D->hasSkippedBody());
810 
811   Record.push_back(D->isRedeclaration());
812   Record.push_back(D->hasRedeclaration());
813   if (D->hasRedeclaration()) {
814     assert(Context.getObjCMethodRedeclaration(D));
815     Record.AddDeclRef(Context.getObjCMethodRedeclaration(D));
816   }
817 
818   // FIXME: stable encoding for @required/@optional
819   Record.push_back(llvm::to_underlying(D->getImplementationControl()));
820   // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway/nullability
821   Record.push_back(D->getObjCDeclQualifier());
822   Record.push_back(D->hasRelatedResultType());
823   Record.AddTypeRef(D->getReturnType());
824   Record.AddTypeSourceInfo(D->getReturnTypeSourceInfo());
825   Record.AddSourceLocation(D->getEndLoc());
826   Record.push_back(D->param_size());
827   for (const auto *P : D->parameters())
828     Record.AddDeclRef(P);
829 
830   Record.push_back(D->getSelLocsKind());
831   unsigned NumStoredSelLocs = D->getNumStoredSelLocs();
832   SourceLocation *SelLocs = D->getStoredSelLocs();
833   Record.push_back(NumStoredSelLocs);
834   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
835     Record.AddSourceLocation(SelLocs[i]);
836 
837   Code = serialization::DECL_OBJC_METHOD;
838 }
839 
840 void ASTDeclWriter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
841   VisitTypedefNameDecl(D);
842   Record.push_back(D->Variance);
843   Record.push_back(D->Index);
844   Record.AddSourceLocation(D->VarianceLoc);
845   Record.AddSourceLocation(D->ColonLoc);
846 
847   Code = serialization::DECL_OBJC_TYPE_PARAM;
848 }
849 
850 void ASTDeclWriter::VisitObjCContainerDecl(ObjCContainerDecl *D) {
851   static_assert(DeclContext::NumObjCContainerDeclBits == 64,
852                 "You need to update the serializer after you change the "
853                 "ObjCContainerDeclBits");
854 
855   VisitNamedDecl(D);
856   Record.AddSourceLocation(D->getAtStartLoc());
857   Record.AddSourceRange(D->getAtEndRange());
858   // Abstract class (no need to define a stable serialization::DECL code).
859 }
860 
861 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
862   VisitRedeclarable(D);
863   VisitObjCContainerDecl(D);
864   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
865   AddObjCTypeParamList(D->TypeParamList);
866 
867   Record.push_back(D->isThisDeclarationADefinition());
868   if (D->isThisDeclarationADefinition()) {
869     // Write the DefinitionData
870     ObjCInterfaceDecl::DefinitionData &Data = D->data();
871 
872     Record.AddTypeSourceInfo(D->getSuperClassTInfo());
873     Record.AddSourceLocation(D->getEndOfDefinitionLoc());
874     Record.push_back(Data.HasDesignatedInitializers);
875     Record.push_back(D->getODRHash());
876 
877     // Write out the protocols that are directly referenced by the @interface.
878     Record.push_back(Data.ReferencedProtocols.size());
879     for (const auto *P : D->protocols())
880       Record.AddDeclRef(P);
881     for (const auto &PL : D->protocol_locs())
882       Record.AddSourceLocation(PL);
883 
884     // Write out the protocols that are transitively referenced.
885     Record.push_back(Data.AllReferencedProtocols.size());
886     for (ObjCList<ObjCProtocolDecl>::iterator
887               P = Data.AllReferencedProtocols.begin(),
888            PEnd = Data.AllReferencedProtocols.end();
889          P != PEnd; ++P)
890       Record.AddDeclRef(*P);
891 
892 
893     if (ObjCCategoryDecl *Cat = D->getCategoryListRaw()) {
894       // Ensure that we write out the set of categories for this class.
895       Writer.ObjCClassesWithCategories.insert(D);
896 
897       // Make sure that the categories get serialized.
898       for (; Cat; Cat = Cat->getNextClassCategoryRaw())
899         (void)Writer.GetDeclRef(Cat);
900     }
901   }
902 
903   Code = serialization::DECL_OBJC_INTERFACE;
904 }
905 
906 void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
907   VisitFieldDecl(D);
908   // FIXME: stable encoding for @public/@private/@protected/@package
909   Record.push_back(D->getAccessControl());
910   Record.push_back(D->getSynthesize());
911 
912   if (D->getDeclContext() == D->getLexicalDeclContext() &&
913       !D->hasAttrs() &&
914       !D->isImplicit() &&
915       !D->isUsed(false) &&
916       !D->isInvalidDecl() &&
917       !D->isReferenced() &&
918       !D->isModulePrivate() &&
919       !D->getBitWidth() &&
920       !D->hasExtInfo() &&
921       D->getDeclName())
922     AbbrevToUse = Writer.getDeclObjCIvarAbbrev();
923 
924   Code = serialization::DECL_OBJC_IVAR;
925 }
926 
927 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
928   VisitRedeclarable(D);
929   VisitObjCContainerDecl(D);
930 
931   Record.push_back(D->isThisDeclarationADefinition());
932   if (D->isThisDeclarationADefinition()) {
933     Record.push_back(D->protocol_size());
934     for (const auto *I : D->protocols())
935       Record.AddDeclRef(I);
936     for (const auto &PL : D->protocol_locs())
937       Record.AddSourceLocation(PL);
938     Record.push_back(D->getODRHash());
939   }
940 
941   Code = serialization::DECL_OBJC_PROTOCOL;
942 }
943 
944 void ASTDeclWriter::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
945   VisitFieldDecl(D);
946   Code = serialization::DECL_OBJC_AT_DEFS_FIELD;
947 }
948 
949 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
950   VisitObjCContainerDecl(D);
951   Record.AddSourceLocation(D->getCategoryNameLoc());
952   Record.AddSourceLocation(D->getIvarLBraceLoc());
953   Record.AddSourceLocation(D->getIvarRBraceLoc());
954   Record.AddDeclRef(D->getClassInterface());
955   AddObjCTypeParamList(D->TypeParamList);
956   Record.push_back(D->protocol_size());
957   for (const auto *I : D->protocols())
958     Record.AddDeclRef(I);
959   for (const auto &PL : D->protocol_locs())
960     Record.AddSourceLocation(PL);
961   Code = serialization::DECL_OBJC_CATEGORY;
962 }
963 
964 void ASTDeclWriter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D) {
965   VisitNamedDecl(D);
966   Record.AddDeclRef(D->getClassInterface());
967   Code = serialization::DECL_OBJC_COMPATIBLE_ALIAS;
968 }
969 
970 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
971   VisitNamedDecl(D);
972   Record.AddSourceLocation(D->getAtLoc());
973   Record.AddSourceLocation(D->getLParenLoc());
974   Record.AddTypeRef(D->getType());
975   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
976   // FIXME: stable encoding
977   Record.push_back((unsigned)D->getPropertyAttributes());
978   Record.push_back((unsigned)D->getPropertyAttributesAsWritten());
979   // FIXME: stable encoding
980   Record.push_back((unsigned)D->getPropertyImplementation());
981   Record.AddDeclarationName(D->getGetterName());
982   Record.AddSourceLocation(D->getGetterNameLoc());
983   Record.AddDeclarationName(D->getSetterName());
984   Record.AddSourceLocation(D->getSetterNameLoc());
985   Record.AddDeclRef(D->getGetterMethodDecl());
986   Record.AddDeclRef(D->getSetterMethodDecl());
987   Record.AddDeclRef(D->getPropertyIvarDecl());
988   Code = serialization::DECL_OBJC_PROPERTY;
989 }
990 
991 void ASTDeclWriter::VisitObjCImplDecl(ObjCImplDecl *D) {
992   VisitObjCContainerDecl(D);
993   Record.AddDeclRef(D->getClassInterface());
994   // Abstract class (no need to define a stable serialization::DECL code).
995 }
996 
997 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
998   VisitObjCImplDecl(D);
999   Record.AddSourceLocation(D->getCategoryNameLoc());
1000   Code = serialization::DECL_OBJC_CATEGORY_IMPL;
1001 }
1002 
1003 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1004   VisitObjCImplDecl(D);
1005   Record.AddDeclRef(D->getSuperClass());
1006   Record.AddSourceLocation(D->getSuperClassLoc());
1007   Record.AddSourceLocation(D->getIvarLBraceLoc());
1008   Record.AddSourceLocation(D->getIvarRBraceLoc());
1009   Record.push_back(D->hasNonZeroConstructors());
1010   Record.push_back(D->hasDestructors());
1011   Record.push_back(D->NumIvarInitializers);
1012   if (D->NumIvarInitializers)
1013     Record.AddCXXCtorInitializers(
1014         llvm::ArrayRef(D->init_begin(), D->init_end()));
1015   Code = serialization::DECL_OBJC_IMPLEMENTATION;
1016 }
1017 
1018 void ASTDeclWriter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1019   VisitDecl(D);
1020   Record.AddSourceLocation(D->getBeginLoc());
1021   Record.AddDeclRef(D->getPropertyDecl());
1022   Record.AddDeclRef(D->getPropertyIvarDecl());
1023   Record.AddSourceLocation(D->getPropertyIvarDeclLoc());
1024   Record.AddDeclRef(D->getGetterMethodDecl());
1025   Record.AddDeclRef(D->getSetterMethodDecl());
1026   Record.AddStmt(D->getGetterCXXConstructor());
1027   Record.AddStmt(D->getSetterCXXAssignment());
1028   Code = serialization::DECL_OBJC_PROPERTY_IMPL;
1029 }
1030 
1031 void ASTDeclWriter::VisitFieldDecl(FieldDecl *D) {
1032   VisitDeclaratorDecl(D);
1033   Record.push_back(D->isMutable());
1034 
1035   Record.push_back((D->StorageKind << 1) | D->BitField);
1036   if (D->StorageKind == FieldDecl::ISK_CapturedVLAType)
1037     Record.AddTypeRef(QualType(D->getCapturedVLAType(), 0));
1038   else if (D->BitField)
1039     Record.AddStmt(D->getBitWidth());
1040 
1041   if (!D->getDeclName())
1042     Record.AddDeclRef(Context.getInstantiatedFromUnnamedFieldDecl(D));
1043 
1044   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1045       !D->hasAttrs() &&
1046       !D->isImplicit() &&
1047       !D->isUsed(false) &&
1048       !D->isInvalidDecl() &&
1049       !D->isReferenced() &&
1050       !D->isTopLevelDeclInObjCContainer() &&
1051       !D->isModulePrivate() &&
1052       !D->getBitWidth() &&
1053       !D->hasInClassInitializer() &&
1054       !D->hasCapturedVLAType() &&
1055       !D->hasExtInfo() &&
1056       !ObjCIvarDecl::classofKind(D->getKind()) &&
1057       !ObjCAtDefsFieldDecl::classofKind(D->getKind()) &&
1058       D->getDeclName())
1059     AbbrevToUse = Writer.getDeclFieldAbbrev();
1060 
1061   Code = serialization::DECL_FIELD;
1062 }
1063 
1064 void ASTDeclWriter::VisitMSPropertyDecl(MSPropertyDecl *D) {
1065   VisitDeclaratorDecl(D);
1066   Record.AddIdentifierRef(D->getGetterId());
1067   Record.AddIdentifierRef(D->getSetterId());
1068   Code = serialization::DECL_MS_PROPERTY;
1069 }
1070 
1071 void ASTDeclWriter::VisitMSGuidDecl(MSGuidDecl *D) {
1072   VisitValueDecl(D);
1073   MSGuidDecl::Parts Parts = D->getParts();
1074   Record.push_back(Parts.Part1);
1075   Record.push_back(Parts.Part2);
1076   Record.push_back(Parts.Part3);
1077   Record.append(std::begin(Parts.Part4And5), std::end(Parts.Part4And5));
1078   Code = serialization::DECL_MS_GUID;
1079 }
1080 
1081 void ASTDeclWriter::VisitUnnamedGlobalConstantDecl(
1082     UnnamedGlobalConstantDecl *D) {
1083   VisitValueDecl(D);
1084   Record.AddAPValue(D->getValue());
1085   Code = serialization::DECL_UNNAMED_GLOBAL_CONSTANT;
1086 }
1087 
1088 void ASTDeclWriter::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1089   VisitValueDecl(D);
1090   Record.AddAPValue(D->getValue());
1091   Code = serialization::DECL_TEMPLATE_PARAM_OBJECT;
1092 }
1093 
1094 void ASTDeclWriter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1095   VisitValueDecl(D);
1096   Record.push_back(D->getChainingSize());
1097 
1098   for (const auto *P : D->chain())
1099     Record.AddDeclRef(P);
1100   Code = serialization::DECL_INDIRECTFIELD;
1101 }
1102 
1103 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
1104   VisitRedeclarable(D);
1105   VisitDeclaratorDecl(D);
1106 
1107   // The order matters here. It will be better to put the bit with higher
1108   // probability to be 0 in the end of the bits. See the comments in VisitDecl
1109   // for details.
1110   BitsPacker VarDeclBits;
1111   VarDeclBits.addBits(llvm::to_underlying(D->getLinkageInternal()),
1112                       /*BitWidth=*/3);
1113 
1114   bool ModulesCodegen = false;
1115   if (Writer.WritingModule && D->getStorageDuration() == SD_Static &&
1116       !D->getDescribedVarTemplate()) {
1117     // When building a C++20 module interface unit or a partition unit, a
1118     // strong definition in the module interface is provided by the
1119     // compilation of that unit, not by its users. (Inline variables are still
1120     // emitted in module users.)
1121     ModulesCodegen =
1122         (Writer.WritingModule->isInterfaceOrPartition() ||
1123          (D->hasAttr<DLLExportAttr>() &&
1124           Writer.Context->getLangOpts().BuildingPCHWithObjectFile)) &&
1125         Writer.Context->GetGVALinkageForVariable(D) >= GVA_StrongExternal;
1126   }
1127   VarDeclBits.addBit(ModulesCodegen);
1128 
1129   VarDeclBits.addBits(D->getStorageClass(), /*BitWidth=*/3);
1130   VarDeclBits.addBits(D->getTSCSpec(), /*BitWidth=*/2);
1131   VarDeclBits.addBits(D->getInitStyle(), /*BitWidth=*/2);
1132   VarDeclBits.addBit(D->isARCPseudoStrong());
1133 
1134   bool HasDeducedType = false;
1135   if (!isa<ParmVarDecl>(D)) {
1136     VarDeclBits.addBit(D->isThisDeclarationADemotedDefinition());
1137     VarDeclBits.addBit(D->isExceptionVariable());
1138     VarDeclBits.addBit(D->isNRVOVariable());
1139     VarDeclBits.addBit(D->isCXXForRangeDecl());
1140 
1141     VarDeclBits.addBit(D->isInline());
1142     VarDeclBits.addBit(D->isInlineSpecified());
1143     VarDeclBits.addBit(D->isConstexpr());
1144     VarDeclBits.addBit(D->isInitCapture());
1145     VarDeclBits.addBit(D->isPreviousDeclInSameBlockScope());
1146 
1147     VarDeclBits.addBit(D->isEscapingByref());
1148     HasDeducedType = D->getType()->getContainedDeducedType();
1149     VarDeclBits.addBit(HasDeducedType);
1150 
1151     if (const auto *IPD = dyn_cast<ImplicitParamDecl>(D))
1152       VarDeclBits.addBits(llvm::to_underlying(IPD->getParameterKind()),
1153                           /*Width=*/3);
1154     else
1155       VarDeclBits.addBits(0, /*Width=*/3);
1156 
1157     VarDeclBits.addBit(D->isObjCForDecl());
1158   }
1159 
1160   Record.push_back(VarDeclBits);
1161 
1162   if (ModulesCodegen)
1163     Writer.AddDeclRef(D, Writer.ModularCodegenDecls);
1164 
1165   if (D->hasAttr<BlocksAttr>()) {
1166     BlockVarCopyInit Init = Writer.Context->getBlockVarCopyInit(D);
1167     Record.AddStmt(Init.getCopyExpr());
1168     if (Init.getCopyExpr())
1169       Record.push_back(Init.canThrow());
1170   }
1171 
1172   enum {
1173     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1174   };
1175   if (VarTemplateDecl *TemplD = D->getDescribedVarTemplate()) {
1176     Record.push_back(VarTemplate);
1177     Record.AddDeclRef(TemplD);
1178   } else if (MemberSpecializationInfo *SpecInfo
1179                = D->getMemberSpecializationInfo()) {
1180     Record.push_back(StaticDataMemberSpecialization);
1181     Record.AddDeclRef(SpecInfo->getInstantiatedFrom());
1182     Record.push_back(SpecInfo->getTemplateSpecializationKind());
1183     Record.AddSourceLocation(SpecInfo->getPointOfInstantiation());
1184   } else {
1185     Record.push_back(VarNotTemplate);
1186   }
1187 
1188   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
1189       !D->isTopLevelDeclInObjCContainer() &&
1190       !needsAnonymousDeclarationNumber(D) &&
1191       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
1192       !D->hasExtInfo() && D->getFirstDecl() == D->getMostRecentDecl() &&
1193       D->getKind() == Decl::Var && !D->isInline() && !D->isConstexpr() &&
1194       !D->isInitCapture() && !D->isPreviousDeclInSameBlockScope() &&
1195       !D->isEscapingByref() && !HasDeducedType &&
1196       D->getStorageDuration() != SD_Static && !D->getDescribedVarTemplate() &&
1197       !D->getMemberSpecializationInfo() && !D->isObjCForDecl() &&
1198       !isa<ImplicitParamDecl>(D) && !D->isEscapingByref())
1199     AbbrevToUse = Writer.getDeclVarAbbrev();
1200 
1201   Code = serialization::DECL_VAR;
1202 }
1203 
1204 void ASTDeclWriter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
1205   VisitVarDecl(D);
1206   Code = serialization::DECL_IMPLICIT_PARAM;
1207 }
1208 
1209 void ASTDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
1210   VisitVarDecl(D);
1211 
1212   // See the implementation of `ParmVarDecl::getParameterIndex()`, which may
1213   // exceed the size of the normal bitfield. So it may be better to not pack
1214   // these bits.
1215   Record.push_back(D->getFunctionScopeIndex());
1216 
1217   BitsPacker ParmVarDeclBits;
1218   ParmVarDeclBits.addBit(D->isObjCMethodParameter());
1219   ParmVarDeclBits.addBits(D->getFunctionScopeDepth(), /*BitsWidth=*/7);
1220   // FIXME: stable encoding
1221   ParmVarDeclBits.addBits(D->getObjCDeclQualifier(), /*BitsWidth=*/7);
1222   ParmVarDeclBits.addBit(D->isKNRPromoted());
1223   ParmVarDeclBits.addBit(D->hasInheritedDefaultArg());
1224   ParmVarDeclBits.addBit(D->hasUninstantiatedDefaultArg());
1225   ParmVarDeclBits.addBit(D->getExplicitObjectParamThisLoc().isValid());
1226   Record.push_back(ParmVarDeclBits);
1227 
1228   if (D->hasUninstantiatedDefaultArg())
1229     Record.AddStmt(D->getUninstantiatedDefaultArg());
1230   if (D->getExplicitObjectParamThisLoc().isValid())
1231     Record.AddSourceLocation(D->getExplicitObjectParamThisLoc());
1232   Code = serialization::DECL_PARM_VAR;
1233 
1234   // If the assumptions about the DECL_PARM_VAR abbrev are true, use it.  Here
1235   // we dynamically check for the properties that we optimize for, but don't
1236   // know are true of all PARM_VAR_DECLs.
1237   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
1238       !D->hasExtInfo() && D->getStorageClass() == 0 && !D->isInvalidDecl() &&
1239       !D->isTopLevelDeclInObjCContainer() &&
1240       D->getInitStyle() == VarDecl::CInit && // Can params have anything else?
1241       D->getInit() == nullptr)               // No default expr.
1242     AbbrevToUse = Writer.getDeclParmVarAbbrev();
1243 
1244   // Check things we know are true of *every* PARM_VAR_DECL, which is more than
1245   // just us assuming it.
1246   assert(!D->getTSCSpec() && "PARM_VAR_DECL can't use TLS");
1247   assert(!D->isThisDeclarationADemotedDefinition()
1248          && "PARM_VAR_DECL can't be demoted definition.");
1249   assert(D->getAccess() == AS_none && "PARM_VAR_DECL can't be public/private");
1250   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception var");
1251   assert(D->getPreviousDecl() == nullptr && "PARM_VAR_DECL can't be redecl");
1252   assert(!D->isStaticDataMember() &&
1253          "PARM_VAR_DECL can't be static data member");
1254 }
1255 
1256 void ASTDeclWriter::VisitDecompositionDecl(DecompositionDecl *D) {
1257   // Record the number of bindings first to simplify deserialization.
1258   Record.push_back(D->bindings().size());
1259 
1260   VisitVarDecl(D);
1261   for (auto *B : D->bindings())
1262     Record.AddDeclRef(B);
1263   Code = serialization::DECL_DECOMPOSITION;
1264 }
1265 
1266 void ASTDeclWriter::VisitBindingDecl(BindingDecl *D) {
1267   VisitValueDecl(D);
1268   Record.AddStmt(D->getBinding());
1269   Code = serialization::DECL_BINDING;
1270 }
1271 
1272 void ASTDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
1273   VisitDecl(D);
1274   Record.AddStmt(D->getAsmString());
1275   Record.AddSourceLocation(D->getRParenLoc());
1276   Code = serialization::DECL_FILE_SCOPE_ASM;
1277 }
1278 
1279 void ASTDeclWriter::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {
1280   VisitDecl(D);
1281   Record.AddStmt(D->getStmt());
1282   Code = serialization::DECL_TOP_LEVEL_STMT_DECL;
1283 }
1284 
1285 void ASTDeclWriter::VisitEmptyDecl(EmptyDecl *D) {
1286   VisitDecl(D);
1287   Code = serialization::DECL_EMPTY;
1288 }
1289 
1290 void ASTDeclWriter::VisitLifetimeExtendedTemporaryDecl(
1291     LifetimeExtendedTemporaryDecl *D) {
1292   VisitDecl(D);
1293   Record.AddDeclRef(D->getExtendingDecl());
1294   Record.AddStmt(D->getTemporaryExpr());
1295   Record.push_back(static_cast<bool>(D->getValue()));
1296   if (D->getValue())
1297     Record.AddAPValue(*D->getValue());
1298   Record.push_back(D->getManglingNumber());
1299   Code = serialization::DECL_LIFETIME_EXTENDED_TEMPORARY;
1300 }
1301 void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) {
1302   VisitDecl(D);
1303   Record.AddStmt(D->getBody());
1304   Record.AddTypeSourceInfo(D->getSignatureAsWritten());
1305   Record.push_back(D->param_size());
1306   for (ParmVarDecl *P : D->parameters())
1307     Record.AddDeclRef(P);
1308   Record.push_back(D->isVariadic());
1309   Record.push_back(D->blockMissingReturnType());
1310   Record.push_back(D->isConversionFromLambda());
1311   Record.push_back(D->doesNotEscape());
1312   Record.push_back(D->canAvoidCopyToHeap());
1313   Record.push_back(D->capturesCXXThis());
1314   Record.push_back(D->getNumCaptures());
1315   for (const auto &capture : D->captures()) {
1316     Record.AddDeclRef(capture.getVariable());
1317 
1318     unsigned flags = 0;
1319     if (capture.isByRef()) flags |= 1;
1320     if (capture.isNested()) flags |= 2;
1321     if (capture.hasCopyExpr()) flags |= 4;
1322     Record.push_back(flags);
1323 
1324     if (capture.hasCopyExpr()) Record.AddStmt(capture.getCopyExpr());
1325   }
1326 
1327   Code = serialization::DECL_BLOCK;
1328 }
1329 
1330 void ASTDeclWriter::VisitCapturedDecl(CapturedDecl *CD) {
1331   Record.push_back(CD->getNumParams());
1332   VisitDecl(CD);
1333   Record.push_back(CD->getContextParamPosition());
1334   Record.push_back(CD->isNothrow() ? 1 : 0);
1335   // Body is stored by VisitCapturedStmt.
1336   for (unsigned I = 0; I < CD->getNumParams(); ++I)
1337     Record.AddDeclRef(CD->getParam(I));
1338   Code = serialization::DECL_CAPTURED;
1339 }
1340 
1341 void ASTDeclWriter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1342   static_assert(DeclContext::NumLinkageSpecDeclBits == 17,
1343                 "You need to update the serializer after you change the"
1344                 "LinkageSpecDeclBits");
1345 
1346   VisitDecl(D);
1347   Record.push_back(llvm::to_underlying(D->getLanguage()));
1348   Record.AddSourceLocation(D->getExternLoc());
1349   Record.AddSourceLocation(D->getRBraceLoc());
1350   Code = serialization::DECL_LINKAGE_SPEC;
1351 }
1352 
1353 void ASTDeclWriter::VisitExportDecl(ExportDecl *D) {
1354   VisitDecl(D);
1355   Record.AddSourceLocation(D->getRBraceLoc());
1356   Code = serialization::DECL_EXPORT;
1357 }
1358 
1359 void ASTDeclWriter::VisitLabelDecl(LabelDecl *D) {
1360   VisitNamedDecl(D);
1361   Record.AddSourceLocation(D->getBeginLoc());
1362   Code = serialization::DECL_LABEL;
1363 }
1364 
1365 
1366 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
1367   VisitRedeclarable(D);
1368   VisitNamedDecl(D);
1369 
1370   BitsPacker NamespaceDeclBits;
1371   NamespaceDeclBits.addBit(D->isInline());
1372   NamespaceDeclBits.addBit(D->isNested());
1373   Record.push_back(NamespaceDeclBits);
1374 
1375   Record.AddSourceLocation(D->getBeginLoc());
1376   Record.AddSourceLocation(D->getRBraceLoc());
1377 
1378   if (D->isFirstDecl())
1379     Record.AddDeclRef(D->getAnonymousNamespace());
1380   Code = serialization::DECL_NAMESPACE;
1381 
1382   if (Writer.hasChain() && D->isAnonymousNamespace() &&
1383       D == D->getMostRecentDecl()) {
1384     // This is a most recent reopening of the anonymous namespace. If its parent
1385     // is in a previous PCH (or is the TU), mark that parent for update, because
1386     // the original namespace always points to the latest re-opening of its
1387     // anonymous namespace.
1388     Decl *Parent = cast<Decl>(
1389         D->getParent()->getRedeclContext()->getPrimaryContext());
1390     if (Parent->isFromASTFile() || isa<TranslationUnitDecl>(Parent)) {
1391       Writer.DeclUpdates[Parent].push_back(
1392           ASTWriter::DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, D));
1393     }
1394   }
1395 }
1396 
1397 void ASTDeclWriter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1398   VisitRedeclarable(D);
1399   VisitNamedDecl(D);
1400   Record.AddSourceLocation(D->getNamespaceLoc());
1401   Record.AddSourceLocation(D->getTargetNameLoc());
1402   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1403   Record.AddDeclRef(D->getNamespace());
1404   Code = serialization::DECL_NAMESPACE_ALIAS;
1405 }
1406 
1407 void ASTDeclWriter::VisitUsingDecl(UsingDecl *D) {
1408   VisitNamedDecl(D);
1409   Record.AddSourceLocation(D->getUsingLoc());
1410   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1411   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1412   Record.AddDeclRef(D->FirstUsingShadow.getPointer());
1413   Record.push_back(D->hasTypename());
1414   Record.AddDeclRef(Context.getInstantiatedFromUsingDecl(D));
1415   Code = serialization::DECL_USING;
1416 }
1417 
1418 void ASTDeclWriter::VisitUsingEnumDecl(UsingEnumDecl *D) {
1419   VisitNamedDecl(D);
1420   Record.AddSourceLocation(D->getUsingLoc());
1421   Record.AddSourceLocation(D->getEnumLoc());
1422   Record.AddTypeSourceInfo(D->getEnumType());
1423   Record.AddDeclRef(D->FirstUsingShadow.getPointer());
1424   Record.AddDeclRef(Context.getInstantiatedFromUsingEnumDecl(D));
1425   Code = serialization::DECL_USING_ENUM;
1426 }
1427 
1428 void ASTDeclWriter::VisitUsingPackDecl(UsingPackDecl *D) {
1429   Record.push_back(D->NumExpansions);
1430   VisitNamedDecl(D);
1431   Record.AddDeclRef(D->getInstantiatedFromUsingDecl());
1432   for (auto *E : D->expansions())
1433     Record.AddDeclRef(E);
1434   Code = serialization::DECL_USING_PACK;
1435 }
1436 
1437 void ASTDeclWriter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1438   VisitRedeclarable(D);
1439   VisitNamedDecl(D);
1440   Record.AddDeclRef(D->getTargetDecl());
1441   Record.push_back(D->getIdentifierNamespace());
1442   Record.AddDeclRef(D->UsingOrNextShadow);
1443   Record.AddDeclRef(Context.getInstantiatedFromUsingShadowDecl(D));
1444 
1445   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1446       D->getFirstDecl() == D->getMostRecentDecl() && !D->hasAttrs() &&
1447       !needsAnonymousDeclarationNumber(D) &&
1448       D->getDeclName().getNameKind() == DeclarationName::Identifier)
1449     AbbrevToUse = Writer.getDeclUsingShadowAbbrev();
1450 
1451   Code = serialization::DECL_USING_SHADOW;
1452 }
1453 
1454 void ASTDeclWriter::VisitConstructorUsingShadowDecl(
1455     ConstructorUsingShadowDecl *D) {
1456   VisitUsingShadowDecl(D);
1457   Record.AddDeclRef(D->NominatedBaseClassShadowDecl);
1458   Record.AddDeclRef(D->ConstructedBaseClassShadowDecl);
1459   Record.push_back(D->IsVirtual);
1460   Code = serialization::DECL_CONSTRUCTOR_USING_SHADOW;
1461 }
1462 
1463 void ASTDeclWriter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1464   VisitNamedDecl(D);
1465   Record.AddSourceLocation(D->getUsingLoc());
1466   Record.AddSourceLocation(D->getNamespaceKeyLocation());
1467   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1468   Record.AddDeclRef(D->getNominatedNamespace());
1469   Record.AddDeclRef(dyn_cast<Decl>(D->getCommonAncestor()));
1470   Code = serialization::DECL_USING_DIRECTIVE;
1471 }
1472 
1473 void ASTDeclWriter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1474   VisitValueDecl(D);
1475   Record.AddSourceLocation(D->getUsingLoc());
1476   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1477   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1478   Record.AddSourceLocation(D->getEllipsisLoc());
1479   Code = serialization::DECL_UNRESOLVED_USING_VALUE;
1480 }
1481 
1482 void ASTDeclWriter::VisitUnresolvedUsingTypenameDecl(
1483                                                UnresolvedUsingTypenameDecl *D) {
1484   VisitTypeDecl(D);
1485   Record.AddSourceLocation(D->getTypenameLoc());
1486   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1487   Record.AddSourceLocation(D->getEllipsisLoc());
1488   Code = serialization::DECL_UNRESOLVED_USING_TYPENAME;
1489 }
1490 
1491 void ASTDeclWriter::VisitUnresolvedUsingIfExistsDecl(
1492     UnresolvedUsingIfExistsDecl *D) {
1493   VisitNamedDecl(D);
1494   Code = serialization::DECL_UNRESOLVED_USING_IF_EXISTS;
1495 }
1496 
1497 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
1498   VisitRecordDecl(D);
1499 
1500   enum {
1501     CXXRecNotTemplate = 0,
1502     CXXRecTemplate,
1503     CXXRecMemberSpecialization,
1504     CXXLambda
1505   };
1506   if (ClassTemplateDecl *TemplD = D->getDescribedClassTemplate()) {
1507     Record.push_back(CXXRecTemplate);
1508     Record.AddDeclRef(TemplD);
1509   } else if (MemberSpecializationInfo *MSInfo
1510                = D->getMemberSpecializationInfo()) {
1511     Record.push_back(CXXRecMemberSpecialization);
1512     Record.AddDeclRef(MSInfo->getInstantiatedFrom());
1513     Record.push_back(MSInfo->getTemplateSpecializationKind());
1514     Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
1515   } else if (D->isLambda()) {
1516     // For a lambda, we need some information early for merging.
1517     Record.push_back(CXXLambda);
1518     if (auto *Context = D->getLambdaContextDecl()) {
1519       Record.AddDeclRef(Context);
1520       Record.push_back(D->getLambdaIndexInContext());
1521     } else {
1522       Record.push_back(0);
1523     }
1524   } else {
1525     Record.push_back(CXXRecNotTemplate);
1526   }
1527 
1528   Record.push_back(D->isThisDeclarationADefinition());
1529   if (D->isThisDeclarationADefinition())
1530     Record.AddCXXDefinitionData(D);
1531 
1532   if (D->isCompleteDefinition() && D->isInNamedModule())
1533     Writer.AddDeclRef(D, Writer.ModularCodegenDecls);
1534 
1535   // Store (what we currently believe to be) the key function to avoid
1536   // deserializing every method so we can compute it.
1537   //
1538   // FIXME: Avoid adding the key function if the class is defined in
1539   // module purview since in that case the key function is meaningless.
1540   if (D->isCompleteDefinition())
1541     Record.AddDeclRef(Context.getCurrentKeyFunction(D));
1542 
1543   Code = serialization::DECL_CXX_RECORD;
1544 }
1545 
1546 void ASTDeclWriter::VisitCXXMethodDecl(CXXMethodDecl *D) {
1547   VisitFunctionDecl(D);
1548   if (D->isCanonicalDecl()) {
1549     Record.push_back(D->size_overridden_methods());
1550     for (const CXXMethodDecl *MD : D->overridden_methods())
1551       Record.AddDeclRef(MD);
1552   } else {
1553     // We only need to record overridden methods once for the canonical decl.
1554     Record.push_back(0);
1555   }
1556 
1557   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1558       D->getFirstDecl() == D->getMostRecentDecl() && !D->isInvalidDecl() &&
1559       !D->hasAttrs() && !D->isTopLevelDeclInObjCContainer() &&
1560       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
1561       !D->hasExtInfo() && !D->isExplicitlyDefaulted()) {
1562     if (D->getTemplatedKind() == FunctionDecl::TK_NonTemplate ||
1563         D->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate ||
1564         D->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
1565         D->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
1566       AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1567     else if (D->getTemplatedKind() ==
1568              FunctionDecl::TK_FunctionTemplateSpecialization) {
1569       FunctionTemplateSpecializationInfo *FTSInfo =
1570           D->getTemplateSpecializationInfo();
1571 
1572       if (FTSInfo->TemplateArguments->size() == 1) {
1573         const TemplateArgument &TA = FTSInfo->TemplateArguments->get(0);
1574         if (TA.getKind() == TemplateArgument::Type &&
1575             !FTSInfo->TemplateArgumentsAsWritten &&
1576             !FTSInfo->getMemberSpecializationInfo())
1577           AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1578       }
1579     } else if (D->getTemplatedKind() ==
1580                FunctionDecl::TK_DependentFunctionTemplateSpecialization) {
1581       DependentFunctionTemplateSpecializationInfo *DFTSInfo =
1582           D->getDependentSpecializationInfo();
1583       if (!DFTSInfo->TemplateArgumentsAsWritten)
1584         AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1585     }
1586   }
1587 
1588   Code = serialization::DECL_CXX_METHOD;
1589 }
1590 
1591 void ASTDeclWriter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1592   static_assert(DeclContext::NumCXXConstructorDeclBits == 64,
1593                 "You need to update the serializer after you change the "
1594                 "CXXConstructorDeclBits");
1595 
1596   Record.push_back(D->getTrailingAllocKind());
1597   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
1598   if (auto Inherited = D->getInheritedConstructor()) {
1599     Record.AddDeclRef(Inherited.getShadowDecl());
1600     Record.AddDeclRef(Inherited.getConstructor());
1601   }
1602 
1603   VisitCXXMethodDecl(D);
1604   Code = serialization::DECL_CXX_CONSTRUCTOR;
1605 }
1606 
1607 void ASTDeclWriter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1608   VisitCXXMethodDecl(D);
1609 
1610   Record.AddDeclRef(D->getOperatorDelete());
1611   if (D->getOperatorDelete())
1612     Record.AddStmt(D->getOperatorDeleteThisArg());
1613 
1614   Code = serialization::DECL_CXX_DESTRUCTOR;
1615 }
1616 
1617 void ASTDeclWriter::VisitCXXConversionDecl(CXXConversionDecl *D) {
1618   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
1619   VisitCXXMethodDecl(D);
1620   Code = serialization::DECL_CXX_CONVERSION;
1621 }
1622 
1623 void ASTDeclWriter::VisitImportDecl(ImportDecl *D) {
1624   VisitDecl(D);
1625   Record.push_back(Writer.getSubmoduleID(D->getImportedModule()));
1626   ArrayRef<SourceLocation> IdentifierLocs = D->getIdentifierLocs();
1627   Record.push_back(!IdentifierLocs.empty());
1628   if (IdentifierLocs.empty()) {
1629     Record.AddSourceLocation(D->getEndLoc());
1630     Record.push_back(1);
1631   } else {
1632     for (unsigned I = 0, N = IdentifierLocs.size(); I != N; ++I)
1633       Record.AddSourceLocation(IdentifierLocs[I]);
1634     Record.push_back(IdentifierLocs.size());
1635   }
1636   // Note: the number of source locations must always be the last element in
1637   // the record.
1638   Code = serialization::DECL_IMPORT;
1639 }
1640 
1641 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1642   VisitDecl(D);
1643   Record.AddSourceLocation(D->getColonLoc());
1644   Code = serialization::DECL_ACCESS_SPEC;
1645 }
1646 
1647 void ASTDeclWriter::VisitFriendDecl(FriendDecl *D) {
1648   // Record the number of friend type template parameter lists here
1649   // so as to simplify memory allocation during deserialization.
1650   Record.push_back(D->NumTPLists);
1651   VisitDecl(D);
1652   bool hasFriendDecl = D->Friend.is<NamedDecl*>();
1653   Record.push_back(hasFriendDecl);
1654   if (hasFriendDecl)
1655     Record.AddDeclRef(D->getFriendDecl());
1656   else
1657     Record.AddTypeSourceInfo(D->getFriendType());
1658   for (unsigned i = 0; i < D->NumTPLists; ++i)
1659     Record.AddTemplateParameterList(D->getFriendTypeTemplateParameterList(i));
1660   Record.AddDeclRef(D->getNextFriend());
1661   Record.push_back(D->UnsupportedFriend);
1662   Record.AddSourceLocation(D->FriendLoc);
1663   Code = serialization::DECL_FRIEND;
1664 }
1665 
1666 void ASTDeclWriter::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1667   VisitDecl(D);
1668   Record.push_back(D->getNumTemplateParameters());
1669   for (unsigned i = 0, e = D->getNumTemplateParameters(); i != e; ++i)
1670     Record.AddTemplateParameterList(D->getTemplateParameterList(i));
1671   Record.push_back(D->getFriendDecl() != nullptr);
1672   if (D->getFriendDecl())
1673     Record.AddDeclRef(D->getFriendDecl());
1674   else
1675     Record.AddTypeSourceInfo(D->getFriendType());
1676   Record.AddSourceLocation(D->getFriendLoc());
1677   Code = serialization::DECL_FRIEND_TEMPLATE;
1678 }
1679 
1680 void ASTDeclWriter::VisitTemplateDecl(TemplateDecl *D) {
1681   VisitNamedDecl(D);
1682 
1683   Record.AddTemplateParameterList(D->getTemplateParameters());
1684   Record.AddDeclRef(D->getTemplatedDecl());
1685 }
1686 
1687 void ASTDeclWriter::VisitConceptDecl(ConceptDecl *D) {
1688   VisitTemplateDecl(D);
1689   Record.AddStmt(D->getConstraintExpr());
1690   Code = serialization::DECL_CONCEPT;
1691 }
1692 
1693 void ASTDeclWriter::VisitImplicitConceptSpecializationDecl(
1694     ImplicitConceptSpecializationDecl *D) {
1695   Record.push_back(D->getTemplateArguments().size());
1696   VisitDecl(D);
1697   for (const TemplateArgument &Arg : D->getTemplateArguments())
1698     Record.AddTemplateArgument(Arg);
1699   Code = serialization::DECL_IMPLICIT_CONCEPT_SPECIALIZATION;
1700 }
1701 
1702 void ASTDeclWriter::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
1703   Code = serialization::DECL_REQUIRES_EXPR_BODY;
1704 }
1705 
1706 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1707   VisitRedeclarable(D);
1708 
1709   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
1710   // getCommonPtr() can be used while this is still initializing.
1711   if (D->isFirstDecl()) {
1712     // This declaration owns the 'common' pointer, so serialize that data now.
1713     Record.AddDeclRef(D->getInstantiatedFromMemberTemplate());
1714     if (D->getInstantiatedFromMemberTemplate())
1715       Record.push_back(D->isMemberSpecialization());
1716   }
1717 
1718   VisitTemplateDecl(D);
1719   Record.push_back(D->getIdentifierNamespace());
1720 }
1721 
1722 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1723   VisitRedeclarableTemplateDecl(D);
1724 
1725   if (D->isFirstDecl())
1726     AddTemplateSpecializations(D);
1727 
1728   // Force emitting the corresponding deduction guide in reduced BMI mode.
1729   // Otherwise, the deduction guide may be optimized out incorrectly.
1730   if (Writer.isGeneratingReducedBMI()) {
1731     auto Name = Context.DeclarationNames.getCXXDeductionGuideName(D);
1732     for (auto *DG : D->getDeclContext()->noload_lookup(Name))
1733       Writer.GetDeclRef(DG->getCanonicalDecl());
1734   }
1735 
1736   Code = serialization::DECL_CLASS_TEMPLATE;
1737 }
1738 
1739 void ASTDeclWriter::VisitClassTemplateSpecializationDecl(
1740                                            ClassTemplateSpecializationDecl *D) {
1741   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1742 
1743   VisitCXXRecordDecl(D);
1744 
1745   llvm::PointerUnion<ClassTemplateDecl *,
1746                      ClassTemplatePartialSpecializationDecl *> InstFrom
1747     = D->getSpecializedTemplateOrPartial();
1748   if (Decl *InstFromD = InstFrom.dyn_cast<ClassTemplateDecl *>()) {
1749     Record.AddDeclRef(InstFromD);
1750   } else {
1751     Record.AddDeclRef(InstFrom.get<ClassTemplatePartialSpecializationDecl *>());
1752     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1753   }
1754 
1755   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1756   Record.AddSourceLocation(D->getPointOfInstantiation());
1757   Record.push_back(D->getSpecializationKind());
1758   Record.push_back(D->isCanonicalDecl());
1759 
1760   if (D->isCanonicalDecl()) {
1761     // When reading, we'll add it to the folding set of the following template.
1762     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1763   }
1764 
1765   bool ExplicitInstantiation =
1766       D->getTemplateSpecializationKind() ==
1767           TSK_ExplicitInstantiationDeclaration ||
1768       D->getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition;
1769   Record.push_back(ExplicitInstantiation);
1770   if (ExplicitInstantiation) {
1771     Record.AddSourceLocation(D->getExternKeywordLoc());
1772     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1773   }
1774 
1775   const ASTTemplateArgumentListInfo *ArgsWritten =
1776       D->getTemplateArgsAsWritten();
1777   Record.push_back(!!ArgsWritten);
1778   if (ArgsWritten)
1779     Record.AddASTTemplateArgumentListInfo(ArgsWritten);
1780 
1781   Code = serialization::DECL_CLASS_TEMPLATE_SPECIALIZATION;
1782 }
1783 
1784 void ASTDeclWriter::VisitClassTemplatePartialSpecializationDecl(
1785                                     ClassTemplatePartialSpecializationDecl *D) {
1786   Record.AddTemplateParameterList(D->getTemplateParameters());
1787 
1788   VisitClassTemplateSpecializationDecl(D);
1789 
1790   // These are read/set from/to the first declaration.
1791   if (D->getPreviousDecl() == nullptr) {
1792     Record.AddDeclRef(D->getInstantiatedFromMember());
1793     Record.push_back(D->isMemberSpecialization());
1794   }
1795 
1796   Code = serialization::DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION;
1797 }
1798 
1799 void ASTDeclWriter::VisitVarTemplateDecl(VarTemplateDecl *D) {
1800   VisitRedeclarableTemplateDecl(D);
1801 
1802   if (D->isFirstDecl())
1803     AddTemplateSpecializations(D);
1804   Code = serialization::DECL_VAR_TEMPLATE;
1805 }
1806 
1807 void ASTDeclWriter::VisitVarTemplateSpecializationDecl(
1808     VarTemplateSpecializationDecl *D) {
1809   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1810 
1811   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
1812   InstFrom = D->getSpecializedTemplateOrPartial();
1813   if (Decl *InstFromD = InstFrom.dyn_cast<VarTemplateDecl *>()) {
1814     Record.AddDeclRef(InstFromD);
1815   } else {
1816     Record.AddDeclRef(InstFrom.get<VarTemplatePartialSpecializationDecl *>());
1817     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1818   }
1819 
1820   bool ExplicitInstantiation =
1821       D->getTemplateSpecializationKind() ==
1822           TSK_ExplicitInstantiationDeclaration ||
1823       D->getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition;
1824   Record.push_back(ExplicitInstantiation);
1825   if (ExplicitInstantiation) {
1826     Record.AddSourceLocation(D->getExternKeywordLoc());
1827     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1828   }
1829 
1830   const ASTTemplateArgumentListInfo *ArgsWritten =
1831       D->getTemplateArgsAsWritten();
1832   Record.push_back(!!ArgsWritten);
1833   if (ArgsWritten)
1834     Record.AddASTTemplateArgumentListInfo(ArgsWritten);
1835 
1836   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1837   Record.AddSourceLocation(D->getPointOfInstantiation());
1838   Record.push_back(D->getSpecializationKind());
1839   Record.push_back(D->IsCompleteDefinition);
1840 
1841   VisitVarDecl(D);
1842 
1843   Record.push_back(D->isCanonicalDecl());
1844 
1845   if (D->isCanonicalDecl()) {
1846     // When reading, we'll add it to the folding set of the following template.
1847     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1848   }
1849 
1850   Code = serialization::DECL_VAR_TEMPLATE_SPECIALIZATION;
1851 }
1852 
1853 void ASTDeclWriter::VisitVarTemplatePartialSpecializationDecl(
1854     VarTemplatePartialSpecializationDecl *D) {
1855   Record.AddTemplateParameterList(D->getTemplateParameters());
1856 
1857   VisitVarTemplateSpecializationDecl(D);
1858 
1859   // These are read/set from/to the first declaration.
1860   if (D->getPreviousDecl() == nullptr) {
1861     Record.AddDeclRef(D->getInstantiatedFromMember());
1862     Record.push_back(D->isMemberSpecialization());
1863   }
1864 
1865   Code = serialization::DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION;
1866 }
1867 
1868 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1869   VisitRedeclarableTemplateDecl(D);
1870 
1871   if (D->isFirstDecl())
1872     AddTemplateSpecializations(D);
1873   Code = serialization::DECL_FUNCTION_TEMPLATE;
1874 }
1875 
1876 void ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1877   Record.push_back(D->hasTypeConstraint());
1878   VisitTypeDecl(D);
1879 
1880   Record.push_back(D->wasDeclaredWithTypename());
1881 
1882   const TypeConstraint *TC = D->getTypeConstraint();
1883   assert((bool)TC == D->hasTypeConstraint());
1884   if (TC) {
1885     auto *CR = TC->getConceptReference();
1886     Record.push_back(CR != nullptr);
1887     if (CR)
1888       Record.AddConceptReference(CR);
1889     Record.AddStmt(TC->getImmediatelyDeclaredConstraint());
1890     Record.push_back(D->isExpandedParameterPack());
1891     if (D->isExpandedParameterPack())
1892       Record.push_back(D->getNumExpansionParameters());
1893   }
1894 
1895   bool OwnsDefaultArg = D->hasDefaultArgument() &&
1896                         !D->defaultArgumentWasInherited();
1897   Record.push_back(OwnsDefaultArg);
1898   if (OwnsDefaultArg)
1899     Record.AddTemplateArgumentLoc(D->getDefaultArgument());
1900 
1901   if (!TC && !OwnsDefaultArg &&
1902       D->getDeclContext() == D->getLexicalDeclContext() &&
1903       !D->isInvalidDecl() && !D->hasAttrs() &&
1904       !D->isTopLevelDeclInObjCContainer() && !D->isImplicit() &&
1905       D->getDeclName().getNameKind() == DeclarationName::Identifier)
1906     AbbrevToUse = Writer.getDeclTemplateTypeParmAbbrev();
1907 
1908   Code = serialization::DECL_TEMPLATE_TYPE_PARM;
1909 }
1910 
1911 void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1912   // For an expanded parameter pack, record the number of expansion types here
1913   // so that it's easier for deserialization to allocate the right amount of
1914   // memory.
1915   Expr *TypeConstraint = D->getPlaceholderTypeConstraint();
1916   Record.push_back(!!TypeConstraint);
1917   if (D->isExpandedParameterPack())
1918     Record.push_back(D->getNumExpansionTypes());
1919 
1920   VisitDeclaratorDecl(D);
1921   // TemplateParmPosition.
1922   Record.push_back(D->getDepth());
1923   Record.push_back(D->getPosition());
1924   if (TypeConstraint)
1925     Record.AddStmt(TypeConstraint);
1926 
1927   if (D->isExpandedParameterPack()) {
1928     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1929       Record.AddTypeRef(D->getExpansionType(I));
1930       Record.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I));
1931     }
1932 
1933     Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK;
1934   } else {
1935     // Rest of NonTypeTemplateParmDecl.
1936     Record.push_back(D->isParameterPack());
1937     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1938                           !D->defaultArgumentWasInherited();
1939     Record.push_back(OwnsDefaultArg);
1940     if (OwnsDefaultArg)
1941       Record.AddTemplateArgumentLoc(D->getDefaultArgument());
1942     Code = serialization::DECL_NON_TYPE_TEMPLATE_PARM;
1943   }
1944 }
1945 
1946 void ASTDeclWriter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1947   // For an expanded parameter pack, record the number of expansion types here
1948   // so that it's easier for deserialization to allocate the right amount of
1949   // memory.
1950   if (D->isExpandedParameterPack())
1951     Record.push_back(D->getNumExpansionTemplateParameters());
1952 
1953   VisitTemplateDecl(D);
1954   Record.push_back(D->wasDeclaredWithTypename());
1955   // TemplateParmPosition.
1956   Record.push_back(D->getDepth());
1957   Record.push_back(D->getPosition());
1958 
1959   if (D->isExpandedParameterPack()) {
1960     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1961          I != N; ++I)
1962       Record.AddTemplateParameterList(D->getExpansionTemplateParameters(I));
1963     Code = serialization::DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK;
1964   } else {
1965     // Rest of TemplateTemplateParmDecl.
1966     Record.push_back(D->isParameterPack());
1967     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1968                           !D->defaultArgumentWasInherited();
1969     Record.push_back(OwnsDefaultArg);
1970     if (OwnsDefaultArg)
1971       Record.AddTemplateArgumentLoc(D->getDefaultArgument());
1972     Code = serialization::DECL_TEMPLATE_TEMPLATE_PARM;
1973   }
1974 }
1975 
1976 void ASTDeclWriter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1977   VisitRedeclarableTemplateDecl(D);
1978   Code = serialization::DECL_TYPE_ALIAS_TEMPLATE;
1979 }
1980 
1981 void ASTDeclWriter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1982   VisitDecl(D);
1983   Record.AddStmt(D->getAssertExpr());
1984   Record.push_back(D->isFailed());
1985   Record.AddStmt(D->getMessage());
1986   Record.AddSourceLocation(D->getRParenLoc());
1987   Code = serialization::DECL_STATIC_ASSERT;
1988 }
1989 
1990 /// Emit the DeclContext part of a declaration context decl.
1991 void ASTDeclWriter::VisitDeclContext(DeclContext *DC) {
1992   static_assert(DeclContext::NumDeclContextBits == 13,
1993                 "You need to update the serializer after you change the "
1994                 "DeclContextBits");
1995 
1996   uint64_t LexicalOffset = 0;
1997   uint64_t VisibleOffset = 0;
1998 
1999   if (Writer.isGeneratingReducedBMI() && isa<NamespaceDecl>(DC) &&
2000       cast<NamespaceDecl>(DC)->isFromExplicitGlobalModule()) {
2001     // In reduced BMI, delay writing lexical and visible block for namespace
2002     // in the global module fragment. See the comments of DelayedNamespace for
2003     // details.
2004     Writer.DelayedNamespace.push_back(cast<NamespaceDecl>(DC));
2005   } else {
2006     LexicalOffset = Writer.WriteDeclContextLexicalBlock(Context, DC);
2007     VisibleOffset = Writer.WriteDeclContextVisibleBlock(Context, DC);
2008   }
2009 
2010   Record.AddOffset(LexicalOffset);
2011   Record.AddOffset(VisibleOffset);
2012 }
2013 
2014 const Decl *ASTWriter::getFirstLocalDecl(const Decl *D) {
2015   assert(IsLocalDecl(D) && "expected a local declaration");
2016 
2017   const Decl *Canon = D->getCanonicalDecl();
2018   if (IsLocalDecl(Canon))
2019     return Canon;
2020 
2021   const Decl *&CacheEntry = FirstLocalDeclCache[Canon];
2022   if (CacheEntry)
2023     return CacheEntry;
2024 
2025   for (const Decl *Redecl = D; Redecl; Redecl = Redecl->getPreviousDecl())
2026     if (IsLocalDecl(Redecl))
2027       D = Redecl;
2028   return CacheEntry = D;
2029 }
2030 
2031 template <typename T>
2032 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
2033   T *First = D->getFirstDecl();
2034   T *MostRecent = First->getMostRecentDecl();
2035   T *DAsT = static_cast<T *>(D);
2036   if (MostRecent != First) {
2037     assert(isRedeclarableDeclKind(DAsT->getKind()) &&
2038            "Not considered redeclarable?");
2039 
2040     Record.AddDeclRef(First);
2041 
2042     // Write out a list of local redeclarations of this declaration if it's the
2043     // first local declaration in the chain.
2044     const Decl *FirstLocal = Writer.getFirstLocalDecl(DAsT);
2045     if (DAsT == FirstLocal) {
2046       // Emit a list of all imported first declarations so that we can be sure
2047       // that all redeclarations visible to this module are before D in the
2048       // redecl chain.
2049       unsigned I = Record.size();
2050       Record.push_back(0);
2051       if (Writer.Chain)
2052         AddFirstDeclFromEachModule(DAsT, /*IncludeLocal*/false);
2053       // This is the number of imported first declarations + 1.
2054       Record[I] = Record.size() - I;
2055 
2056       // Collect the set of local redeclarations of this declaration, from
2057       // newest to oldest.
2058       ASTWriter::RecordData LocalRedecls;
2059       ASTRecordWriter LocalRedeclWriter(Record, LocalRedecls);
2060       for (const Decl *Prev = FirstLocal->getMostRecentDecl();
2061            Prev != FirstLocal; Prev = Prev->getPreviousDecl())
2062         if (!Prev->isFromASTFile())
2063           LocalRedeclWriter.AddDeclRef(Prev);
2064 
2065       // If we have any redecls, write them now as a separate record preceding
2066       // the declaration itself.
2067       if (LocalRedecls.empty())
2068         Record.push_back(0);
2069       else
2070         Record.AddOffset(LocalRedeclWriter.Emit(LOCAL_REDECLARATIONS));
2071     } else {
2072       Record.push_back(0);
2073       Record.AddDeclRef(FirstLocal);
2074     }
2075 
2076     // Make sure that we serialize both the previous and the most-recent
2077     // declarations, which (transitively) ensures that all declarations in the
2078     // chain get serialized.
2079     //
2080     // FIXME: This is not correct; when we reach an imported declaration we
2081     // won't emit its previous declaration.
2082     (void)Writer.GetDeclRef(D->getPreviousDecl());
2083     (void)Writer.GetDeclRef(MostRecent);
2084   } else {
2085     // We use the sentinel value 0 to indicate an only declaration.
2086     Record.push_back(0);
2087   }
2088 }
2089 
2090 void ASTDeclWriter::VisitHLSLBufferDecl(HLSLBufferDecl *D) {
2091   VisitNamedDecl(D);
2092   VisitDeclContext(D);
2093   Record.push_back(D->isCBuffer());
2094   Record.AddSourceLocation(D->getLocStart());
2095   Record.AddSourceLocation(D->getLBraceLoc());
2096   Record.AddSourceLocation(D->getRBraceLoc());
2097 
2098   Code = serialization::DECL_HLSL_BUFFER;
2099 }
2100 
2101 void ASTDeclWriter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2102   Record.writeOMPChildren(D->Data);
2103   VisitDecl(D);
2104   Code = serialization::DECL_OMP_THREADPRIVATE;
2105 }
2106 
2107 void ASTDeclWriter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2108   Record.writeOMPChildren(D->Data);
2109   VisitDecl(D);
2110   Code = serialization::DECL_OMP_ALLOCATE;
2111 }
2112 
2113 void ASTDeclWriter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2114   Record.writeOMPChildren(D->Data);
2115   VisitDecl(D);
2116   Code = serialization::DECL_OMP_REQUIRES;
2117 }
2118 
2119 void ASTDeclWriter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2120   static_assert(DeclContext::NumOMPDeclareReductionDeclBits == 15,
2121                 "You need to update the serializer after you change the "
2122                 "NumOMPDeclareReductionDeclBits");
2123 
2124   VisitValueDecl(D);
2125   Record.AddSourceLocation(D->getBeginLoc());
2126   Record.AddStmt(D->getCombinerIn());
2127   Record.AddStmt(D->getCombinerOut());
2128   Record.AddStmt(D->getCombiner());
2129   Record.AddStmt(D->getInitOrig());
2130   Record.AddStmt(D->getInitPriv());
2131   Record.AddStmt(D->getInitializer());
2132   Record.push_back(llvm::to_underlying(D->getInitializerKind()));
2133   Record.AddDeclRef(D->getPrevDeclInScope());
2134   Code = serialization::DECL_OMP_DECLARE_REDUCTION;
2135 }
2136 
2137 void ASTDeclWriter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2138   Record.writeOMPChildren(D->Data);
2139   VisitValueDecl(D);
2140   Record.AddDeclarationName(D->getVarName());
2141   Record.AddDeclRef(D->getPrevDeclInScope());
2142   Code = serialization::DECL_OMP_DECLARE_MAPPER;
2143 }
2144 
2145 void ASTDeclWriter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2146   VisitVarDecl(D);
2147   Code = serialization::DECL_OMP_CAPTUREDEXPR;
2148 }
2149 
2150 //===----------------------------------------------------------------------===//
2151 // ASTWriter Implementation
2152 //===----------------------------------------------------------------------===//
2153 
2154 namespace {
2155 template <FunctionDecl::TemplatedKind Kind>
2156 std::shared_ptr<llvm::BitCodeAbbrev>
2157 getFunctionDeclAbbrev(serialization::DeclCode Code) {
2158   using namespace llvm;
2159 
2160   auto Abv = std::make_shared<BitCodeAbbrev>();
2161   Abv->Add(BitCodeAbbrevOp(Code));
2162   // RedeclarableDecl
2163   Abv->Add(BitCodeAbbrevOp(0)); // CanonicalDecl
2164   Abv->Add(BitCodeAbbrevOp(Kind));
2165   if constexpr (Kind == FunctionDecl::TK_NonTemplate) {
2166 
2167   } else if constexpr (Kind == FunctionDecl::TK_FunctionTemplate) {
2168     // DescribedFunctionTemplate
2169     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2170   } else if constexpr (Kind == FunctionDecl::TK_DependentNonTemplate) {
2171     // Instantiated From Decl
2172     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2173   } else if constexpr (Kind == FunctionDecl::TK_MemberSpecialization) {
2174     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InstantiatedFrom
2175     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2176                              3)); // TemplateSpecializationKind
2177     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Specialized Location
2178   } else if constexpr (Kind ==
2179                        FunctionDecl::TK_FunctionTemplateSpecialization) {
2180     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Template
2181     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2182                              3)); // TemplateSpecializationKind
2183     Abv->Add(BitCodeAbbrevOp(1)); // Template Argument Size
2184     Abv->Add(BitCodeAbbrevOp(TemplateArgument::Type)); // Template Argument Kind
2185     Abv->Add(
2186         BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Template Argument Type
2187     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is Defaulted
2188     Abv->Add(BitCodeAbbrevOp(0)); // TemplateArgumentsAsWritten
2189     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SourceLocation
2190     Abv->Add(BitCodeAbbrevOp(0));
2191     Abv->Add(
2192         BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Canonical Decl of template
2193   } else if constexpr (Kind == FunctionDecl::
2194                                    TK_DependentFunctionTemplateSpecialization) {
2195     // Candidates of specialization
2196     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2197     Abv->Add(BitCodeAbbrevOp(0)); // TemplateArgumentsAsWritten
2198   } else {
2199     llvm_unreachable("Unknown templated kind?");
2200   }
2201   // Decl
2202   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2203                            8)); // Packed DeclBits: ModuleOwnershipKind,
2204                                 // isUsed, isReferenced,  AccessSpecifier,
2205                                 // isImplicit
2206                                 //
2207                                 // The following bits should be 0:
2208                                 // HasStandaloneLexicalDC, HasAttrs,
2209                                 // TopLevelDeclInObjCContainer,
2210                                 // isInvalidDecl
2211   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2212   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2213   // NamedDecl
2214   Abv->Add(BitCodeAbbrevOp(DeclarationName::Identifier)); // NameKind
2215   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));     // Identifier
2216   Abv->Add(BitCodeAbbrevOp(0));                           // AnonDeclNumber
2217   // ValueDecl
2218   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2219   // DeclaratorDecl
2220   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerLocStart
2221   Abv->Add(BitCodeAbbrevOp(0));                       // HasExtInfo
2222   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2223   // FunctionDecl
2224   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 11)); // IDNS
2225   Abv->Add(BitCodeAbbrevOp(
2226       BitCodeAbbrevOp::Fixed,
2227       28)); // Packed Function Bits: StorageClass, Inline, InlineSpecified,
2228             // VirtualAsWritten, Pure, HasInheritedProto, HasWrittenProto,
2229             // Deleted, Trivial, TrivialForCall, Defaulted, ExplicitlyDefaulted,
2230             // IsIneligibleOrNotSelected, ImplicitReturnZero, Constexpr,
2231             // UsesSEHTry, SkippedBody, MultiVersion, LateParsed,
2232             // FriendConstraintRefersToEnclosingTemplate, Linkage,
2233             // ShouldSkipCheckingODR
2234   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // LocEnd
2235   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // ODRHash
2236   // This Array slurps the rest of the record. Fortunately we want to encode
2237   // (nearly) all the remaining (variable number of) fields in the same way.
2238   //
2239   // This is:
2240   //         NumParams and Params[] from FunctionDecl, and
2241   //         NumOverriddenMethods, OverriddenMethods[] from CXXMethodDecl.
2242   //
2243   //  Add an AbbrevOp for 'size then elements' and use it here.
2244   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2245   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2246   return Abv;
2247 }
2248 
2249 template <FunctionDecl::TemplatedKind Kind>
2250 std::shared_ptr<llvm::BitCodeAbbrev> getCXXMethodAbbrev() {
2251   return getFunctionDeclAbbrev<Kind>(serialization::DECL_CXX_METHOD);
2252 }
2253 } // namespace
2254 
2255 void ASTWriter::WriteDeclAbbrevs() {
2256   using namespace llvm;
2257 
2258   std::shared_ptr<BitCodeAbbrev> Abv;
2259 
2260   // Abbreviation for DECL_FIELD
2261   Abv = std::make_shared<BitCodeAbbrev>();
2262   Abv->Add(BitCodeAbbrevOp(serialization::DECL_FIELD));
2263   // Decl
2264   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2265                            7)); // Packed DeclBits: ModuleOwnershipKind,
2266                                 // isUsed, isReferenced,  AccessSpecifier,
2267                                 //
2268                                 // The following bits should be 0:
2269                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2270                                 // TopLevelDeclInObjCContainer,
2271                                 // isInvalidDecl
2272   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2273   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2274   // NamedDecl
2275   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2276   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2277   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2278   // ValueDecl
2279   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2280   // DeclaratorDecl
2281   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2282   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2283   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2284   // FieldDecl
2285   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
2286   Abv->Add(BitCodeAbbrevOp(0));                       // StorageKind
2287   // Type Source Info
2288   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2289   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2290   DeclFieldAbbrev = Stream.EmitAbbrev(std::move(Abv));
2291 
2292   // Abbreviation for DECL_OBJC_IVAR
2293   Abv = std::make_shared<BitCodeAbbrev>();
2294   Abv->Add(BitCodeAbbrevOp(serialization::DECL_OBJC_IVAR));
2295   // Decl
2296   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2297                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2298                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2299                                  // isReferenced, TopLevelDeclInObjCContainer,
2300                                  // AccessSpecifier, ModuleOwnershipKind
2301   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2302   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2303   // NamedDecl
2304   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2305   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2306   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2307   // ValueDecl
2308   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2309   // DeclaratorDecl
2310   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2311   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2312   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2313   // FieldDecl
2314   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
2315   Abv->Add(BitCodeAbbrevOp(0));                       // InitStyle
2316   // ObjC Ivar
2317   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getAccessControl
2318   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getSynthesize
2319   // Type Source Info
2320   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2321   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2322   DeclObjCIvarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2323 
2324   // Abbreviation for DECL_ENUM
2325   Abv = std::make_shared<BitCodeAbbrev>();
2326   Abv->Add(BitCodeAbbrevOp(serialization::DECL_ENUM));
2327   // Redeclarable
2328   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2329   // Decl
2330   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2331                            7)); // Packed DeclBits: ModuleOwnershipKind,
2332                                 // isUsed, isReferenced,  AccessSpecifier,
2333                                 //
2334                                 // The following bits should be 0:
2335                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2336                                 // TopLevelDeclInObjCContainer,
2337                                 // isInvalidDecl
2338   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2339   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2340   // NamedDecl
2341   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2342   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2343   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2344   // TypeDecl
2345   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2346   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2347   // TagDecl
2348   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
2349   Abv->Add(BitCodeAbbrevOp(
2350       BitCodeAbbrevOp::Fixed,
2351       9)); // Packed Tag Decl Bits: getTagKind, isCompleteDefinition,
2352            // EmbeddedInDeclarator, IsFreeStanding,
2353            // isCompleteDefinitionRequired, ExtInfoKind
2354   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2355   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2356   // EnumDecl
2357   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddTypeRef
2358   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IntegerType
2359   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getPromotionType
2360   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 20)); // Enum Decl Bits
2361   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));// ODRHash
2362   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // InstantiatedMembEnum
2363   // DC
2364   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
2365   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
2366   DeclEnumAbbrev = Stream.EmitAbbrev(std::move(Abv));
2367 
2368   // Abbreviation for DECL_RECORD
2369   Abv = std::make_shared<BitCodeAbbrev>();
2370   Abv->Add(BitCodeAbbrevOp(serialization::DECL_RECORD));
2371   // Redeclarable
2372   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2373   // Decl
2374   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2375                            7)); // Packed DeclBits: ModuleOwnershipKind,
2376                                 // isUsed, isReferenced,  AccessSpecifier,
2377                                 //
2378                                 // The following bits should be 0:
2379                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2380                                 // TopLevelDeclInObjCContainer,
2381                                 // isInvalidDecl
2382   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2383   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2384   // NamedDecl
2385   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2386   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2387   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2388   // TypeDecl
2389   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2390   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2391   // TagDecl
2392   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
2393   Abv->Add(BitCodeAbbrevOp(
2394       BitCodeAbbrevOp::Fixed,
2395       9)); // Packed Tag Decl Bits: getTagKind, isCompleteDefinition,
2396            // EmbeddedInDeclarator, IsFreeStanding,
2397            // isCompleteDefinitionRequired, ExtInfoKind
2398   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2399   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2400   // RecordDecl
2401   Abv->Add(BitCodeAbbrevOp(
2402       BitCodeAbbrevOp::Fixed,
2403       13)); // Packed Record Decl Bits: FlexibleArrayMember,
2404             // AnonymousStructUnion, hasObjectMember, hasVolatileMember,
2405             // isNonTrivialToPrimitiveDefaultInitialize,
2406             // isNonTrivialToPrimitiveCopy, isNonTrivialToPrimitiveDestroy,
2407             // hasNonTrivialToPrimitiveDefaultInitializeCUnion,
2408             // hasNonTrivialToPrimitiveDestructCUnion,
2409             // hasNonTrivialToPrimitiveCopyCUnion, isParamDestroyedInCallee,
2410             // getArgPassingRestrictions
2411   // ODRHash
2412   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 26));
2413 
2414   // DC
2415   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
2416   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
2417   DeclRecordAbbrev = Stream.EmitAbbrev(std::move(Abv));
2418 
2419   // Abbreviation for DECL_PARM_VAR
2420   Abv = std::make_shared<BitCodeAbbrev>();
2421   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
2422   // Redeclarable
2423   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2424   // Decl
2425   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2426                            8)); // Packed DeclBits: ModuleOwnershipKind, isUsed,
2427                                 // isReferenced, AccessSpecifier,
2428                                 // HasStandaloneLexicalDC, HasAttrs, isImplicit,
2429                                 // TopLevelDeclInObjCContainer,
2430                                 // isInvalidDecl,
2431   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2432   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2433   // NamedDecl
2434   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2435   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2436   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2437   // ValueDecl
2438   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2439   // DeclaratorDecl
2440   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2441   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2442   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2443   // VarDecl
2444   Abv->Add(
2445       BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2446                       12)); // Packed Var Decl bits: SClass, TSCSpec, InitStyle,
2447                             // isARCPseudoStrong, Linkage, ModulesCodegen
2448   Abv->Add(BitCodeAbbrevOp(0));                          // VarKind (local enum)
2449   // ParmVarDecl
2450   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ScopeIndex
2451   Abv->Add(BitCodeAbbrevOp(
2452       BitCodeAbbrevOp::Fixed,
2453       19)); // Packed Parm Var Decl bits: IsObjCMethodParameter, ScopeDepth,
2454             // ObjCDeclQualifier, KNRPromoted,
2455             // HasInheritedDefaultArg, HasUninstantiatedDefaultArg
2456   // Type Source Info
2457   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2458   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2459   DeclParmVarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2460 
2461   // Abbreviation for DECL_TYPEDEF
2462   Abv = std::make_shared<BitCodeAbbrev>();
2463   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TYPEDEF));
2464   // Redeclarable
2465   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2466   // Decl
2467   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2468                            7)); // Packed DeclBits: ModuleOwnershipKind,
2469                                 // isReferenced, isUsed, AccessSpecifier. Other
2470                                 // higher bits should be 0: isImplicit,
2471                                 // HasStandaloneLexicalDC, HasAttrs,
2472                                 // TopLevelDeclInObjCContainer, isInvalidDecl
2473   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2474   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2475   // NamedDecl
2476   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2477   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2478   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2479   // TypeDecl
2480   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2481   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2482   // TypedefDecl
2483   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2484   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2485   DeclTypedefAbbrev = Stream.EmitAbbrev(std::move(Abv));
2486 
2487   // Abbreviation for DECL_VAR
2488   Abv = std::make_shared<BitCodeAbbrev>();
2489   Abv->Add(BitCodeAbbrevOp(serialization::DECL_VAR));
2490   // Redeclarable
2491   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2492   // Decl
2493   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2494                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2495                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2496                                  // isReferenced, TopLevelDeclInObjCContainer,
2497                                  // AccessSpecifier, ModuleOwnershipKind
2498   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2499   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2500   // NamedDecl
2501   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2502   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2503   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2504   // ValueDecl
2505   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2506   // DeclaratorDecl
2507   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2508   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2509   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2510   // VarDecl
2511   Abv->Add(BitCodeAbbrevOp(
2512       BitCodeAbbrevOp::Fixed,
2513       21)); // Packed Var Decl bits:  Linkage, ModulesCodegen,
2514             // SClass, TSCSpec, InitStyle,
2515             // isARCPseudoStrong, IsThisDeclarationADemotedDefinition,
2516             // isExceptionVariable, isNRVOVariable, isCXXForRangeDecl,
2517             // isInline, isInlineSpecified, isConstexpr,
2518             // isInitCapture, isPrevDeclInSameScope,
2519             // EscapingByref, HasDeducedType, ImplicitParamKind, isObjCForDecl
2520   Abv->Add(BitCodeAbbrevOp(0));                         // VarKind (local enum)
2521   // Type Source Info
2522   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2523   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2524   DeclVarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2525 
2526   // Abbreviation for DECL_CXX_METHOD
2527   DeclCXXMethodAbbrev =
2528       Stream.EmitAbbrev(getCXXMethodAbbrev<FunctionDecl::TK_NonTemplate>());
2529   DeclTemplateCXXMethodAbbrev = Stream.EmitAbbrev(
2530       getCXXMethodAbbrev<FunctionDecl::TK_FunctionTemplate>());
2531   DeclDependentNonTemplateCXXMethodAbbrev = Stream.EmitAbbrev(
2532       getCXXMethodAbbrev<FunctionDecl::TK_DependentNonTemplate>());
2533   DeclMemberSpecializedCXXMethodAbbrev = Stream.EmitAbbrev(
2534       getCXXMethodAbbrev<FunctionDecl::TK_MemberSpecialization>());
2535   DeclTemplateSpecializedCXXMethodAbbrev = Stream.EmitAbbrev(
2536       getCXXMethodAbbrev<FunctionDecl::TK_FunctionTemplateSpecialization>());
2537   DeclDependentSpecializationCXXMethodAbbrev = Stream.EmitAbbrev(
2538       getCXXMethodAbbrev<
2539           FunctionDecl::TK_DependentFunctionTemplateSpecialization>());
2540 
2541   // Abbreviation for DECL_TEMPLATE_TYPE_PARM
2542   Abv = std::make_shared<BitCodeAbbrev>();
2543   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TEMPLATE_TYPE_PARM));
2544   Abv->Add(BitCodeAbbrevOp(0)); // hasTypeConstraint
2545   // Decl
2546   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2547                            7)); // Packed DeclBits: ModuleOwnershipKind,
2548                                 // isReferenced, isUsed, AccessSpecifier. Other
2549                                 // higher bits should be 0: isImplicit,
2550                                 // HasStandaloneLexicalDC, HasAttrs,
2551                                 // TopLevelDeclInObjCContainer, isInvalidDecl
2552   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2553   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2554   // NamedDecl
2555   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2556   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2557   Abv->Add(BitCodeAbbrevOp(0));
2558   // TypeDecl
2559   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2560   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2561   // TemplateTypeParmDecl
2562   Abv->Add(
2563       BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // wasDeclaredWithTypename
2564   Abv->Add(BitCodeAbbrevOp(0));                    // OwnsDefaultArg
2565   DeclTemplateTypeParmAbbrev = Stream.EmitAbbrev(std::move(Abv));
2566 
2567   // Abbreviation for DECL_USING_SHADOW
2568   Abv = std::make_shared<BitCodeAbbrev>();
2569   Abv->Add(BitCodeAbbrevOp(serialization::DECL_USING_SHADOW));
2570   // Redeclarable
2571   Abv->Add(BitCodeAbbrevOp(0)); // No redeclaration
2572   // Decl
2573   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2574                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2575                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2576                                  // isReferenced, TopLevelDeclInObjCContainer,
2577                                  // AccessSpecifier, ModuleOwnershipKind
2578   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2579   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2580   // NamedDecl
2581   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2582   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2583   Abv->Add(BitCodeAbbrevOp(0));
2584   // UsingShadowDecl
2585   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // TargetDecl
2586   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 11)); // IDNS
2587   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // UsingOrNextShadow
2588   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR,
2589                            6)); // InstantiatedFromUsingShadowDecl
2590   DeclUsingShadowAbbrev = Stream.EmitAbbrev(std::move(Abv));
2591 
2592   // Abbreviation for EXPR_DECL_REF
2593   Abv = std::make_shared<BitCodeAbbrev>();
2594   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_DECL_REF));
2595   // Stmt
2596   //  Expr
2597   //  PackingBits: DependenceKind, ValueKind. ObjectKind should be 0.
2598   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2599   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2600   // DeclRefExpr
2601   // Packing Bits: , HadMultipleCandidates, RefersToEnclosingVariableOrCapture,
2602   // IsImmediateEscalating, NonOdrUseReason.
2603   // GetDeclFound, HasQualifier and ExplicitTemplateArgs should be 0.
2604   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2605   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclRef
2606   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2607   DeclRefExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2608 
2609   // Abbreviation for EXPR_INTEGER_LITERAL
2610   Abv = std::make_shared<BitCodeAbbrev>();
2611   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_INTEGER_LITERAL));
2612   //Stmt
2613   // Expr
2614   // DependenceKind, ValueKind, ObjectKind
2615   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2616   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2617   // Integer Literal
2618   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2619   Abv->Add(BitCodeAbbrevOp(32));                      // Bit Width
2620   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Value
2621   IntegerLiteralAbbrev = Stream.EmitAbbrev(std::move(Abv));
2622 
2623   // Abbreviation for EXPR_CHARACTER_LITERAL
2624   Abv = std::make_shared<BitCodeAbbrev>();
2625   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CHARACTER_LITERAL));
2626   //Stmt
2627   // Expr
2628   // DependenceKind, ValueKind, ObjectKind
2629   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2630   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2631   // Character Literal
2632   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getValue
2633   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2634   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // getKind
2635   CharacterLiteralAbbrev = Stream.EmitAbbrev(std::move(Abv));
2636 
2637   // Abbreviation for EXPR_IMPLICIT_CAST
2638   Abv = std::make_shared<BitCodeAbbrev>();
2639   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_IMPLICIT_CAST));
2640   // Stmt
2641   // Expr
2642   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2643   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2644   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2645   // CastExpr
2646   Abv->Add(BitCodeAbbrevOp(0)); // PathSize
2647   // Packing Bits: CastKind, StoredFPFeatures, isPartOfExplicitCast
2648   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9));
2649   // ImplicitCastExpr
2650   ExprImplicitCastAbbrev = Stream.EmitAbbrev(std::move(Abv));
2651 
2652   // Abbreviation for EXPR_BINARY_OPERATOR
2653   Abv = std::make_shared<BitCodeAbbrev>();
2654   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_BINARY_OPERATOR));
2655   // Stmt
2656   // Expr
2657   // Packing Bits: DependenceKind. ValueKind and ObjectKind should
2658   // be 0 in this case.
2659   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2660   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2661   // BinaryOperator
2662   Abv->Add(
2663       BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpCode and HasFPFeatures
2664   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2665   BinaryOperatorAbbrev = Stream.EmitAbbrev(std::move(Abv));
2666 
2667   // Abbreviation for EXPR_COMPOUND_ASSIGN_OPERATOR
2668   Abv = std::make_shared<BitCodeAbbrev>();
2669   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_COMPOUND_ASSIGN_OPERATOR));
2670   // Stmt
2671   // Expr
2672   // Packing Bits: DependenceKind. ValueKind and ObjectKind should
2673   // be 0 in this case.
2674   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2675   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2676   // BinaryOperator
2677   // Packing Bits: OpCode. The HasFPFeatures bit should be 0
2678   Abv->Add(
2679       BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpCode and HasFPFeatures
2680   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2681   // CompoundAssignOperator
2682   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHSType
2683   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Result Type
2684   CompoundAssignOperatorAbbrev = Stream.EmitAbbrev(std::move(Abv));
2685 
2686   // Abbreviation for EXPR_CALL
2687   Abv = std::make_shared<BitCodeAbbrev>();
2688   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CALL));
2689   // Stmt
2690   // Expr
2691   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2692   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2693   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2694   // CallExpr
2695   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2696   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2697   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2698   CallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2699 
2700   // Abbreviation for EXPR_CXX_OPERATOR_CALL
2701   Abv = std::make_shared<BitCodeAbbrev>();
2702   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CXX_OPERATOR_CALL));
2703   // Stmt
2704   // Expr
2705   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2706   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2707   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2708   // CallExpr
2709   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2710   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2711   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2712   // CXXOperatorCallExpr
2713   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Operator Kind
2714   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2715   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2716   CXXOperatorCallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2717 
2718   // Abbreviation for EXPR_CXX_MEMBER_CALL
2719   Abv = std::make_shared<BitCodeAbbrev>();
2720   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CXX_MEMBER_CALL));
2721   // Stmt
2722   // Expr
2723   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2724   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2725   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2726   // CallExpr
2727   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2728   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2729   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2730   // CXXMemberCallExpr
2731   CXXMemberCallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2732 
2733   // Abbreviation for STMT_COMPOUND
2734   Abv = std::make_shared<BitCodeAbbrev>();
2735   Abv->Add(BitCodeAbbrevOp(serialization::STMT_COMPOUND));
2736   // Stmt
2737   // CompoundStmt
2738   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Num Stmts
2739   Abv->Add(BitCodeAbbrevOp(0));                       // hasStoredFPFeatures
2740   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2741   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2742   CompoundStmtAbbrev = Stream.EmitAbbrev(std::move(Abv));
2743 
2744   Abv = std::make_shared<BitCodeAbbrev>();
2745   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_LEXICAL));
2746   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2747   DeclContextLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
2748 
2749   Abv = std::make_shared<BitCodeAbbrev>();
2750   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_VISIBLE));
2751   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2752   DeclContextVisibleLookupAbbrev = Stream.EmitAbbrev(std::move(Abv));
2753 }
2754 
2755 /// isRequiredDecl - Check if this is a "required" Decl, which must be seen by
2756 /// consumers of the AST.
2757 ///
2758 /// Such decls will always be deserialized from the AST file, so we would like
2759 /// this to be as restrictive as possible. Currently the predicate is driven by
2760 /// code generation requirements, if other clients have a different notion of
2761 /// what is "required" then we may have to consider an alternate scheme where
2762 /// clients can iterate over the top-level decls and get information on them,
2763 /// without necessary deserializing them. We could explicitly require such
2764 /// clients to use a separate API call to "realize" the decl. This should be
2765 /// relatively painless since they would presumably only do it for top-level
2766 /// decls.
2767 static bool isRequiredDecl(const Decl *D, ASTContext &Context,
2768                            Module *WritingModule) {
2769   // Named modules have different semantics than header modules. Every named
2770   // module units owns a translation unit. So the importer of named modules
2771   // doesn't need to deserilize everything ahead of time.
2772   if (WritingModule && WritingModule->isNamedModule()) {
2773     // The PragmaCommentDecl and PragmaDetectMismatchDecl are MSVC's extension.
2774     // And the behavior of MSVC for such cases will leak this to the module
2775     // users. Given pragma is not a standard thing, the compiler has the space
2776     // to do their own decision. Let's follow MSVC here.
2777     if (isa<PragmaCommentDecl, PragmaDetectMismatchDecl>(D))
2778       return true;
2779     return false;
2780   }
2781 
2782   // An ObjCMethodDecl is never considered as "required" because its
2783   // implementation container always is.
2784 
2785   // File scoped assembly or obj-c or OMP declare target implementation must be
2786   // seen.
2787   if (isa<FileScopeAsmDecl, TopLevelStmtDecl, ObjCImplDecl>(D))
2788     return true;
2789 
2790   if (WritingModule && isPartOfPerModuleInitializer(D)) {
2791     // These declarations are part of the module initializer, and are emitted
2792     // if and when the module is imported, rather than being emitted eagerly.
2793     return false;
2794   }
2795 
2796   return Context.DeclMustBeEmitted(D);
2797 }
2798 
2799 void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) {
2800   PrettyDeclStackTraceEntry CrashInfo(Context, D, SourceLocation(),
2801                                       "serializing");
2802 
2803   // Determine the ID for this declaration.
2804   LocalDeclID ID;
2805   assert(!D->isFromASTFile() && "should not be emitting imported decl");
2806   LocalDeclID &IDR = DeclIDs[D];
2807   if (IDR.isInvalid())
2808     IDR = NextDeclID++;
2809 
2810   ID = IDR;
2811 
2812   assert(ID >= FirstDeclID && "invalid decl ID");
2813 
2814   RecordData Record;
2815   ASTDeclWriter W(*this, Context, Record, GeneratingReducedBMI);
2816 
2817   // Build a record for this declaration
2818   W.Visit(D);
2819 
2820   // Emit this declaration to the bitstream.
2821   uint64_t Offset = W.Emit(D);
2822 
2823   // Record the offset for this declaration
2824   SourceLocation Loc = D->getLocation();
2825   SourceLocationEncoding::RawLocEncoding RawLoc =
2826       getRawSourceLocationEncoding(getAdjustedLocation(Loc));
2827 
2828   unsigned Index = ID.getRawValue() - FirstDeclID.getRawValue();
2829   if (DeclOffsets.size() == Index)
2830     DeclOffsets.emplace_back(RawLoc, Offset, DeclTypesBlockStartOffset);
2831   else if (DeclOffsets.size() < Index) {
2832     // FIXME: Can/should this happen?
2833     DeclOffsets.resize(Index+1);
2834     DeclOffsets[Index].setRawLoc(RawLoc);
2835     DeclOffsets[Index].setBitOffset(Offset, DeclTypesBlockStartOffset);
2836   } else {
2837     llvm_unreachable("declarations should be emitted in ID order");
2838   }
2839 
2840   SourceManager &SM = Context.getSourceManager();
2841   if (Loc.isValid() && SM.isLocalSourceLocation(Loc))
2842     associateDeclWithFile(D, ID);
2843 
2844   // Note declarations that should be deserialized eagerly so that we can add
2845   // them to a record in the AST file later.
2846   if (isRequiredDecl(D, Context, WritingModule))
2847     AddDeclRef(D, EagerlyDeserializedDecls);
2848 }
2849 
2850 void ASTRecordWriter::AddFunctionDefinition(const FunctionDecl *FD) {
2851   // Switch case IDs are per function body.
2852   Writer->ClearSwitchCaseIDs();
2853 
2854   assert(FD->doesThisDeclarationHaveABody());
2855   bool ModulesCodegen = false;
2856   if (!FD->isDependentContext()) {
2857     std::optional<GVALinkage> Linkage;
2858     if (Writer->WritingModule &&
2859         Writer->WritingModule->isInterfaceOrPartition()) {
2860       // When building a C++20 module interface unit or a partition unit, a
2861       // strong definition in the module interface is provided by the
2862       // compilation of that unit, not by its users. (Inline functions are still
2863       // emitted in module users.)
2864       Linkage = Writer->Context->GetGVALinkageForFunction(FD);
2865       ModulesCodegen = *Linkage >= GVA_StrongExternal;
2866     }
2867     if (Writer->Context->getLangOpts().ModulesCodegen ||
2868         (FD->hasAttr<DLLExportAttr>() &&
2869          Writer->Context->getLangOpts().BuildingPCHWithObjectFile)) {
2870 
2871       // Under -fmodules-codegen, codegen is performed for all non-internal,
2872       // non-always_inline functions, unless they are available elsewhere.
2873       if (!FD->hasAttr<AlwaysInlineAttr>()) {
2874         if (!Linkage)
2875           Linkage = Writer->Context->GetGVALinkageForFunction(FD);
2876         ModulesCodegen =
2877             *Linkage != GVA_Internal && *Linkage != GVA_AvailableExternally;
2878       }
2879     }
2880   }
2881   Record->push_back(ModulesCodegen);
2882   if (ModulesCodegen)
2883     Writer->AddDeclRef(FD, Writer->ModularCodegenDecls);
2884   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
2885     Record->push_back(CD->getNumCtorInitializers());
2886     if (CD->getNumCtorInitializers())
2887       AddCXXCtorInitializers(llvm::ArrayRef(CD->init_begin(), CD->init_end()));
2888   }
2889   AddStmt(FD->getBody());
2890 }
2891