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