xref: /freebsd/contrib/llvm-project/clang/lib/Serialization/ASTWriter.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
1 //===- ASTWriter.cpp - AST File Writer ------------------------------------===//
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 defines the ASTWriter class, which writes AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "MultiOnDiskHashTable.h"
16 #include "TemplateArgumentHasher.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTUnresolvedSet.h"
19 #include "clang/AST/AbstractTypeWriter.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclContextInternals.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclarationName.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/LambdaCapture.h"
32 #include "clang/AST/NestedNameSpecifier.h"
33 #include "clang/AST/OpenACCClause.h"
34 #include "clang/AST/OpenMPClause.h"
35 #include "clang/AST/RawCommentList.h"
36 #include "clang/AST/TemplateName.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
39 #include "clang/AST/TypeLocVisitor.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/DiagnosticOptions.h"
42 #include "clang/Basic/FileEntry.h"
43 #include "clang/Basic/FileManager.h"
44 #include "clang/Basic/FileSystemOptions.h"
45 #include "clang/Basic/IdentifierTable.h"
46 #include "clang/Basic/LLVM.h"
47 #include "clang/Basic/Lambda.h"
48 #include "clang/Basic/LangOptions.h"
49 #include "clang/Basic/Module.h"
50 #include "clang/Basic/ObjCRuntime.h"
51 #include "clang/Basic/OpenACCKinds.h"
52 #include "clang/Basic/OpenCLOptions.h"
53 #include "clang/Basic/SourceLocation.h"
54 #include "clang/Basic/SourceManager.h"
55 #include "clang/Basic/SourceManagerInternals.h"
56 #include "clang/Basic/Specifiers.h"
57 #include "clang/Basic/TargetInfo.h"
58 #include "clang/Basic/TargetOptions.h"
59 #include "clang/Basic/Version.h"
60 #include "clang/Lex/HeaderSearch.h"
61 #include "clang/Lex/HeaderSearchOptions.h"
62 #include "clang/Lex/MacroInfo.h"
63 #include "clang/Lex/ModuleMap.h"
64 #include "clang/Lex/PreprocessingRecord.h"
65 #include "clang/Lex/Preprocessor.h"
66 #include "clang/Lex/PreprocessorOptions.h"
67 #include "clang/Lex/Token.h"
68 #include "clang/Sema/IdentifierResolver.h"
69 #include "clang/Sema/ObjCMethodList.h"
70 #include "clang/Sema/Sema.h"
71 #include "clang/Sema/SemaCUDA.h"
72 #include "clang/Sema/SemaObjC.h"
73 #include "clang/Sema/Weak.h"
74 #include "clang/Serialization/ASTBitCodes.h"
75 #include "clang/Serialization/ASTReader.h"
76 #include "clang/Serialization/ASTRecordWriter.h"
77 #include "clang/Serialization/InMemoryModuleCache.h"
78 #include "clang/Serialization/ModuleCache.h"
79 #include "clang/Serialization/ModuleFile.h"
80 #include "clang/Serialization/ModuleFileExtension.h"
81 #include "clang/Serialization/SerializationDiagnostic.h"
82 #include "llvm/ADT/APFloat.h"
83 #include "llvm/ADT/APInt.h"
84 #include "llvm/ADT/ArrayRef.h"
85 #include "llvm/ADT/DenseMap.h"
86 #include "llvm/ADT/DenseSet.h"
87 #include "llvm/ADT/PointerIntPair.h"
88 #include "llvm/ADT/STLExtras.h"
89 #include "llvm/ADT/ScopeExit.h"
90 #include "llvm/ADT/SmallPtrSet.h"
91 #include "llvm/ADT/SmallString.h"
92 #include "llvm/ADT/SmallVector.h"
93 #include "llvm/ADT/StringRef.h"
94 #include "llvm/Bitstream/BitCodes.h"
95 #include "llvm/Bitstream/BitstreamWriter.h"
96 #include "llvm/Support/Compression.h"
97 #include "llvm/Support/DJB.h"
98 #include "llvm/Support/EndianStream.h"
99 #include "llvm/Support/ErrorHandling.h"
100 #include "llvm/Support/LEB128.h"
101 #include "llvm/Support/MemoryBuffer.h"
102 #include "llvm/Support/OnDiskHashTable.h"
103 #include "llvm/Support/Path.h"
104 #include "llvm/Support/SHA1.h"
105 #include "llvm/Support/TimeProfiler.h"
106 #include "llvm/Support/VersionTuple.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include <algorithm>
109 #include <cassert>
110 #include <cstdint>
111 #include <cstdlib>
112 #include <cstring>
113 #include <ctime>
114 #include <limits>
115 #include <memory>
116 #include <optional>
117 #include <queue>
118 #include <tuple>
119 #include <utility>
120 #include <vector>
121 
122 using namespace clang;
123 using namespace clang::serialization;
124 
125 template <typename T, typename Allocator>
126 static StringRef bytes(const std::vector<T, Allocator> &v) {
127   if (v.empty()) return StringRef();
128   return StringRef(reinterpret_cast<const char*>(&v[0]),
129                          sizeof(T) * v.size());
130 }
131 
132 template <typename T>
133 static StringRef bytes(const SmallVectorImpl<T> &v) {
134   return StringRef(reinterpret_cast<const char*>(v.data()),
135                          sizeof(T) * v.size());
136 }
137 
138 static std::string bytes(const std::vector<bool> &V) {
139   std::string Str;
140   Str.reserve(V.size() / 8);
141   for (unsigned I = 0, E = V.size(); I < E;) {
142     char Byte = 0;
143     for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
144       Byte |= V[I] << Bit;
145     Str += Byte;
146   }
147   return Str;
148 }
149 
150 //===----------------------------------------------------------------------===//
151 // Type serialization
152 //===----------------------------------------------------------------------===//
153 
154 static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
155   switch (id) {
156 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
157   case Type::CLASS_ID: return TYPE_##CODE_ID;
158 #include "clang/Serialization/TypeBitCodes.def"
159   case Type::Builtin:
160     llvm_unreachable("shouldn't be serializing a builtin type this way");
161   }
162   llvm_unreachable("bad type kind");
163 }
164 
165 namespace {
166 
167 struct AffectingModuleMaps {
168   llvm::DenseSet<FileID> DefinitionFileIDs;
169   llvm::DenseSet<const FileEntry *> DefinitionFiles;
170 };
171 
172 std::optional<AffectingModuleMaps>
173 GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) {
174   if (!PP.getHeaderSearchInfo()
175            .getHeaderSearchOpts()
176            .ModulesPruneNonAffectingModuleMaps)
177     return std::nullopt;
178 
179   const HeaderSearch &HS = PP.getHeaderSearchInfo();
180   const SourceManager &SM = PP.getSourceManager();
181   const ModuleMap &MM = HS.getModuleMap();
182 
183   // Module maps used only by textual headers are special. Their FileID is
184   // non-affecting, but their FileEntry is (i.e. must be written as InputFile).
185   enum AffectedReason : bool {
186     AR_TextualHeader = 0,
187     AR_ImportOrTextualHeader = 1,
188   };
189   auto AssignMostImportant = [](AffectedReason &LHS, AffectedReason RHS) {
190     LHS = std::max(LHS, RHS);
191   };
192   llvm::DenseMap<FileID, AffectedReason> ModuleMaps;
193   llvm::DenseMap<const Module *, AffectedReason> ProcessedModules;
194   auto CollectModuleMapsForHierarchy = [&](const Module *M,
195                                            AffectedReason Reason) {
196     M = M->getTopLevelModule();
197 
198     // We need to process the header either when it was not present or when we
199     // previously flagged module map as textual headers and now we found a
200     // proper import.
201     if (auto [It, Inserted] = ProcessedModules.insert({M, Reason});
202         !Inserted && Reason <= It->second) {
203       return;
204     } else {
205       It->second = Reason;
206     }
207 
208     std::queue<const Module *> Q;
209     Q.push(M);
210     while (!Q.empty()) {
211       const Module *Mod = Q.front();
212       Q.pop();
213 
214       // The containing module map is affecting, because it's being pointed
215       // into by Module::DefinitionLoc.
216       if (auto F = MM.getContainingModuleMapFileID(Mod); F.isValid())
217         AssignMostImportant(ModuleMaps[F], Reason);
218       // For inferred modules, the module map that allowed inferring is not
219       // related to the virtual containing module map file. It did affect the
220       // compilation, though.
221       if (auto UniqF = MM.getModuleMapFileIDForUniquing(Mod); UniqF.isValid())
222         AssignMostImportant(ModuleMaps[UniqF], Reason);
223 
224       for (auto *SubM : Mod->submodules())
225         Q.push(SubM);
226     }
227   };
228 
229   // Handle all the affecting modules referenced from the root module.
230 
231   CollectModuleMapsForHierarchy(RootModule, AR_ImportOrTextualHeader);
232 
233   std::queue<const Module *> Q;
234   Q.push(RootModule);
235   while (!Q.empty()) {
236     const Module *CurrentModule = Q.front();
237     Q.pop();
238 
239     for (const Module *ImportedModule : CurrentModule->Imports)
240       CollectModuleMapsForHierarchy(ImportedModule, AR_ImportOrTextualHeader);
241     for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
242       CollectModuleMapsForHierarchy(UndeclaredModule, AR_ImportOrTextualHeader);
243 
244     for (auto *M : CurrentModule->submodules())
245       Q.push(M);
246   }
247 
248   // Handle textually-included headers that belong to other modules.
249 
250   SmallVector<OptionalFileEntryRef, 16> FilesByUID;
251   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
252 
253   if (FilesByUID.size() > HS.header_file_size())
254     FilesByUID.resize(HS.header_file_size());
255 
256   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
257     OptionalFileEntryRef File = FilesByUID[UID];
258     if (!File)
259       continue;
260 
261     const HeaderFileInfo *HFI = HS.getExistingLocalFileInfo(*File);
262     if (!HFI)
263       continue; // We have no information on this being a header file.
264     if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
265       continue; // Modular header, handled in the above module-based loop.
266     if (!HFI->isCompilingModuleHeader && !HFI->IsLocallyIncluded)
267       continue; // Non-modular header not included locally is not affecting.
268 
269     for (const auto &KH : HS.findResolvedModulesForHeader(*File))
270       if (const Module *M = KH.getModule())
271         CollectModuleMapsForHierarchy(M, AR_TextualHeader);
272   }
273 
274   // FIXME: This algorithm is not correct for module map hierarchies where
275   // module map file defining a (sub)module of a top-level module X includes
276   // a module map file that defines a (sub)module of another top-level module Y.
277   // Whenever X is affecting and Y is not, "replaying" this PCM file will fail
278   // when parsing module map files for X due to not knowing about the `extern`
279   // module map for Y.
280   //
281   // We don't have a good way to fix it here. We could mark all children of
282   // affecting module map files as being affecting as well, but that's
283   // expensive. SourceManager does not model the edge from parent to child
284   // SLocEntries, so instead, we would need to iterate over leaf module map
285   // files, walk up their include hierarchy and check whether we arrive at an
286   // affecting module map.
287   //
288   // Instead of complicating and slowing down this function, we should probably
289   // just ban module map hierarchies where module map defining a (sub)module X
290   // includes a module map defining a module that's not a submodule of X.
291 
292   llvm::DenseSet<const FileEntry *> ModuleFileEntries;
293   llvm::DenseSet<FileID> ModuleFileIDs;
294   for (auto [FID, Reason] : ModuleMaps) {
295     if (Reason == AR_ImportOrTextualHeader)
296       ModuleFileIDs.insert(FID);
297     if (auto *FE = SM.getFileEntryForID(FID))
298       ModuleFileEntries.insert(FE);
299   }
300 
301   AffectingModuleMaps R;
302   R.DefinitionFileIDs = std::move(ModuleFileIDs);
303   R.DefinitionFiles = std::move(ModuleFileEntries);
304   return std::move(R);
305 }
306 
307 class ASTTypeWriter {
308   ASTWriter &Writer;
309   ASTWriter::RecordData Record;
310   ASTRecordWriter BasicWriter;
311 
312 public:
313   ASTTypeWriter(ASTContext &Context, ASTWriter &Writer)
314       : Writer(Writer), BasicWriter(Context, Writer, Record) {}
315 
316   uint64_t write(QualType T) {
317     if (T.hasLocalNonFastQualifiers()) {
318       Qualifiers Qs = T.getLocalQualifiers();
319       BasicWriter.writeQualType(T.getLocalUnqualifiedType());
320       BasicWriter.writeQualifiers(Qs);
321       return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
322     }
323 
324     const Type *typePtr = T.getTypePtr();
325     serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
326     atw.write(typePtr);
327     return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
328                             /*abbrev*/ 0);
329   }
330 };
331 
332 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
333   ASTRecordWriter &Record;
334 
335   void addSourceLocation(SourceLocation Loc) { Record.AddSourceLocation(Loc); }
336   void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range); }
337 
338 public:
339   TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
340 
341 #define ABSTRACT_TYPELOC(CLASS, PARENT)
342 #define TYPELOC(CLASS, PARENT) \
343     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
344 #include "clang/AST/TypeLocNodes.def"
345 
346   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
347   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
348 };
349 
350 } // namespace
351 
352 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
353   // nothing to do
354 }
355 
356 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
357   addSourceLocation(TL.getBuiltinLoc());
358   if (TL.needsExtraLocalData()) {
359     Record.push_back(TL.getWrittenTypeSpec());
360     Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
361     Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
362     Record.push_back(TL.hasModeAttr());
363   }
364 }
365 
366 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
367   addSourceLocation(TL.getNameLoc());
368 }
369 
370 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
371   addSourceLocation(TL.getStarLoc());
372 }
373 
374 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
375   // nothing to do
376 }
377 
378 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
379   // nothing to do
380 }
381 
382 void TypeLocWriter::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
383   // nothing to do
384 }
385 
386 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
387   addSourceLocation(TL.getCaretLoc());
388 }
389 
390 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
391   addSourceLocation(TL.getAmpLoc());
392 }
393 
394 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
395   addSourceLocation(TL.getAmpAmpLoc());
396 }
397 
398 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
399   addSourceLocation(TL.getStarLoc());
400   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
401 }
402 
403 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
404   addSourceLocation(TL.getLBracketLoc());
405   addSourceLocation(TL.getRBracketLoc());
406   Record.push_back(TL.getSizeExpr() ? 1 : 0);
407   if (TL.getSizeExpr())
408     Record.AddStmt(TL.getSizeExpr());
409 }
410 
411 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
412   VisitArrayTypeLoc(TL);
413 }
414 
415 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
416   VisitArrayTypeLoc(TL);
417 }
418 
419 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
420   VisitArrayTypeLoc(TL);
421 }
422 
423 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
424                                             DependentSizedArrayTypeLoc TL) {
425   VisitArrayTypeLoc(TL);
426 }
427 
428 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
429     DependentAddressSpaceTypeLoc TL) {
430   addSourceLocation(TL.getAttrNameLoc());
431   SourceRange range = TL.getAttrOperandParensRange();
432   addSourceLocation(range.getBegin());
433   addSourceLocation(range.getEnd());
434   Record.AddStmt(TL.getAttrExprOperand());
435 }
436 
437 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
438                                         DependentSizedExtVectorTypeLoc TL) {
439   addSourceLocation(TL.getNameLoc());
440 }
441 
442 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
443   addSourceLocation(TL.getNameLoc());
444 }
445 
446 void TypeLocWriter::VisitDependentVectorTypeLoc(
447     DependentVectorTypeLoc TL) {
448   addSourceLocation(TL.getNameLoc());
449 }
450 
451 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
452   addSourceLocation(TL.getNameLoc());
453 }
454 
455 void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
456   addSourceLocation(TL.getAttrNameLoc());
457   SourceRange range = TL.getAttrOperandParensRange();
458   addSourceLocation(range.getBegin());
459   addSourceLocation(range.getEnd());
460   Record.AddStmt(TL.getAttrRowOperand());
461   Record.AddStmt(TL.getAttrColumnOperand());
462 }
463 
464 void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
465     DependentSizedMatrixTypeLoc TL) {
466   addSourceLocation(TL.getAttrNameLoc());
467   SourceRange range = TL.getAttrOperandParensRange();
468   addSourceLocation(range.getBegin());
469   addSourceLocation(range.getEnd());
470   Record.AddStmt(TL.getAttrRowOperand());
471   Record.AddStmt(TL.getAttrColumnOperand());
472 }
473 
474 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
475   addSourceLocation(TL.getLocalRangeBegin());
476   addSourceLocation(TL.getLParenLoc());
477   addSourceLocation(TL.getRParenLoc());
478   addSourceRange(TL.getExceptionSpecRange());
479   addSourceLocation(TL.getLocalRangeEnd());
480   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
481     Record.AddDeclRef(TL.getParam(i));
482 }
483 
484 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
485   VisitFunctionTypeLoc(TL);
486 }
487 
488 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
489   VisitFunctionTypeLoc(TL);
490 }
491 
492 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
493   addSourceLocation(TL.getNameLoc());
494 }
495 
496 void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
497   addSourceLocation(TL.getNameLoc());
498 }
499 
500 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
501   addSourceLocation(TL.getNameLoc());
502 }
503 
504 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
505   if (TL.getNumProtocols()) {
506     addSourceLocation(TL.getProtocolLAngleLoc());
507     addSourceLocation(TL.getProtocolRAngleLoc());
508   }
509   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
510     addSourceLocation(TL.getProtocolLoc(i));
511 }
512 
513 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
514   addSourceLocation(TL.getTypeofLoc());
515   addSourceLocation(TL.getLParenLoc());
516   addSourceLocation(TL.getRParenLoc());
517 }
518 
519 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
520   addSourceLocation(TL.getTypeofLoc());
521   addSourceLocation(TL.getLParenLoc());
522   addSourceLocation(TL.getRParenLoc());
523   Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
524 }
525 
526 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
527   addSourceLocation(TL.getDecltypeLoc());
528   addSourceLocation(TL.getRParenLoc());
529 }
530 
531 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
532   addSourceLocation(TL.getKWLoc());
533   addSourceLocation(TL.getLParenLoc());
534   addSourceLocation(TL.getRParenLoc());
535   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
536 }
537 
538 void ASTRecordWriter::AddConceptReference(const ConceptReference *CR) {
539   assert(CR);
540   AddNestedNameSpecifierLoc(CR->getNestedNameSpecifierLoc());
541   AddSourceLocation(CR->getTemplateKWLoc());
542   AddDeclarationNameInfo(CR->getConceptNameInfo());
543   AddDeclRef(CR->getFoundDecl());
544   AddDeclRef(CR->getNamedConcept());
545   push_back(CR->getTemplateArgsAsWritten() != nullptr);
546   if (CR->getTemplateArgsAsWritten())
547     AddASTTemplateArgumentListInfo(CR->getTemplateArgsAsWritten());
548 }
549 
550 void TypeLocWriter::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
551   addSourceLocation(TL.getEllipsisLoc());
552 }
553 
554 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
555   addSourceLocation(TL.getNameLoc());
556   auto *CR = TL.getConceptReference();
557   Record.push_back(TL.isConstrained() && CR);
558   if (TL.isConstrained() && CR)
559     Record.AddConceptReference(CR);
560   Record.push_back(TL.isDecltypeAuto());
561   if (TL.isDecltypeAuto())
562     addSourceLocation(TL.getRParenLoc());
563 }
564 
565 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
566     DeducedTemplateSpecializationTypeLoc TL) {
567   addSourceLocation(TL.getTemplateNameLoc());
568 }
569 
570 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
571   addSourceLocation(TL.getNameLoc());
572 }
573 
574 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
575   addSourceLocation(TL.getNameLoc());
576 }
577 
578 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
579   Record.AddAttr(TL.getAttr());
580 }
581 
582 void TypeLocWriter::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
583   // Nothing to do
584 }
585 
586 void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
587   // Nothing to do.
588 }
589 
590 void TypeLocWriter::VisitHLSLAttributedResourceTypeLoc(
591     HLSLAttributedResourceTypeLoc TL) {
592   // Nothing to do.
593 }
594 
595 void TypeLocWriter::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
596   // Nothing to do.
597 }
598 
599 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
600   addSourceLocation(TL.getNameLoc());
601 }
602 
603 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
604                                             SubstTemplateTypeParmTypeLoc TL) {
605   addSourceLocation(TL.getNameLoc());
606 }
607 
608 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
609                                           SubstTemplateTypeParmPackTypeLoc TL) {
610   addSourceLocation(TL.getNameLoc());
611 }
612 
613 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
614                                            TemplateSpecializationTypeLoc TL) {
615   addSourceLocation(TL.getTemplateKeywordLoc());
616   addSourceLocation(TL.getTemplateNameLoc());
617   addSourceLocation(TL.getLAngleLoc());
618   addSourceLocation(TL.getRAngleLoc());
619   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
620     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
621                                       TL.getArgLoc(i).getLocInfo());
622 }
623 
624 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
625   addSourceLocation(TL.getLParenLoc());
626   addSourceLocation(TL.getRParenLoc());
627 }
628 
629 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
630   addSourceLocation(TL.getExpansionLoc());
631 }
632 
633 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
634   addSourceLocation(TL.getElaboratedKeywordLoc());
635   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
636 }
637 
638 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
639   addSourceLocation(TL.getNameLoc());
640 }
641 
642 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
643   addSourceLocation(TL.getElaboratedKeywordLoc());
644   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
645   addSourceLocation(TL.getNameLoc());
646 }
647 
648 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
649        DependentTemplateSpecializationTypeLoc TL) {
650   addSourceLocation(TL.getElaboratedKeywordLoc());
651   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
652   addSourceLocation(TL.getTemplateKeywordLoc());
653   addSourceLocation(TL.getTemplateNameLoc());
654   addSourceLocation(TL.getLAngleLoc());
655   addSourceLocation(TL.getRAngleLoc());
656   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
657     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
658                                       TL.getArgLoc(I).getLocInfo());
659 }
660 
661 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
662   addSourceLocation(TL.getEllipsisLoc());
663 }
664 
665 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
666   addSourceLocation(TL.getNameLoc());
667   addSourceLocation(TL.getNameEndLoc());
668 }
669 
670 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
671   Record.push_back(TL.hasBaseTypeAsWritten());
672   addSourceLocation(TL.getTypeArgsLAngleLoc());
673   addSourceLocation(TL.getTypeArgsRAngleLoc());
674   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
675     Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
676   addSourceLocation(TL.getProtocolLAngleLoc());
677   addSourceLocation(TL.getProtocolRAngleLoc());
678   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
679     addSourceLocation(TL.getProtocolLoc(i));
680 }
681 
682 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
683   addSourceLocation(TL.getStarLoc());
684 }
685 
686 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
687   addSourceLocation(TL.getKWLoc());
688   addSourceLocation(TL.getLParenLoc());
689   addSourceLocation(TL.getRParenLoc());
690 }
691 
692 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
693   addSourceLocation(TL.getKWLoc());
694 }
695 
696 void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
697   addSourceLocation(TL.getNameLoc());
698 }
699 void TypeLocWriter::VisitDependentBitIntTypeLoc(
700     clang::DependentBitIntTypeLoc TL) {
701   addSourceLocation(TL.getNameLoc());
702 }
703 
704 void ASTWriter::WriteTypeAbbrevs() {
705   using namespace llvm;
706 
707   std::shared_ptr<BitCodeAbbrev> Abv;
708 
709   // Abbreviation for TYPE_EXT_QUAL
710   Abv = std::make_shared<BitCodeAbbrev>();
711   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
712   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
713   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
714   TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
715 }
716 
717 //===----------------------------------------------------------------------===//
718 // ASTWriter Implementation
719 //===----------------------------------------------------------------------===//
720 
721 static void EmitBlockID(unsigned ID, const char *Name,
722                         llvm::BitstreamWriter &Stream,
723                         ASTWriter::RecordDataImpl &Record) {
724   Record.clear();
725   Record.push_back(ID);
726   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
727 
728   // Emit the block name if present.
729   if (!Name || Name[0] == 0)
730     return;
731   Record.clear();
732   while (*Name)
733     Record.push_back(*Name++);
734   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
735 }
736 
737 static void EmitRecordID(unsigned ID, const char *Name,
738                          llvm::BitstreamWriter &Stream,
739                          ASTWriter::RecordDataImpl &Record) {
740   Record.clear();
741   Record.push_back(ID);
742   while (*Name)
743     Record.push_back(*Name++);
744   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
745 }
746 
747 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
748                           ASTWriter::RecordDataImpl &Record) {
749 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
750   RECORD(STMT_STOP);
751   RECORD(STMT_NULL_PTR);
752   RECORD(STMT_REF_PTR);
753   RECORD(STMT_NULL);
754   RECORD(STMT_COMPOUND);
755   RECORD(STMT_CASE);
756   RECORD(STMT_DEFAULT);
757   RECORD(STMT_LABEL);
758   RECORD(STMT_ATTRIBUTED);
759   RECORD(STMT_IF);
760   RECORD(STMT_SWITCH);
761   RECORD(STMT_WHILE);
762   RECORD(STMT_DO);
763   RECORD(STMT_FOR);
764   RECORD(STMT_GOTO);
765   RECORD(STMT_INDIRECT_GOTO);
766   RECORD(STMT_CONTINUE);
767   RECORD(STMT_BREAK);
768   RECORD(STMT_RETURN);
769   RECORD(STMT_DECL);
770   RECORD(STMT_GCCASM);
771   RECORD(STMT_MSASM);
772   RECORD(EXPR_PREDEFINED);
773   RECORD(EXPR_DECL_REF);
774   RECORD(EXPR_INTEGER_LITERAL);
775   RECORD(EXPR_FIXEDPOINT_LITERAL);
776   RECORD(EXPR_FLOATING_LITERAL);
777   RECORD(EXPR_IMAGINARY_LITERAL);
778   RECORD(EXPR_STRING_LITERAL);
779   RECORD(EXPR_CHARACTER_LITERAL);
780   RECORD(EXPR_PAREN);
781   RECORD(EXPR_PAREN_LIST);
782   RECORD(EXPR_UNARY_OPERATOR);
783   RECORD(EXPR_SIZEOF_ALIGN_OF);
784   RECORD(EXPR_ARRAY_SUBSCRIPT);
785   RECORD(EXPR_CALL);
786   RECORD(EXPR_MEMBER);
787   RECORD(EXPR_BINARY_OPERATOR);
788   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
789   RECORD(EXPR_CONDITIONAL_OPERATOR);
790   RECORD(EXPR_IMPLICIT_CAST);
791   RECORD(EXPR_CSTYLE_CAST);
792   RECORD(EXPR_COMPOUND_LITERAL);
793   RECORD(EXPR_EXT_VECTOR_ELEMENT);
794   RECORD(EXPR_INIT_LIST);
795   RECORD(EXPR_DESIGNATED_INIT);
796   RECORD(EXPR_DESIGNATED_INIT_UPDATE);
797   RECORD(EXPR_IMPLICIT_VALUE_INIT);
798   RECORD(EXPR_NO_INIT);
799   RECORD(EXPR_VA_ARG);
800   RECORD(EXPR_ADDR_LABEL);
801   RECORD(EXPR_STMT);
802   RECORD(EXPR_CHOOSE);
803   RECORD(EXPR_GNU_NULL);
804   RECORD(EXPR_SHUFFLE_VECTOR);
805   RECORD(EXPR_BLOCK);
806   RECORD(EXPR_GENERIC_SELECTION);
807   RECORD(EXPR_OBJC_STRING_LITERAL);
808   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
809   RECORD(EXPR_OBJC_ARRAY_LITERAL);
810   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
811   RECORD(EXPR_OBJC_ENCODE);
812   RECORD(EXPR_OBJC_SELECTOR_EXPR);
813   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
814   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
815   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
816   RECORD(EXPR_OBJC_KVC_REF_EXPR);
817   RECORD(EXPR_OBJC_MESSAGE_EXPR);
818   RECORD(STMT_OBJC_FOR_COLLECTION);
819   RECORD(STMT_OBJC_CATCH);
820   RECORD(STMT_OBJC_FINALLY);
821   RECORD(STMT_OBJC_AT_TRY);
822   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
823   RECORD(STMT_OBJC_AT_THROW);
824   RECORD(EXPR_OBJC_BOOL_LITERAL);
825   RECORD(STMT_CXX_CATCH);
826   RECORD(STMT_CXX_TRY);
827   RECORD(STMT_CXX_FOR_RANGE);
828   RECORD(EXPR_CXX_OPERATOR_CALL);
829   RECORD(EXPR_CXX_MEMBER_CALL);
830   RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
831   RECORD(EXPR_CXX_CONSTRUCT);
832   RECORD(EXPR_CXX_TEMPORARY_OBJECT);
833   RECORD(EXPR_CXX_STATIC_CAST);
834   RECORD(EXPR_CXX_DYNAMIC_CAST);
835   RECORD(EXPR_CXX_REINTERPRET_CAST);
836   RECORD(EXPR_CXX_CONST_CAST);
837   RECORD(EXPR_CXX_ADDRSPACE_CAST);
838   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
839   RECORD(EXPR_USER_DEFINED_LITERAL);
840   RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
841   RECORD(EXPR_CXX_BOOL_LITERAL);
842   RECORD(EXPR_CXX_PAREN_LIST_INIT);
843   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
844   RECORD(EXPR_CXX_TYPEID_EXPR);
845   RECORD(EXPR_CXX_TYPEID_TYPE);
846   RECORD(EXPR_CXX_THIS);
847   RECORD(EXPR_CXX_THROW);
848   RECORD(EXPR_CXX_DEFAULT_ARG);
849   RECORD(EXPR_CXX_DEFAULT_INIT);
850   RECORD(EXPR_CXX_BIND_TEMPORARY);
851   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
852   RECORD(EXPR_CXX_NEW);
853   RECORD(EXPR_CXX_DELETE);
854   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
855   RECORD(EXPR_EXPR_WITH_CLEANUPS);
856   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
857   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
858   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
859   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
860   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
861   RECORD(EXPR_CXX_EXPRESSION_TRAIT);
862   RECORD(EXPR_CXX_NOEXCEPT);
863   RECORD(EXPR_OPAQUE_VALUE);
864   RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
865   RECORD(EXPR_TYPE_TRAIT);
866   RECORD(EXPR_ARRAY_TYPE_TRAIT);
867   RECORD(EXPR_PACK_EXPANSION);
868   RECORD(EXPR_SIZEOF_PACK);
869   RECORD(EXPR_PACK_INDEXING);
870   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
871   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
872   RECORD(EXPR_FUNCTION_PARM_PACK);
873   RECORD(EXPR_MATERIALIZE_TEMPORARY);
874   RECORD(EXPR_CUDA_KERNEL_CALL);
875   RECORD(EXPR_CXX_UUIDOF_EXPR);
876   RECORD(EXPR_CXX_UUIDOF_TYPE);
877   RECORD(EXPR_LAMBDA);
878 #undef RECORD
879 }
880 
881 void ASTWriter::WriteBlockInfoBlock() {
882   RecordData Record;
883   Stream.EnterBlockInfoBlock();
884 
885 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
886 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
887 
888   // Control Block.
889   BLOCK(CONTROL_BLOCK);
890   RECORD(METADATA);
891   RECORD(MODULE_NAME);
892   RECORD(MODULE_DIRECTORY);
893   RECORD(MODULE_MAP_FILE);
894   RECORD(IMPORT);
895   RECORD(ORIGINAL_FILE);
896   RECORD(ORIGINAL_FILE_ID);
897   RECORD(INPUT_FILE_OFFSETS);
898 
899   BLOCK(OPTIONS_BLOCK);
900   RECORD(LANGUAGE_OPTIONS);
901   RECORD(TARGET_OPTIONS);
902   RECORD(FILE_SYSTEM_OPTIONS);
903   RECORD(HEADER_SEARCH_OPTIONS);
904   RECORD(PREPROCESSOR_OPTIONS);
905 
906   BLOCK(INPUT_FILES_BLOCK);
907   RECORD(INPUT_FILE);
908   RECORD(INPUT_FILE_HASH);
909 
910   // AST Top-Level Block.
911   BLOCK(AST_BLOCK);
912   RECORD(TYPE_OFFSET);
913   RECORD(DECL_OFFSET);
914   RECORD(IDENTIFIER_OFFSET);
915   RECORD(IDENTIFIER_TABLE);
916   RECORD(EAGERLY_DESERIALIZED_DECLS);
917   RECORD(MODULAR_CODEGEN_DECLS);
918   RECORD(SPECIAL_TYPES);
919   RECORD(STATISTICS);
920   RECORD(TENTATIVE_DEFINITIONS);
921   RECORD(SELECTOR_OFFSETS);
922   RECORD(METHOD_POOL);
923   RECORD(PP_COUNTER_VALUE);
924   RECORD(SOURCE_LOCATION_OFFSETS);
925   RECORD(EXT_VECTOR_DECLS);
926   RECORD(UNUSED_FILESCOPED_DECLS);
927   RECORD(PPD_ENTITIES_OFFSETS);
928   RECORD(VTABLE_USES);
929   RECORD(PPD_SKIPPED_RANGES);
930   RECORD(REFERENCED_SELECTOR_POOL);
931   RECORD(TU_UPDATE_LEXICAL);
932   RECORD(SEMA_DECL_REFS);
933   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
934   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
935   RECORD(UPDATE_VISIBLE);
936   RECORD(DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD);
937   RECORD(RELATED_DECLS_MAP);
938   RECORD(DECL_UPDATE_OFFSETS);
939   RECORD(DECL_UPDATES);
940   RECORD(CUDA_SPECIAL_DECL_REFS);
941   RECORD(HEADER_SEARCH_TABLE);
942   RECORD(FP_PRAGMA_OPTIONS);
943   RECORD(OPENCL_EXTENSIONS);
944   RECORD(OPENCL_EXTENSION_TYPES);
945   RECORD(OPENCL_EXTENSION_DECLS);
946   RECORD(DELEGATING_CTORS);
947   RECORD(KNOWN_NAMESPACES);
948   RECORD(MODULE_OFFSET_MAP);
949   RECORD(SOURCE_MANAGER_LINE_TABLE);
950   RECORD(OBJC_CATEGORIES_MAP);
951   RECORD(FILE_SORTED_DECLS);
952   RECORD(IMPORTED_MODULES);
953   RECORD(OBJC_CATEGORIES);
954   RECORD(MACRO_OFFSET);
955   RECORD(INTERESTING_IDENTIFIERS);
956   RECORD(UNDEFINED_BUT_USED);
957   RECORD(LATE_PARSED_TEMPLATE);
958   RECORD(OPTIMIZE_PRAGMA_OPTIONS);
959   RECORD(MSSTRUCT_PRAGMA_OPTIONS);
960   RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
961   RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
962   RECORD(DELETE_EXPRS_TO_ANALYZE);
963   RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
964   RECORD(PP_CONDITIONAL_STACK);
965   RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
966   RECORD(PP_ASSUME_NONNULL_LOC);
967   RECORD(PP_UNSAFE_BUFFER_USAGE);
968   RECORD(VTABLES_TO_EMIT);
969 
970   // SourceManager Block.
971   BLOCK(SOURCE_MANAGER_BLOCK);
972   RECORD(SM_SLOC_FILE_ENTRY);
973   RECORD(SM_SLOC_BUFFER_ENTRY);
974   RECORD(SM_SLOC_BUFFER_BLOB);
975   RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
976   RECORD(SM_SLOC_EXPANSION_ENTRY);
977 
978   // Preprocessor Block.
979   BLOCK(PREPROCESSOR_BLOCK);
980   RECORD(PP_MACRO_DIRECTIVE_HISTORY);
981   RECORD(PP_MACRO_FUNCTION_LIKE);
982   RECORD(PP_MACRO_OBJECT_LIKE);
983   RECORD(PP_MODULE_MACRO);
984   RECORD(PP_TOKEN);
985 
986   // Submodule Block.
987   BLOCK(SUBMODULE_BLOCK);
988   RECORD(SUBMODULE_METADATA);
989   RECORD(SUBMODULE_DEFINITION);
990   RECORD(SUBMODULE_UMBRELLA_HEADER);
991   RECORD(SUBMODULE_HEADER);
992   RECORD(SUBMODULE_TOPHEADER);
993   RECORD(SUBMODULE_UMBRELLA_DIR);
994   RECORD(SUBMODULE_IMPORTS);
995   RECORD(SUBMODULE_AFFECTING_MODULES);
996   RECORD(SUBMODULE_EXPORTS);
997   RECORD(SUBMODULE_REQUIRES);
998   RECORD(SUBMODULE_EXCLUDED_HEADER);
999   RECORD(SUBMODULE_LINK_LIBRARY);
1000   RECORD(SUBMODULE_CONFIG_MACRO);
1001   RECORD(SUBMODULE_CONFLICT);
1002   RECORD(SUBMODULE_PRIVATE_HEADER);
1003   RECORD(SUBMODULE_TEXTUAL_HEADER);
1004   RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1005   RECORD(SUBMODULE_INITIALIZERS);
1006   RECORD(SUBMODULE_EXPORT_AS);
1007 
1008   // Comments Block.
1009   BLOCK(COMMENTS_BLOCK);
1010   RECORD(COMMENTS_RAW_COMMENT);
1011 
1012   // Decls and Types block.
1013   BLOCK(DECLTYPES_BLOCK);
1014   RECORD(TYPE_EXT_QUAL);
1015   RECORD(TYPE_COMPLEX);
1016   RECORD(TYPE_POINTER);
1017   RECORD(TYPE_BLOCK_POINTER);
1018   RECORD(TYPE_LVALUE_REFERENCE);
1019   RECORD(TYPE_RVALUE_REFERENCE);
1020   RECORD(TYPE_MEMBER_POINTER);
1021   RECORD(TYPE_CONSTANT_ARRAY);
1022   RECORD(TYPE_INCOMPLETE_ARRAY);
1023   RECORD(TYPE_VARIABLE_ARRAY);
1024   RECORD(TYPE_VECTOR);
1025   RECORD(TYPE_EXT_VECTOR);
1026   RECORD(TYPE_FUNCTION_NO_PROTO);
1027   RECORD(TYPE_FUNCTION_PROTO);
1028   RECORD(TYPE_TYPEDEF);
1029   RECORD(TYPE_TYPEOF_EXPR);
1030   RECORD(TYPE_TYPEOF);
1031   RECORD(TYPE_RECORD);
1032   RECORD(TYPE_ENUM);
1033   RECORD(TYPE_OBJC_INTERFACE);
1034   RECORD(TYPE_OBJC_OBJECT_POINTER);
1035   RECORD(TYPE_DECLTYPE);
1036   RECORD(TYPE_ELABORATED);
1037   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1038   RECORD(TYPE_UNRESOLVED_USING);
1039   RECORD(TYPE_INJECTED_CLASS_NAME);
1040   RECORD(TYPE_OBJC_OBJECT);
1041   RECORD(TYPE_TEMPLATE_TYPE_PARM);
1042   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1043   RECORD(TYPE_DEPENDENT_NAME);
1044   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1045   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1046   RECORD(TYPE_PAREN);
1047   RECORD(TYPE_MACRO_QUALIFIED);
1048   RECORD(TYPE_PACK_EXPANSION);
1049   RECORD(TYPE_ATTRIBUTED);
1050   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1051   RECORD(TYPE_AUTO);
1052   RECORD(TYPE_UNARY_TRANSFORM);
1053   RECORD(TYPE_ATOMIC);
1054   RECORD(TYPE_DECAYED);
1055   RECORD(TYPE_ADJUSTED);
1056   RECORD(TYPE_OBJC_TYPE_PARAM);
1057   RECORD(LOCAL_REDECLARATIONS);
1058   RECORD(DECL_TYPEDEF);
1059   RECORD(DECL_TYPEALIAS);
1060   RECORD(DECL_ENUM);
1061   RECORD(DECL_RECORD);
1062   RECORD(DECL_ENUM_CONSTANT);
1063   RECORD(DECL_FUNCTION);
1064   RECORD(DECL_OBJC_METHOD);
1065   RECORD(DECL_OBJC_INTERFACE);
1066   RECORD(DECL_OBJC_PROTOCOL);
1067   RECORD(DECL_OBJC_IVAR);
1068   RECORD(DECL_OBJC_AT_DEFS_FIELD);
1069   RECORD(DECL_OBJC_CATEGORY);
1070   RECORD(DECL_OBJC_CATEGORY_IMPL);
1071   RECORD(DECL_OBJC_IMPLEMENTATION);
1072   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1073   RECORD(DECL_OBJC_PROPERTY);
1074   RECORD(DECL_OBJC_PROPERTY_IMPL);
1075   RECORD(DECL_FIELD);
1076   RECORD(DECL_MS_PROPERTY);
1077   RECORD(DECL_VAR);
1078   RECORD(DECL_IMPLICIT_PARAM);
1079   RECORD(DECL_PARM_VAR);
1080   RECORD(DECL_FILE_SCOPE_ASM);
1081   RECORD(DECL_BLOCK);
1082   RECORD(DECL_CONTEXT_LEXICAL);
1083   RECORD(DECL_CONTEXT_VISIBLE);
1084   RECORD(DECL_CONTEXT_MODULE_LOCAL_VISIBLE);
1085   RECORD(DECL_NAMESPACE);
1086   RECORD(DECL_NAMESPACE_ALIAS);
1087   RECORD(DECL_USING);
1088   RECORD(DECL_USING_SHADOW);
1089   RECORD(DECL_USING_DIRECTIVE);
1090   RECORD(DECL_UNRESOLVED_USING_VALUE);
1091   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1092   RECORD(DECL_LINKAGE_SPEC);
1093   RECORD(DECL_EXPORT);
1094   RECORD(DECL_CXX_RECORD);
1095   RECORD(DECL_CXX_METHOD);
1096   RECORD(DECL_CXX_CONSTRUCTOR);
1097   RECORD(DECL_CXX_DESTRUCTOR);
1098   RECORD(DECL_CXX_CONVERSION);
1099   RECORD(DECL_ACCESS_SPEC);
1100   RECORD(DECL_FRIEND);
1101   RECORD(DECL_FRIEND_TEMPLATE);
1102   RECORD(DECL_CLASS_TEMPLATE);
1103   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1104   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1105   RECORD(DECL_VAR_TEMPLATE);
1106   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1107   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1108   RECORD(DECL_FUNCTION_TEMPLATE);
1109   RECORD(DECL_TEMPLATE_TYPE_PARM);
1110   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1111   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1112   RECORD(DECL_CONCEPT);
1113   RECORD(DECL_REQUIRES_EXPR_BODY);
1114   RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1115   RECORD(DECL_STATIC_ASSERT);
1116   RECORD(DECL_CXX_BASE_SPECIFIERS);
1117   RECORD(DECL_CXX_CTOR_INITIALIZERS);
1118   RECORD(DECL_INDIRECTFIELD);
1119   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1120   RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1121   RECORD(DECL_IMPORT);
1122   RECORD(DECL_OMP_THREADPRIVATE);
1123   RECORD(DECL_EMPTY);
1124   RECORD(DECL_OBJC_TYPE_PARAM);
1125   RECORD(DECL_OMP_CAPTUREDEXPR);
1126   RECORD(DECL_PRAGMA_COMMENT);
1127   RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1128   RECORD(DECL_OMP_DECLARE_REDUCTION);
1129   RECORD(DECL_OMP_ALLOCATE);
1130   RECORD(DECL_HLSL_BUFFER);
1131   RECORD(DECL_OPENACC_DECLARE);
1132   RECORD(DECL_OPENACC_ROUTINE);
1133 
1134   // Statements and Exprs can occur in the Decls and Types block.
1135   AddStmtsExprs(Stream, Record);
1136 
1137   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1138   RECORD(PPD_MACRO_EXPANSION);
1139   RECORD(PPD_MACRO_DEFINITION);
1140   RECORD(PPD_INCLUSION_DIRECTIVE);
1141 
1142   // Decls and Types block.
1143   BLOCK(EXTENSION_BLOCK);
1144   RECORD(EXTENSION_METADATA);
1145 
1146   BLOCK(UNHASHED_CONTROL_BLOCK);
1147   RECORD(SIGNATURE);
1148   RECORD(AST_BLOCK_HASH);
1149   RECORD(DIAGNOSTIC_OPTIONS);
1150   RECORD(HEADER_SEARCH_PATHS);
1151   RECORD(DIAG_PRAGMA_MAPPINGS);
1152   RECORD(HEADER_SEARCH_ENTRY_USAGE);
1153   RECORD(VFS_USAGE);
1154 
1155 #undef RECORD
1156 #undef BLOCK
1157   Stream.ExitBlock();
1158 }
1159 
1160 /// Prepares a path for being written to an AST file by converting it
1161 /// to an absolute path and removing nested './'s.
1162 ///
1163 /// \return \c true if the path was changed.
1164 static bool cleanPathForOutput(FileManager &FileMgr,
1165                                SmallVectorImpl<char> &Path) {
1166   bool Changed = FileMgr.makeAbsolutePath(Path);
1167   return Changed | llvm::sys::path::remove_dots(Path);
1168 }
1169 
1170 /// Adjusts the given filename to only write out the portion of the
1171 /// filename that is not part of the system root directory.
1172 ///
1173 /// \param Filename the file name to adjust.
1174 ///
1175 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1176 /// the returned filename will be adjusted by this root directory.
1177 ///
1178 /// \returns either the original filename (if it needs no adjustment) or the
1179 /// adjusted filename (which points into the @p Filename parameter).
1180 static const char *
1181 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1182   assert(Filename && "No file name to adjust?");
1183 
1184   if (BaseDir.empty())
1185     return Filename;
1186 
1187   // Verify that the filename and the system root have the same prefix.
1188   unsigned Pos = 0;
1189   for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1190     if (Filename[Pos] != BaseDir[Pos])
1191       return Filename; // Prefixes don't match.
1192 
1193   // We hit the end of the filename before we hit the end of the system root.
1194   if (!Filename[Pos])
1195     return Filename;
1196 
1197   // If there's not a path separator at the end of the base directory nor
1198   // immediately after it, then this isn't within the base directory.
1199   if (!llvm::sys::path::is_separator(Filename[Pos])) {
1200     if (!llvm::sys::path::is_separator(BaseDir.back()))
1201       return Filename;
1202   } else {
1203     // If the file name has a '/' at the current position, skip over the '/'.
1204     // We distinguish relative paths from absolute paths by the
1205     // absence of '/' at the beginning of relative paths.
1206     //
1207     // FIXME: This is wrong. We distinguish them by asking if the path is
1208     // absolute, which isn't the same thing. And there might be multiple '/'s
1209     // in a row. Use a better mechanism to indicate whether we have emitted an
1210     // absolute or relative path.
1211     ++Pos;
1212   }
1213 
1214   return Filename + Pos;
1215 }
1216 
1217 std::pair<ASTFileSignature, ASTFileSignature>
1218 ASTWriter::createSignature() const {
1219   StringRef AllBytes(Buffer.data(), Buffer.size());
1220 
1221   llvm::SHA1 Hasher;
1222   Hasher.update(AllBytes.slice(ASTBlockRange.first, ASTBlockRange.second));
1223   ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1224 
1225   // Add the remaining bytes:
1226   //  1. Before the unhashed control block.
1227   Hasher.update(AllBytes.slice(0, UnhashedControlBlockRange.first));
1228   //  2. Between the unhashed control block and the AST block.
1229   Hasher.update(
1230       AllBytes.slice(UnhashedControlBlockRange.second, ASTBlockRange.first));
1231   //  3. After the AST block.
1232   Hasher.update(AllBytes.substr(ASTBlockRange.second));
1233   ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1234 
1235   return std::make_pair(ASTBlockHash, Signature);
1236 }
1237 
1238 ASTFileSignature ASTWriter::createSignatureForNamedModule() const {
1239   llvm::SHA1 Hasher;
1240   Hasher.update(StringRef(Buffer.data(), Buffer.size()));
1241 
1242   assert(WritingModule);
1243   assert(WritingModule->isNamedModule());
1244 
1245   // We need to combine all the export imported modules no matter
1246   // we used it or not.
1247   for (auto [ExportImported, _] : WritingModule->Exports)
1248     Hasher.update(ExportImported->Signature);
1249 
1250   // We combine all the used modules to make sure the signature is precise.
1251   // Consider the case like:
1252   //
1253   // // a.cppm
1254   // export module a;
1255   // export inline int a() { ... }
1256   //
1257   // // b.cppm
1258   // export module b;
1259   // import a;
1260   // export inline int b() { return a(); }
1261   //
1262   // Since both `a()` and `b()` are inline, we need to make sure the BMI of
1263   // `b.pcm` will change after the implementation of `a()` changes. We can't
1264   // get that naturally since we won't record the body of `a()` during the
1265   // writing process. We can't reuse ODRHash here since ODRHash won't calculate
1266   // the called function recursively. So ODRHash will be problematic if `a()`
1267   // calls other inline functions.
1268   //
1269   // Probably we can solve this by a new hash mechanism. But the safety and
1270   // efficiency may a problem too. Here we just combine the hash value of the
1271   // used modules conservatively.
1272   for (Module *M : TouchedTopLevelModules)
1273     Hasher.update(M->Signature);
1274 
1275   return ASTFileSignature::create(Hasher.result());
1276 }
1277 
1278 static void BackpatchSignatureAt(llvm::BitstreamWriter &Stream,
1279                                  const ASTFileSignature &S, uint64_t BitNo) {
1280   for (uint8_t Byte : S) {
1281     Stream.BackpatchByte(BitNo, Byte);
1282     BitNo += 8;
1283   }
1284 }
1285 
1286 ASTFileSignature ASTWriter::backpatchSignature() {
1287   if (isWritingStdCXXNamedModules()) {
1288     ASTFileSignature Signature = createSignatureForNamedModule();
1289     BackpatchSignatureAt(Stream, Signature, SignatureOffset);
1290     return Signature;
1291   }
1292 
1293   if (!WritingModule ||
1294       !PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)
1295     return {};
1296 
1297   // For implicit modules, write the hash of the PCM as its signature.
1298   ASTFileSignature ASTBlockHash;
1299   ASTFileSignature Signature;
1300   std::tie(ASTBlockHash, Signature) = createSignature();
1301 
1302   BackpatchSignatureAt(Stream, ASTBlockHash, ASTBlockHashOffset);
1303   BackpatchSignatureAt(Stream, Signature, SignatureOffset);
1304 
1305   return Signature;
1306 }
1307 
1308 void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP) {
1309   using namespace llvm;
1310 
1311   // Flush first to prepare the PCM hash (signature).
1312   Stream.FlushToWord();
1313   UnhashedControlBlockRange.first = Stream.GetCurrentBitNo() >> 3;
1314 
1315   // Enter the block and prepare to write records.
1316   RecordData Record;
1317   Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1318 
1319   // For implicit modules and C++20 named modules, write the hash of the PCM as
1320   // its signature.
1321   if (isWritingStdCXXNamedModules() ||
1322       (WritingModule &&
1323        PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)) {
1324     // At this point, we don't know the actual signature of the file or the AST
1325     // block - we're only able to compute those at the end of the serialization
1326     // process. Let's store dummy signatures for now, and replace them with the
1327     // real ones later on.
1328     // The bitstream VBR-encodes record elements, which makes backpatching them
1329     // really difficult. Let's store the signatures as blobs instead - they are
1330     // guaranteed to be word-aligned, and we control their format/encoding.
1331     auto Dummy = ASTFileSignature::createDummy();
1332     SmallString<128> Blob{Dummy.begin(), Dummy.end()};
1333 
1334     // We don't need AST Block hash in named modules.
1335     if (!isWritingStdCXXNamedModules()) {
1336       auto Abbrev = std::make_shared<BitCodeAbbrev>();
1337       Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH));
1338       Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1339       unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1340 
1341       Record.push_back(AST_BLOCK_HASH);
1342       Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob);
1343       ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1344       Record.clear();
1345     }
1346 
1347     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1348     Abbrev->Add(BitCodeAbbrevOp(SIGNATURE));
1349     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1350     unsigned SignatureAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1351 
1352     Record.push_back(SIGNATURE);
1353     Stream.EmitRecordWithBlob(SignatureAbbrev, Record, Blob);
1354     SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1355     Record.clear();
1356   }
1357 
1358   const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1359 
1360   // Diagnostic options.
1361   const auto &Diags = PP.getDiagnostics();
1362   const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1363   if (!HSOpts.ModulesSkipDiagnosticOptions) {
1364 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1365 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1366   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1367 #include "clang/Basic/DiagnosticOptions.def"
1368     Record.push_back(DiagOpts.Warnings.size());
1369     for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1370       AddString(DiagOpts.Warnings[I], Record);
1371     Record.push_back(DiagOpts.Remarks.size());
1372     for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1373       AddString(DiagOpts.Remarks[I], Record);
1374     // Note: we don't serialize the log or serialization file names, because
1375     // they are generally transient files and will almost always be overridden.
1376     Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1377     Record.clear();
1378   }
1379 
1380   // Header search paths.
1381   if (!HSOpts.ModulesSkipHeaderSearchPaths) {
1382     // Include entries.
1383     Record.push_back(HSOpts.UserEntries.size());
1384     for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1385       const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1386       AddString(Entry.Path, Record);
1387       Record.push_back(static_cast<unsigned>(Entry.Group));
1388       Record.push_back(Entry.IsFramework);
1389       Record.push_back(Entry.IgnoreSysRoot);
1390     }
1391 
1392     // System header prefixes.
1393     Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1394     for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1395       AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1396       Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1397     }
1398 
1399     // VFS overlay files.
1400     Record.push_back(HSOpts.VFSOverlayFiles.size());
1401     for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1402       AddString(VFSOverlayFile, Record);
1403 
1404     Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
1405   }
1406 
1407   if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
1408     WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1409 
1410   // Header search entry usage.
1411   {
1412     auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1413     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1414     Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1415     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1416     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Bit vector.
1417     unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1418     RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1419                                        HSEntryUsage.size()};
1420     Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1421   }
1422 
1423   // VFS usage.
1424   {
1425     auto VFSUsage = PP.getHeaderSearchInfo().collectVFSUsageAndClear();
1426     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1427     Abbrev->Add(BitCodeAbbrevOp(VFS_USAGE));
1428     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1429     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Bit vector.
1430     unsigned VFSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1431     RecordData::value_type Record[] = {VFS_USAGE, VFSUsage.size()};
1432     Stream.EmitRecordWithBlob(VFSUsageAbbrevCode, Record, bytes(VFSUsage));
1433   }
1434 
1435   // Leave the options block.
1436   Stream.ExitBlock();
1437   UnhashedControlBlockRange.second = Stream.GetCurrentBitNo() >> 3;
1438 }
1439 
1440 /// Write the control block.
1441 void ASTWriter::WriteControlBlock(Preprocessor &PP, StringRef isysroot) {
1442   using namespace llvm;
1443 
1444   SourceManager &SourceMgr = PP.getSourceManager();
1445   FileManager &FileMgr = PP.getFileManager();
1446 
1447   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1448   RecordData Record;
1449 
1450   // Metadata
1451   auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1452   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1453   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1454   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1455   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1456   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1457   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1458   // Standard C++ module
1459   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1460   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1461   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1462   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1463   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1464   assert((!WritingModule || isysroot.empty()) &&
1465          "writing module as a relocatable PCH?");
1466   {
1467     RecordData::value_type Record[] = {METADATA,
1468                                        VERSION_MAJOR,
1469                                        VERSION_MINOR,
1470                                        CLANG_VERSION_MAJOR,
1471                                        CLANG_VERSION_MINOR,
1472                                        !isysroot.empty(),
1473                                        isWritingStdCXXNamedModules(),
1474                                        IncludeTimestamps,
1475                                        ASTHasCompilerErrors};
1476     Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1477                               getClangFullRepositoryVersion());
1478   }
1479 
1480   if (WritingModule) {
1481     // Module name
1482     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1483     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1484     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1485     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1486     RecordData::value_type Record[] = {MODULE_NAME};
1487     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1488 
1489     auto BaseDir = [&]() -> std::optional<SmallString<128>> {
1490       if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1491         // Use the current working directory as the base path for all inputs.
1492         auto CWD = FileMgr.getOptionalDirectoryRef(".");
1493         return CWD->getName();
1494       }
1495       if (WritingModule->Directory) {
1496         return WritingModule->Directory->getName();
1497       }
1498       return std::nullopt;
1499     }();
1500     if (BaseDir) {
1501       cleanPathForOutput(FileMgr, *BaseDir);
1502 
1503       // If the home of the module is the current working directory, then we
1504       // want to pick up the cwd of the build process loading the module, not
1505       // our cwd, when we load this module.
1506       if (!PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd &&
1507           (!PP.getHeaderSearchInfo()
1508                 .getHeaderSearchOpts()
1509                 .ModuleMapFileHomeIsCwd ||
1510            WritingModule->Directory->getName() != ".")) {
1511         // Module directory.
1512         auto Abbrev = std::make_shared<BitCodeAbbrev>();
1513         Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1514         Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1515         unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1516 
1517         RecordData::value_type Record[] = {MODULE_DIRECTORY};
1518         Stream.EmitRecordWithBlob(AbbrevCode, Record, *BaseDir);
1519       }
1520 
1521       // Write out all other paths relative to the base directory if possible.
1522       BaseDirectory.assign(BaseDir->begin(), BaseDir->end());
1523     } else if (!isysroot.empty()) {
1524       // Write out paths relative to the sysroot if possible.
1525       BaseDirectory = std::string(isysroot);
1526     }
1527   }
1528 
1529   // Module map file
1530   if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1531     Record.clear();
1532 
1533     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1534     AddPath(WritingModule->PresumedModuleMapFile.empty()
1535                 ? Map.getModuleMapFileForUniquing(WritingModule)
1536                       ->getNameAsRequested()
1537                 : StringRef(WritingModule->PresumedModuleMapFile),
1538             Record);
1539 
1540     // Additional module map files.
1541     if (auto *AdditionalModMaps =
1542             Map.getAdditionalModuleMapFiles(WritingModule)) {
1543       Record.push_back(AdditionalModMaps->size());
1544       SmallVector<FileEntryRef, 1> ModMaps(AdditionalModMaps->begin(),
1545                                            AdditionalModMaps->end());
1546       llvm::sort(ModMaps, [](FileEntryRef A, FileEntryRef B) {
1547         return A.getName() < B.getName();
1548       });
1549       for (FileEntryRef F : ModMaps)
1550         AddPath(F.getName(), Record);
1551     } else {
1552       Record.push_back(0);
1553     }
1554 
1555     Stream.EmitRecord(MODULE_MAP_FILE, Record);
1556   }
1557 
1558   // Imports
1559   if (Chain) {
1560     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1561     Abbrev->Add(BitCodeAbbrevOp(IMPORT));
1562     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
1563     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ImportLoc
1564     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Module name len
1565     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Standard C++ mod
1566     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File size
1567     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File timestamp
1568     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File name len
1569     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Strings
1570     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1571 
1572     SmallString<128> Blob;
1573 
1574     for (ModuleFile &M : Chain->getModuleManager()) {
1575       // Skip modules that weren't directly imported.
1576       if (!M.isDirectlyImported())
1577         continue;
1578 
1579       Record.clear();
1580       Blob.clear();
1581 
1582       Record.push_back(IMPORT);
1583       Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1584       AddSourceLocation(M.ImportLoc, Record);
1585       AddStringBlob(M.ModuleName, Record, Blob);
1586       Record.push_back(M.StandardCXXModule);
1587 
1588       // We don't want to hard code the information about imported modules
1589       // in the C++20 named modules.
1590       if (M.StandardCXXModule) {
1591         Record.push_back(0);
1592         Record.push_back(0);
1593         Record.push_back(0);
1594       } else {
1595         // If we have calculated signature, there is no need to store
1596         // the size or timestamp.
1597         Record.push_back(M.Signature ? 0 : M.File.getSize());
1598         Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1599 
1600         llvm::append_range(Blob, M.Signature);
1601 
1602         AddPathBlob(M.FileName, Record, Blob);
1603       }
1604 
1605       Stream.EmitRecordWithBlob(AbbrevCode, Record, Blob);
1606     }
1607   }
1608 
1609   // Write the options block.
1610   Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1611 
1612   // Language options.
1613   Record.clear();
1614   const LangOptions &LangOpts = PP.getLangOpts();
1615 #define LANGOPT(Name, Bits, Default, Compatibility, Description)               \
1616   Record.push_back(LangOpts.Name);
1617 #define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description)    \
1618   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1619 #include "clang/Basic/LangOptions.def"
1620 #define SANITIZER(NAME, ID)                                                    \
1621   Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1622 #include "clang/Basic/Sanitizers.def"
1623 
1624   Record.push_back(LangOpts.ModuleFeatures.size());
1625   for (StringRef Feature : LangOpts.ModuleFeatures)
1626     AddString(Feature, Record);
1627 
1628   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1629   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1630 
1631   AddString(LangOpts.CurrentModule, Record);
1632 
1633   // Comment options.
1634   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1635   for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1636     AddString(I, Record);
1637   }
1638   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1639 
1640   // OpenMP offloading options.
1641   Record.push_back(LangOpts.OMPTargetTriples.size());
1642   for (auto &T : LangOpts.OMPTargetTriples)
1643     AddString(T.getTriple(), Record);
1644 
1645   AddString(LangOpts.OMPHostIRFile, Record);
1646 
1647   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1648 
1649   // Target options.
1650   Record.clear();
1651   const TargetInfo &Target = PP.getTargetInfo();
1652   const TargetOptions &TargetOpts = Target.getTargetOpts();
1653   AddString(TargetOpts.Triple, Record);
1654   AddString(TargetOpts.CPU, Record);
1655   AddString(TargetOpts.TuneCPU, Record);
1656   AddString(TargetOpts.ABI, Record);
1657   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1658   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1659     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1660   }
1661   Record.push_back(TargetOpts.Features.size());
1662   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1663     AddString(TargetOpts.Features[I], Record);
1664   }
1665   Stream.EmitRecord(TARGET_OPTIONS, Record);
1666 
1667   // File system options.
1668   Record.clear();
1669   const FileSystemOptions &FSOpts = FileMgr.getFileSystemOpts();
1670   AddString(FSOpts.WorkingDir, Record);
1671   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1672 
1673   // Header search options.
1674   Record.clear();
1675   const HeaderSearchOptions &HSOpts =
1676       PP.getHeaderSearchInfo().getHeaderSearchOpts();
1677 
1678   AddString(HSOpts.Sysroot, Record);
1679   AddString(HSOpts.ResourceDir, Record);
1680   AddString(HSOpts.ModuleCachePath, Record);
1681   AddString(HSOpts.ModuleUserBuildPath, Record);
1682   Record.push_back(HSOpts.DisableModuleHash);
1683   Record.push_back(HSOpts.ImplicitModuleMaps);
1684   Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1685   Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1686   Record.push_back(HSOpts.UseBuiltinIncludes);
1687   Record.push_back(HSOpts.UseStandardSystemIncludes);
1688   Record.push_back(HSOpts.UseStandardCXXIncludes);
1689   Record.push_back(HSOpts.UseLibcxx);
1690   // Write out the specific module cache path that contains the module files.
1691   AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1692   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1693 
1694   // Preprocessor options.
1695   Record.clear();
1696   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1697 
1698   // If we're building an implicit module with a context hash, the importer is
1699   // guaranteed to have the same macros defined on the command line. Skip
1700   // writing them.
1701   bool SkipMacros = BuildingImplicitModule && !HSOpts.DisableModuleHash;
1702   bool WriteMacros = !SkipMacros;
1703   Record.push_back(WriteMacros);
1704   if (WriteMacros) {
1705     // Macro definitions.
1706     Record.push_back(PPOpts.Macros.size());
1707     for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1708       AddString(PPOpts.Macros[I].first, Record);
1709       Record.push_back(PPOpts.Macros[I].second);
1710     }
1711   }
1712 
1713   // Includes
1714   Record.push_back(PPOpts.Includes.size());
1715   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1716     AddString(PPOpts.Includes[I], Record);
1717 
1718   // Macro includes
1719   Record.push_back(PPOpts.MacroIncludes.size());
1720   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1721     AddString(PPOpts.MacroIncludes[I], Record);
1722 
1723   Record.push_back(PPOpts.UsePredefines);
1724   // Detailed record is important since it is used for the module cache hash.
1725   Record.push_back(PPOpts.DetailedRecord);
1726   AddString(PPOpts.ImplicitPCHInclude, Record);
1727   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1728   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1729 
1730   // Leave the options block.
1731   Stream.ExitBlock();
1732 
1733   // Original file name and file ID
1734   if (auto MainFile =
1735           SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID())) {
1736     auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1737     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1738     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1739     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1740     unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1741 
1742     Record.clear();
1743     Record.push_back(ORIGINAL_FILE);
1744     AddFileID(SourceMgr.getMainFileID(), Record);
1745     EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1746   }
1747 
1748   Record.clear();
1749   AddFileID(SourceMgr.getMainFileID(), Record);
1750   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1751 
1752   WriteInputFiles(SourceMgr);
1753   Stream.ExitBlock();
1754 }
1755 
1756 namespace  {
1757 
1758 /// An input file.
1759 struct InputFileEntry {
1760   FileEntryRef File;
1761   bool IsSystemFile;
1762   bool IsTransient;
1763   bool BufferOverridden;
1764   bool IsTopLevel;
1765   bool IsModuleMap;
1766   uint32_t ContentHash[2];
1767 
1768   InputFileEntry(FileEntryRef File) : File(File) {}
1769 
1770   void trySetContentHash(
1771       Preprocessor &PP,
1772       llvm::function_ref<std::optional<llvm::MemoryBufferRef>()> GetMemBuff) {
1773     ContentHash[0] = 0;
1774     ContentHash[1] = 0;
1775 
1776     if (!PP.getHeaderSearchInfo()
1777              .getHeaderSearchOpts()
1778              .ValidateASTInputFilesContent)
1779       return;
1780 
1781     auto MemBuff = GetMemBuff();
1782     if (!MemBuff) {
1783       PP.Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1784           << File.getName();
1785       return;
1786     }
1787 
1788     uint64_t Hash = xxh3_64bits(MemBuff->getBuffer());
1789     ContentHash[0] = uint32_t(Hash);
1790     ContentHash[1] = uint32_t(Hash >> 32);
1791   }
1792 };
1793 
1794 } // namespace
1795 
1796 SourceLocation ASTWriter::getAffectingIncludeLoc(const SourceManager &SourceMgr,
1797                                                  const SrcMgr::FileInfo &File) {
1798   SourceLocation IncludeLoc = File.getIncludeLoc();
1799   if (IncludeLoc.isValid()) {
1800     FileID IncludeFID = SourceMgr.getFileID(IncludeLoc);
1801     assert(IncludeFID.isValid() && "IncludeLoc in invalid file");
1802     if (!IsSLocAffecting[IncludeFID.ID])
1803       IncludeLoc = SourceLocation();
1804   }
1805   return IncludeLoc;
1806 }
1807 
1808 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr) {
1809   using namespace llvm;
1810 
1811   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1812 
1813   // Create input-file abbreviation.
1814   auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1815   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1816   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1817   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1818   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1819   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1820   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1821   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
1822   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1823   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
1824   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
1825   unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1826 
1827   // Create input file hash abbreviation.
1828   auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1829   IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1830   IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1831   IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1832   unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1833 
1834   uint64_t InputFilesOffsetBase = Stream.GetCurrentBitNo();
1835 
1836   // Get all ContentCache objects for files.
1837   std::vector<InputFileEntry> UserFiles;
1838   std::vector<InputFileEntry> SystemFiles;
1839   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1840     // Get this source location entry.
1841     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1842     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1843 
1844     // We only care about file entries that were not overridden.
1845     if (!SLoc->isFile())
1846       continue;
1847     const SrcMgr::FileInfo &File = SLoc->getFile();
1848     const SrcMgr::ContentCache *Cache = &File.getContentCache();
1849     if (!Cache->OrigEntry)
1850       continue;
1851 
1852     // Do not emit input files that do not affect current module.
1853     if (!IsSLocFileEntryAffecting[I])
1854       continue;
1855 
1856     InputFileEntry Entry(*Cache->OrigEntry);
1857     Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1858     Entry.IsTransient = Cache->IsTransient;
1859     Entry.BufferOverridden = Cache->BufferOverridden;
1860 
1861     FileID IncludeFileID = SourceMgr.getFileID(File.getIncludeLoc());
1862     Entry.IsTopLevel = IncludeFileID.isInvalid() || IncludeFileID.ID < 0 ||
1863                        !IsSLocFileEntryAffecting[IncludeFileID.ID];
1864     Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic());
1865 
1866     Entry.trySetContentHash(*PP, [&] { return Cache->getBufferIfLoaded(); });
1867 
1868     if (Entry.IsSystemFile)
1869       SystemFiles.push_back(Entry);
1870     else
1871       UserFiles.push_back(Entry);
1872   }
1873 
1874   // FIXME: Make providing input files not in the SourceManager more flexible.
1875   // The SDKSettings.json file is necessary for correct evaluation of
1876   // availability annotations.
1877   StringRef Sysroot = PP->getHeaderSearchInfo().getHeaderSearchOpts().Sysroot;
1878   if (!Sysroot.empty()) {
1879     SmallString<128> SDKSettingsJSON = Sysroot;
1880     llvm::sys::path::append(SDKSettingsJSON, "SDKSettings.json");
1881     FileManager &FM = PP->getFileManager();
1882     if (auto FE = FM.getOptionalFileRef(SDKSettingsJSON)) {
1883       InputFileEntry Entry(*FE);
1884       Entry.IsSystemFile = true;
1885       Entry.IsTransient = false;
1886       Entry.BufferOverridden = false;
1887       Entry.IsTopLevel = true;
1888       Entry.IsModuleMap = false;
1889       std::unique_ptr<MemoryBuffer> MB;
1890       Entry.trySetContentHash(*PP, [&]() -> std::optional<MemoryBufferRef> {
1891         if (auto MBOrErr = FM.getBufferForFile(Entry.File)) {
1892           MB = std::move(*MBOrErr);
1893           return MB->getMemBufferRef();
1894         }
1895         return std::nullopt;
1896       });
1897       SystemFiles.push_back(Entry);
1898     }
1899   }
1900 
1901   // User files go at the front, system files at the back.
1902   auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1903                                                   std::move(SystemFiles));
1904 
1905   unsigned UserFilesNum = 0;
1906   // Write out all of the input files.
1907   std::vector<uint64_t> InputFileOffsets;
1908   for (const auto &Entry : SortedFiles) {
1909     uint32_t &InputFileID = InputFileIDs[Entry.File];
1910     if (InputFileID != 0)
1911       continue; // already recorded this file.
1912 
1913     // Record this entry's offset.
1914     InputFileOffsets.push_back(Stream.GetCurrentBitNo() - InputFilesOffsetBase);
1915 
1916     InputFileID = InputFileOffsets.size();
1917 
1918     if (!Entry.IsSystemFile)
1919       ++UserFilesNum;
1920 
1921     // Emit size/modification time for this file.
1922     // And whether this file was overridden.
1923     {
1924       SmallString<128> NameAsRequested = Entry.File.getNameAsRequested();
1925       SmallString<128> Name = Entry.File.getName();
1926 
1927       PreparePathForOutput(NameAsRequested);
1928       PreparePathForOutput(Name);
1929 
1930       if (Name == NameAsRequested)
1931         Name.clear();
1932 
1933       RecordData::value_type Record[] = {
1934           INPUT_FILE,
1935           InputFileOffsets.size(),
1936           (uint64_t)Entry.File.getSize(),
1937           (uint64_t)getTimestampForOutput(Entry.File),
1938           Entry.BufferOverridden,
1939           Entry.IsTransient,
1940           Entry.IsTopLevel,
1941           Entry.IsModuleMap,
1942           NameAsRequested.size()};
1943 
1944       Stream.EmitRecordWithBlob(IFAbbrevCode, Record,
1945                                 (NameAsRequested + Name).str());
1946     }
1947 
1948     // Emit content hash for this file.
1949     {
1950       RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1951                                          Entry.ContentHash[1]};
1952       Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1953     }
1954   }
1955 
1956   Stream.ExitBlock();
1957 
1958   // Create input file offsets abbreviation.
1959   auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1960   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1961   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1962   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1963                                                                 //   input files
1964   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1965   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1966 
1967   // Write input file offsets.
1968   RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1969                                      InputFileOffsets.size(), UserFilesNum};
1970   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1971 }
1972 
1973 //===----------------------------------------------------------------------===//
1974 // Source Manager Serialization
1975 //===----------------------------------------------------------------------===//
1976 
1977 /// Create an abbreviation for the SLocEntry that refers to a
1978 /// file.
1979 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1980   using namespace llvm;
1981 
1982   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1983   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1984   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1985   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1986   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1987   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1988   // FileEntry fields.
1989   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1990   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1991   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1992   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1993   return Stream.EmitAbbrev(std::move(Abbrev));
1994 }
1995 
1996 /// Create an abbreviation for the SLocEntry that refers to a
1997 /// buffer.
1998 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1999   using namespace llvm;
2000 
2001   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2002   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
2003   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2004   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
2005   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
2006   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
2007   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
2008   return Stream.EmitAbbrev(std::move(Abbrev));
2009 }
2010 
2011 /// Create an abbreviation for the SLocEntry that refers to a
2012 /// buffer's blob.
2013 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
2014                                            bool Compressed) {
2015   using namespace llvm;
2016 
2017   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2018   Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
2019                                          : SM_SLOC_BUFFER_BLOB));
2020   if (Compressed)
2021     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
2022   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
2023   return Stream.EmitAbbrev(std::move(Abbrev));
2024 }
2025 
2026 /// Create an abbreviation for the SLocEntry that refers to a macro
2027 /// expansion.
2028 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
2029   using namespace llvm;
2030 
2031   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2032   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
2033   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2034   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
2035   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
2036   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
2037   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
2038   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
2039   return Stream.EmitAbbrev(std::move(Abbrev));
2040 }
2041 
2042 /// Emit key length and data length as ULEB-encoded data, and return them as a
2043 /// pair.
2044 static std::pair<unsigned, unsigned>
2045 emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
2046   llvm::encodeULEB128(KeyLen, Out);
2047   llvm::encodeULEB128(DataLen, Out);
2048   return std::make_pair(KeyLen, DataLen);
2049 }
2050 
2051 namespace {
2052 
2053   // Trait used for the on-disk hash table of header search information.
2054   class HeaderFileInfoTrait {
2055     ASTWriter &Writer;
2056 
2057   public:
2058     HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
2059 
2060     struct key_type {
2061       StringRef Filename;
2062       off_t Size;
2063       time_t ModTime;
2064     };
2065     using key_type_ref = const key_type &;
2066 
2067     using UnresolvedModule =
2068         llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
2069 
2070     struct data_type {
2071       data_type(const HeaderFileInfo &HFI, bool AlreadyIncluded,
2072                 ArrayRef<ModuleMap::KnownHeader> KnownHeaders,
2073                 UnresolvedModule Unresolved)
2074           : HFI(HFI), AlreadyIncluded(AlreadyIncluded),
2075             KnownHeaders(KnownHeaders), Unresolved(Unresolved) {}
2076 
2077       HeaderFileInfo HFI;
2078       bool AlreadyIncluded;
2079       SmallVector<ModuleMap::KnownHeader, 1> KnownHeaders;
2080       UnresolvedModule Unresolved;
2081     };
2082     using data_type_ref = const data_type &;
2083 
2084     using hash_value_type = unsigned;
2085     using offset_type = unsigned;
2086 
2087     hash_value_type ComputeHash(key_type_ref key) {
2088       // The hash is based only on size/time of the file, so that the reader can
2089       // match even when symlinking or excess path elements ("foo/../", "../")
2090       // change the form of the name. However, complete path is still the key.
2091       uint8_t buf[sizeof(key.Size) + sizeof(key.ModTime)];
2092       memcpy(buf, &key.Size, sizeof(key.Size));
2093       memcpy(buf + sizeof(key.Size), &key.ModTime, sizeof(key.ModTime));
2094       return llvm::xxh3_64bits(buf);
2095     }
2096 
2097     std::pair<unsigned, unsigned>
2098     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
2099       unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
2100       unsigned DataLen = 1 + sizeof(IdentifierID);
2101       for (auto ModInfo : Data.KnownHeaders)
2102         if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
2103           DataLen += 4;
2104       if (Data.Unresolved.getPointer())
2105         DataLen += 4;
2106       return emitULEBKeyDataLength(KeyLen, DataLen, Out);
2107     }
2108 
2109     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
2110       using namespace llvm::support;
2111 
2112       endian::Writer LE(Out, llvm::endianness::little);
2113       LE.write<uint64_t>(key.Size);
2114       KeyLen -= 8;
2115       LE.write<uint64_t>(key.ModTime);
2116       KeyLen -= 8;
2117       Out.write(key.Filename.data(), KeyLen);
2118     }
2119 
2120     void EmitData(raw_ostream &Out, key_type_ref key,
2121                   data_type_ref Data, unsigned DataLen) {
2122       using namespace llvm::support;
2123 
2124       endian::Writer LE(Out, llvm::endianness::little);
2125       uint64_t Start = Out.tell(); (void)Start;
2126 
2127       unsigned char Flags = (Data.AlreadyIncluded << 6)
2128                           | (Data.HFI.isImport << 5)
2129                           | (Writer.isWritingStdCXXNamedModules() ? 0 :
2130                              Data.HFI.isPragmaOnce << 4)
2131                           | (Data.HFI.DirInfo << 1);
2132       LE.write<uint8_t>(Flags);
2133 
2134       if (Data.HFI.LazyControllingMacro.isID())
2135         LE.write<IdentifierID>(Data.HFI.LazyControllingMacro.getID());
2136       else
2137         LE.write<IdentifierID>(
2138             Writer.getIdentifierRef(Data.HFI.LazyControllingMacro.getPtr()));
2139 
2140       auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2141         if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2142           uint32_t Value = (ModID << 3) | (unsigned)Role;
2143           assert((Value >> 3) == ModID && "overflow in header module info");
2144           LE.write<uint32_t>(Value);
2145         }
2146       };
2147 
2148       for (auto ModInfo : Data.KnownHeaders)
2149         EmitModule(ModInfo.getModule(), ModInfo.getRole());
2150       if (Data.Unresolved.getPointer())
2151         EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2152 
2153       assert(Out.tell() - Start == DataLen && "Wrong data length");
2154     }
2155   };
2156 
2157 } // namespace
2158 
2159 /// Write the header search block for the list of files that
2160 ///
2161 /// \param HS The header search structure to save.
2162 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2163   HeaderFileInfoTrait GeneratorTrait(*this);
2164   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2165   SmallVector<const char *, 4> SavedStrings;
2166   unsigned NumHeaderSearchEntries = 0;
2167 
2168   // Find all unresolved headers for the current module. We generally will
2169   // have resolved them before we get here, but not necessarily: we might be
2170   // compiling a preprocessed module, where there is no requirement for the
2171   // original files to exist any more.
2172   const HeaderFileInfo Empty; // So we can take a reference.
2173   if (WritingModule) {
2174     llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2175     while (!Worklist.empty()) {
2176       Module *M = Worklist.pop_back_val();
2177       // We don't care about headers in unimportable submodules.
2178       if (M->isUnimportable())
2179         continue;
2180 
2181       // Map to disk files where possible, to pick up any missing stat
2182       // information. This also means we don't need to check the unresolved
2183       // headers list when emitting resolved headers in the first loop below.
2184       // FIXME: It'd be preferable to avoid doing this if we were given
2185       // sufficient stat information in the module map.
2186       HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/std::nullopt);
2187 
2188       // If the file didn't exist, we can still create a module if we were given
2189       // enough information in the module map.
2190       for (const auto &U : M->MissingHeaders) {
2191         // Check that we were given enough information to build a module
2192         // without this file existing on disk.
2193         if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2194           PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2195               << WritingModule->getFullModuleName() << U.Size.has_value()
2196               << U.FileName;
2197           continue;
2198         }
2199 
2200         // Form the effective relative pathname for the file.
2201         SmallString<128> Filename(M->Directory->getName());
2202         llvm::sys::path::append(Filename, U.FileName);
2203         PreparePathForOutput(Filename);
2204 
2205         StringRef FilenameDup = strdup(Filename.c_str());
2206         SavedStrings.push_back(FilenameDup.data());
2207 
2208         HeaderFileInfoTrait::key_type Key = {
2209             FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0};
2210         HeaderFileInfoTrait::data_type Data = {
2211             Empty, false, {}, {M, ModuleMap::headerKindToRole(U.Kind)}};
2212         // FIXME: Deal with cases where there are multiple unresolved header
2213         // directives in different submodules for the same header.
2214         Generator.insert(Key, Data, GeneratorTrait);
2215         ++NumHeaderSearchEntries;
2216       }
2217       auto SubmodulesRange = M->submodules();
2218       Worklist.append(SubmodulesRange.begin(), SubmodulesRange.end());
2219     }
2220   }
2221 
2222   SmallVector<OptionalFileEntryRef, 16> FilesByUID;
2223   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2224 
2225   if (FilesByUID.size() > HS.header_file_size())
2226     FilesByUID.resize(HS.header_file_size());
2227 
2228   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2229     OptionalFileEntryRef File = FilesByUID[UID];
2230     if (!File)
2231       continue;
2232 
2233     const HeaderFileInfo *HFI = HS.getExistingLocalFileInfo(*File);
2234     if (!HFI)
2235       continue; // We have no information on this being a header file.
2236     if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
2237       continue; // Header file info is tracked by the owning module file.
2238     if (!HFI->isCompilingModuleHeader && !HFI->IsLocallyIncluded)
2239       continue; // Header file info is tracked by the including module file.
2240 
2241     // Massage the file path into an appropriate form.
2242     StringRef Filename = File->getName();
2243     SmallString<128> FilenameTmp(Filename);
2244     if (PreparePathForOutput(FilenameTmp)) {
2245       // If we performed any translation on the file name at all, we need to
2246       // save this string, since the generator will refer to it later.
2247       Filename = StringRef(strdup(FilenameTmp.c_str()));
2248       SavedStrings.push_back(Filename.data());
2249     }
2250 
2251     bool Included = HFI->IsLocallyIncluded || PP->alreadyIncluded(*File);
2252 
2253     HeaderFileInfoTrait::key_type Key = {
2254       Filename, File->getSize(), getTimestampForOutput(*File)
2255     };
2256     HeaderFileInfoTrait::data_type Data = {
2257       *HFI, Included, HS.getModuleMap().findResolvedModulesForHeader(*File), {}
2258     };
2259     Generator.insert(Key, Data, GeneratorTrait);
2260     ++NumHeaderSearchEntries;
2261   }
2262 
2263   // Create the on-disk hash table in a buffer.
2264   SmallString<4096> TableData;
2265   uint32_t BucketOffset;
2266   {
2267     using namespace llvm::support;
2268 
2269     llvm::raw_svector_ostream Out(TableData);
2270     // Make sure that no bucket is at offset 0
2271     endian::write<uint32_t>(Out, 0, llvm::endianness::little);
2272     BucketOffset = Generator.Emit(Out, GeneratorTrait);
2273   }
2274 
2275   // Create a blob abbreviation
2276   using namespace llvm;
2277 
2278   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2279   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2280   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2281   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2282   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2283   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2284   unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2285 
2286   // Write the header search table
2287   RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2288                                      NumHeaderSearchEntries, TableData.size()};
2289   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2290 
2291   // Free all of the strings we had to duplicate.
2292   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2293     free(const_cast<char *>(SavedStrings[I]));
2294 }
2295 
2296 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2297                      unsigned SLocBufferBlobCompressedAbbrv,
2298                      unsigned SLocBufferBlobAbbrv) {
2299   using RecordDataType = ASTWriter::RecordData::value_type;
2300 
2301   // Compress the buffer if possible. We expect that almost all PCM
2302   // consumers will not want its contents.
2303   SmallVector<uint8_t, 0> CompressedBuffer;
2304   if (llvm::compression::zstd::isAvailable()) {
2305     llvm::compression::zstd::compress(
2306         llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer, 9);
2307     RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2308     Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2309                               llvm::toStringRef(CompressedBuffer));
2310     return;
2311   }
2312   if (llvm::compression::zlib::isAvailable()) {
2313     llvm::compression::zlib::compress(
2314         llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2315     RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2316     Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2317                               llvm::toStringRef(CompressedBuffer));
2318     return;
2319   }
2320 
2321   RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2322   Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2323 }
2324 
2325 /// Writes the block containing the serialized form of the
2326 /// source manager.
2327 ///
2328 /// TODO: We should probably use an on-disk hash table (stored in a
2329 /// blob), indexed based on the file name, so that we only create
2330 /// entries for files that we actually need. In the common case (no
2331 /// errors), we probably won't have to create file entries for any of
2332 /// the files in the AST.
2333 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
2334   RecordData Record;
2335 
2336   // Enter the source manager block.
2337   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2338   const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2339 
2340   // Abbreviations for the various kinds of source-location entries.
2341   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2342   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2343   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2344   unsigned SLocBufferBlobCompressedAbbrv =
2345       CreateSLocBufferBlobAbbrev(Stream, true);
2346   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2347 
2348   // Write out the source location entry table. We skip the first
2349   // entry, which is always the same dummy entry.
2350   std::vector<uint32_t> SLocEntryOffsets;
2351   uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2352   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2353   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2354        I != N; ++I) {
2355     // Get this source location entry.
2356     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2357     FileID FID = FileID::get(I);
2358     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2359 
2360     // Record the offset of this source-location entry.
2361     uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2362     assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2363 
2364     // Figure out which record code to use.
2365     unsigned Code;
2366     if (SLoc->isFile()) {
2367       const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2368       if (Cache->OrigEntry) {
2369         Code = SM_SLOC_FILE_ENTRY;
2370       } else
2371         Code = SM_SLOC_BUFFER_ENTRY;
2372     } else
2373       Code = SM_SLOC_EXPANSION_ENTRY;
2374     Record.clear();
2375     Record.push_back(Code);
2376 
2377     if (SLoc->isFile()) {
2378       const SrcMgr::FileInfo &File = SLoc->getFile();
2379       const SrcMgr::ContentCache *Content = &File.getContentCache();
2380       // Do not emit files that were not listed as inputs.
2381       if (!IsSLocAffecting[I])
2382         continue;
2383       SLocEntryOffsets.push_back(Offset);
2384       // Starting offset of this entry within this module, so skip the dummy.
2385       Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2386       AddSourceLocation(getAffectingIncludeLoc(SourceMgr, File), Record);
2387       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2388       Record.push_back(File.hasLineDirectives());
2389 
2390       bool EmitBlob = false;
2391       if (Content->OrigEntry) {
2392         assert(Content->OrigEntry == Content->ContentsEntry &&
2393                "Writing to AST an overridden file is not supported");
2394 
2395         // The source location entry is a file. Emit input file ID.
2396         assert(InputFileIDs[*Content->OrigEntry] != 0 && "Missed file entry");
2397         Record.push_back(InputFileIDs[*Content->OrigEntry]);
2398 
2399         Record.push_back(getAdjustedNumCreatedFIDs(FID));
2400 
2401         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2402         if (FDI != FileDeclIDs.end()) {
2403           Record.push_back(FDI->second->FirstDeclIndex);
2404           Record.push_back(FDI->second->DeclIDs.size());
2405         } else {
2406           Record.push_back(0);
2407           Record.push_back(0);
2408         }
2409 
2410         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2411 
2412         if (Content->BufferOverridden || Content->IsTransient)
2413           EmitBlob = true;
2414       } else {
2415         // The source location entry is a buffer. The blob associated
2416         // with this entry contains the contents of the buffer.
2417 
2418         // We add one to the size so that we capture the trailing NULL
2419         // that is required by llvm::MemoryBuffer::getMemBuffer (on
2420         // the reader side).
2421         std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2422             SourceMgr.getDiagnostics(), SourceMgr.getFileManager());
2423         StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2424         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2425                                   StringRef(Name.data(), Name.size() + 1));
2426         EmitBlob = true;
2427       }
2428 
2429       if (EmitBlob) {
2430         // Include the implicit terminating null character in the on-disk buffer
2431         // if we're writing it uncompressed.
2432         std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2433             SourceMgr.getDiagnostics(), SourceMgr.getFileManager());
2434         if (!Buffer)
2435           Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2436         StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2437         emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2438                  SLocBufferBlobAbbrv);
2439       }
2440     } else {
2441       // The source location entry is a macro expansion.
2442       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2443       SLocEntryOffsets.push_back(Offset);
2444       // Starting offset of this entry within this module, so skip the dummy.
2445       Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2446       AddSourceLocation(Expansion.getSpellingLoc(), Record);
2447       AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2448       AddSourceLocation(Expansion.isMacroArgExpansion()
2449                             ? SourceLocation()
2450                             : Expansion.getExpansionLocEnd(),
2451                         Record);
2452       Record.push_back(Expansion.isExpansionTokenRange());
2453 
2454       // Compute the token length for this macro expansion.
2455       SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2456       if (I + 1 != N)
2457         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2458       Record.push_back(getAdjustedOffset(NextOffset - SLoc->getOffset()) - 1);
2459       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2460     }
2461   }
2462 
2463   Stream.ExitBlock();
2464 
2465   if (SLocEntryOffsets.empty())
2466     return;
2467 
2468   // Write the source-location offsets table into the AST block. This
2469   // table is used for lazily loading source-location information.
2470   using namespace llvm;
2471 
2472   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2473   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2474   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2475   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2476   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2477   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2478   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2479   {
2480     RecordData::value_type Record[] = {
2481         SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2482         getAdjustedOffset(SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2483         SLocEntryOffsetsBase - SourceManagerBlockOffset};
2484     Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2485                               bytes(SLocEntryOffsets));
2486   }
2487 
2488   // Write the line table. It depends on remapping working, so it must come
2489   // after the source location offsets.
2490   if (SourceMgr.hasLineTable()) {
2491     LineTableInfo &LineTable = SourceMgr.getLineTable();
2492 
2493     Record.clear();
2494 
2495     // Emit the needed file names.
2496     llvm::DenseMap<int, int> FilenameMap;
2497     FilenameMap[-1] = -1; // For unspecified filenames.
2498     for (const auto &L : LineTable) {
2499       if (L.first.ID < 0)
2500         continue;
2501       for (auto &LE : L.second) {
2502         if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2503                                               FilenameMap.size() - 1)).second)
2504           AddPath(LineTable.getFilename(LE.FilenameID), Record);
2505       }
2506     }
2507     Record.push_back(0);
2508 
2509     // Emit the line entries
2510     for (const auto &L : LineTable) {
2511       // Only emit entries for local files.
2512       if (L.first.ID < 0)
2513         continue;
2514 
2515       AddFileID(L.first, Record);
2516 
2517       // Emit the line entries
2518       Record.push_back(L.second.size());
2519       for (const auto &LE : L.second) {
2520         Record.push_back(LE.FileOffset);
2521         Record.push_back(LE.LineNo);
2522         Record.push_back(FilenameMap[LE.FilenameID]);
2523         Record.push_back((unsigned)LE.FileKind);
2524         Record.push_back(LE.IncludeOffset);
2525       }
2526     }
2527 
2528     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2529   }
2530 }
2531 
2532 //===----------------------------------------------------------------------===//
2533 // Preprocessor Serialization
2534 //===----------------------------------------------------------------------===//
2535 
2536 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2537                               const Preprocessor &PP) {
2538   if (MacroInfo *MI = MD->getMacroInfo())
2539     if (MI->isBuiltinMacro())
2540       return true;
2541 
2542   if (IsModule) {
2543     SourceLocation Loc = MD->getLocation();
2544     if (Loc.isInvalid())
2545       return true;
2546     if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2547       return true;
2548   }
2549 
2550   return false;
2551 }
2552 
2553 /// Writes the block containing the serialized form of the
2554 /// preprocessor.
2555 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2556   uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2557 
2558   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2559   if (PPRec)
2560     WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2561 
2562   RecordData Record;
2563   RecordData ModuleMacroRecord;
2564 
2565   // If the preprocessor __COUNTER__ value has been bumped, remember it.
2566   if (PP.getCounterValue() != 0) {
2567     RecordData::value_type Record[] = {PP.getCounterValue()};
2568     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2569   }
2570 
2571   // If we have a recorded #pragma assume_nonnull, remember it so it can be
2572   // replayed when the preamble terminates into the main file.
2573   SourceLocation AssumeNonNullLoc =
2574       PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2575   if (AssumeNonNullLoc.isValid()) {
2576     assert(PP.isRecordingPreamble());
2577     AddSourceLocation(AssumeNonNullLoc, Record);
2578     Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2579     Record.clear();
2580   }
2581 
2582   if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2583     assert(!IsModule);
2584     auto SkipInfo = PP.getPreambleSkipInfo();
2585     if (SkipInfo) {
2586       Record.push_back(true);
2587       AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2588       AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2589       Record.push_back(SkipInfo->FoundNonSkipPortion);
2590       Record.push_back(SkipInfo->FoundElse);
2591       AddSourceLocation(SkipInfo->ElseLoc, Record);
2592     } else {
2593       Record.push_back(false);
2594     }
2595     for (const auto &Cond : PP.getPreambleConditionalStack()) {
2596       AddSourceLocation(Cond.IfLoc, Record);
2597       Record.push_back(Cond.WasSkipping);
2598       Record.push_back(Cond.FoundNonSkip);
2599       Record.push_back(Cond.FoundElse);
2600     }
2601     Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2602     Record.clear();
2603   }
2604 
2605   // Write the safe buffer opt-out region map in PP
2606   for (SourceLocation &S : PP.serializeSafeBufferOptOutMap())
2607     AddSourceLocation(S, Record);
2608   Stream.EmitRecord(PP_UNSAFE_BUFFER_USAGE, Record);
2609   Record.clear();
2610 
2611   // Enter the preprocessor block.
2612   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2613 
2614   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2615   // FIXME: Include a location for the use, and say which one was used.
2616   if (PP.SawDateOrTime())
2617     PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2618 
2619   // Loop over all the macro directives that are live at the end of the file,
2620   // emitting each to the PP section.
2621 
2622   // Construct the list of identifiers with macro directives that need to be
2623   // serialized.
2624   SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2625   // It is meaningless to emit macros for named modules. It only wastes times
2626   // and spaces.
2627   if (!isWritingStdCXXNamedModules())
2628     for (auto &Id : PP.getIdentifierTable())
2629       if (Id.second->hadMacroDefinition() &&
2630           (!Id.second->isFromAST() ||
2631           Id.second->hasChangedSinceDeserialization()))
2632         MacroIdentifiers.push_back(Id.second);
2633   // Sort the set of macro definitions that need to be serialized by the
2634   // name of the macro, to provide a stable ordering.
2635   llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2636 
2637   // Emit the macro directives as a list and associate the offset with the
2638   // identifier they belong to.
2639   for (const IdentifierInfo *Name : MacroIdentifiers) {
2640     MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2641     uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2642     assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2643 
2644     // Write out any exported module macros.
2645     bool EmittedModuleMacros = false;
2646     // C+=20 Header Units are compiled module interfaces, but they preserve
2647     // macros that are live (i.e. have a defined value) at the end of the
2648     // compilation.  So when writing a header unit, we preserve only the final
2649     // value of each macro (and discard any that are undefined).  Header units
2650     // do not have sub-modules (although they might import other header units).
2651     // PCH files, conversely, retain the history of each macro's define/undef
2652     // and of leaf macros in sub modules.
2653     if (IsModule && WritingModule->isHeaderUnit()) {
2654       // This is for the main TU when it is a C++20 header unit.
2655       // We preserve the final state of defined macros, and we do not emit ones
2656       // that are undefined.
2657       if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2658           MD->getKind() == MacroDirective::MD_Undefine)
2659         continue;
2660       AddSourceLocation(MD->getLocation(), Record);
2661       Record.push_back(MD->getKind());
2662       if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2663         Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2664       } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2665         Record.push_back(VisMD->isPublic());
2666       }
2667       ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2668       ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2669       Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2670       ModuleMacroRecord.clear();
2671       EmittedModuleMacros = true;
2672     } else {
2673       // Emit the macro directives in reverse source order.
2674       for (; MD; MD = MD->getPrevious()) {
2675         // Once we hit an ignored macro, we're done: the rest of the chain
2676         // will all be ignored macros.
2677         if (shouldIgnoreMacro(MD, IsModule, PP))
2678           break;
2679         AddSourceLocation(MD->getLocation(), Record);
2680         Record.push_back(MD->getKind());
2681         if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2682           Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2683         } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2684           Record.push_back(VisMD->isPublic());
2685         }
2686       }
2687 
2688       // We write out exported module macros for PCH as well.
2689       auto Leafs = PP.getLeafModuleMacros(Name);
2690       SmallVector<ModuleMacro *, 8> Worklist(Leafs);
2691       llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2692       while (!Worklist.empty()) {
2693         auto *Macro = Worklist.pop_back_val();
2694 
2695         // Emit a record indicating this submodule exports this macro.
2696         ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2697         ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2698         for (auto *M : Macro->overrides())
2699           ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2700 
2701         Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2702         ModuleMacroRecord.clear();
2703 
2704         // Enqueue overridden macros once we've visited all their ancestors.
2705         for (auto *M : Macro->overrides())
2706           if (++Visits[M] == M->getNumOverridingMacros())
2707             Worklist.push_back(M);
2708 
2709         EmittedModuleMacros = true;
2710       }
2711     }
2712     if (Record.empty() && !EmittedModuleMacros)
2713       continue;
2714 
2715     IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2716     Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2717     Record.clear();
2718   }
2719 
2720   /// Offsets of each of the macros into the bitstream, indexed by
2721   /// the local macro ID
2722   ///
2723   /// For each identifier that is associated with a macro, this map
2724   /// provides the offset into the bitstream where that macro is
2725   /// defined.
2726   std::vector<uint32_t> MacroOffsets;
2727 
2728   for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2729     const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2730     MacroInfo *MI = MacroInfosToEmit[I].MI;
2731     MacroID ID = MacroInfosToEmit[I].ID;
2732 
2733     if (ID < FirstMacroID) {
2734       assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2735       continue;
2736     }
2737 
2738     // Record the local offset of this macro.
2739     unsigned Index = ID - FirstMacroID;
2740     if (Index >= MacroOffsets.size())
2741       MacroOffsets.resize(Index + 1);
2742 
2743     uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2744     assert((Offset >> 32) == 0 && "Macro offset too large");
2745     MacroOffsets[Index] = Offset;
2746 
2747     AddIdentifierRef(Name, Record);
2748     AddSourceLocation(MI->getDefinitionLoc(), Record);
2749     AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2750     Record.push_back(MI->isUsed());
2751     Record.push_back(MI->isUsedForHeaderGuard());
2752     Record.push_back(MI->getNumTokens());
2753     unsigned Code;
2754     if (MI->isObjectLike()) {
2755       Code = PP_MACRO_OBJECT_LIKE;
2756     } else {
2757       Code = PP_MACRO_FUNCTION_LIKE;
2758 
2759       Record.push_back(MI->isC99Varargs());
2760       Record.push_back(MI->isGNUVarargs());
2761       Record.push_back(MI->hasCommaPasting());
2762       Record.push_back(MI->getNumParams());
2763       for (const IdentifierInfo *Param : MI->params())
2764         AddIdentifierRef(Param, Record);
2765     }
2766 
2767     // If we have a detailed preprocessing record, record the macro definition
2768     // ID that corresponds to this macro.
2769     if (PPRec)
2770       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2771 
2772     Stream.EmitRecord(Code, Record);
2773     Record.clear();
2774 
2775     // Emit the tokens array.
2776     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2777       // Note that we know that the preprocessor does not have any annotation
2778       // tokens in it because they are created by the parser, and thus can't
2779       // be in a macro definition.
2780       const Token &Tok = MI->getReplacementToken(TokNo);
2781       AddToken(Tok, Record);
2782       Stream.EmitRecord(PP_TOKEN, Record);
2783       Record.clear();
2784     }
2785     ++NumMacros;
2786   }
2787 
2788   Stream.ExitBlock();
2789 
2790   // Write the offsets table for macro IDs.
2791   using namespace llvm;
2792 
2793   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2794   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2795   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2796   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2797   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32));   // base offset
2798   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2799 
2800   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2801   {
2802     RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2803                                        FirstMacroID - NUM_PREDEF_MACRO_IDS,
2804                                        MacroOffsetsBase - ASTBlockStartOffset};
2805     Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2806   }
2807 }
2808 
2809 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2810                                         uint64_t MacroOffsetsBase) {
2811   if (PPRec.local_begin() == PPRec.local_end())
2812     return;
2813 
2814   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2815 
2816   // Enter the preprocessor block.
2817   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2818 
2819   // If the preprocessor has a preprocessing record, emit it.
2820   unsigned NumPreprocessingRecords = 0;
2821   using namespace llvm;
2822 
2823   // Set up the abbreviation for
2824   unsigned InclusionAbbrev = 0;
2825   {
2826     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2827     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2828     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2829     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2830     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2831     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2832     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2833     InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2834   }
2835 
2836   unsigned FirstPreprocessorEntityID
2837     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2838     + NUM_PREDEF_PP_ENTITY_IDS;
2839   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2840   RecordData Record;
2841   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2842                                   EEnd = PPRec.local_end();
2843        E != EEnd;
2844        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2845     Record.clear();
2846 
2847     uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2848     assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2849     SourceRange R = getAdjustedRange((*E)->getSourceRange());
2850     PreprocessedEntityOffsets.emplace_back(
2851         getRawSourceLocationEncoding(R.getBegin()),
2852         getRawSourceLocationEncoding(R.getEnd()), Offset);
2853 
2854     if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2855       // Record this macro definition's ID.
2856       MacroDefinitions[MD] = NextPreprocessorEntityID;
2857 
2858       AddIdentifierRef(MD->getName(), Record);
2859       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2860       continue;
2861     }
2862 
2863     if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2864       Record.push_back(ME->isBuiltinMacro());
2865       if (ME->isBuiltinMacro())
2866         AddIdentifierRef(ME->getName(), Record);
2867       else
2868         Record.push_back(MacroDefinitions[ME->getDefinition()]);
2869       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2870       continue;
2871     }
2872 
2873     if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2874       Record.push_back(PPD_INCLUSION_DIRECTIVE);
2875       Record.push_back(ID->getFileName().size());
2876       Record.push_back(ID->wasInQuotes());
2877       Record.push_back(static_cast<unsigned>(ID->getKind()));
2878       Record.push_back(ID->importedModule());
2879       SmallString<64> Buffer;
2880       Buffer += ID->getFileName();
2881       // Check that the FileEntry is not null because it was not resolved and
2882       // we create a PCH even with compiler errors.
2883       if (ID->getFile())
2884         Buffer += ID->getFile()->getName();
2885       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2886       continue;
2887     }
2888 
2889     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2890   }
2891   Stream.ExitBlock();
2892 
2893   // Write the offsets table for the preprocessing record.
2894   if (NumPreprocessingRecords > 0) {
2895     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2896 
2897     // Write the offsets table for identifier IDs.
2898     using namespace llvm;
2899 
2900     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2901     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2902     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2903     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2904     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2905 
2906     RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2907                                        FirstPreprocessorEntityID -
2908                                            NUM_PREDEF_PP_ENTITY_IDS};
2909     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2910                               bytes(PreprocessedEntityOffsets));
2911   }
2912 
2913   // Write the skipped region table for the preprocessing record.
2914   ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2915   if (SkippedRanges.size() > 0) {
2916     std::vector<PPSkippedRange> SerializedSkippedRanges;
2917     SerializedSkippedRanges.reserve(SkippedRanges.size());
2918     for (auto const& Range : SkippedRanges)
2919       SerializedSkippedRanges.emplace_back(
2920           getRawSourceLocationEncoding(Range.getBegin()),
2921           getRawSourceLocationEncoding(Range.getEnd()));
2922 
2923     using namespace llvm;
2924     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2925     Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2926     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2927     unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2928 
2929     Record.clear();
2930     Record.push_back(PPD_SKIPPED_RANGES);
2931     Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2932                               bytes(SerializedSkippedRanges));
2933   }
2934 }
2935 
2936 unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2937   if (!Mod)
2938     return 0;
2939 
2940   auto Known = SubmoduleIDs.find(Mod);
2941   if (Known != SubmoduleIDs.end())
2942     return Known->second;
2943 
2944   auto *Top = Mod->getTopLevelModule();
2945   if (Top != WritingModule &&
2946       (getLangOpts().CompilingPCH ||
2947        !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2948     return 0;
2949 
2950   return SubmoduleIDs[Mod] = NextSubmoduleID++;
2951 }
2952 
2953 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2954   unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2955   // FIXME: This can easily happen, if we have a reference to a submodule that
2956   // did not result in us loading a module file for that submodule. For
2957   // instance, a cross-top-level-module 'conflict' declaration will hit this.
2958   // assert((ID || !Mod) &&
2959   //        "asked for module ID for non-local, non-imported module");
2960   return ID;
2961 }
2962 
2963 /// Compute the number of modules within the given tree (including the
2964 /// given module).
2965 static unsigned getNumberOfModules(Module *Mod) {
2966   unsigned ChildModules = 0;
2967   for (auto *Submodule : Mod->submodules())
2968     ChildModules += getNumberOfModules(Submodule);
2969 
2970   return ChildModules + 1;
2971 }
2972 
2973 void ASTWriter::WriteSubmodules(Module *WritingModule, ASTContext *Context) {
2974   // Enter the submodule description block.
2975   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2976 
2977   // Write the abbreviations needed for the submodules block.
2978   using namespace llvm;
2979 
2980   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2981   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2982   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2983   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2984   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
2985   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Definition location
2986   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Inferred allowed by
2987   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2988   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2989   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2990   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2991   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2992   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2993   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2994   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2995   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2996   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NamedModuleHasN...
2997   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2998   unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2999 
3000   Abbrev = std::make_shared<BitCodeAbbrev>();
3001   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
3002   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3003   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3004 
3005   Abbrev = std::make_shared<BitCodeAbbrev>();
3006   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
3007   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3008   unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3009 
3010   Abbrev = std::make_shared<BitCodeAbbrev>();
3011   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
3012   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3013   unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3014 
3015   Abbrev = std::make_shared<BitCodeAbbrev>();
3016   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
3017   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3018   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3019 
3020   Abbrev = std::make_shared<BitCodeAbbrev>();
3021   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
3022   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
3023   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
3024   unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3025 
3026   Abbrev = std::make_shared<BitCodeAbbrev>();
3027   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
3028   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3029   unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3030 
3031   Abbrev = std::make_shared<BitCodeAbbrev>();
3032   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
3033   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3034   unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3035 
3036   Abbrev = std::make_shared<BitCodeAbbrev>();
3037   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
3038   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3039   unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3040 
3041   Abbrev = std::make_shared<BitCodeAbbrev>();
3042   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
3043   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3044   unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3045 
3046   Abbrev = std::make_shared<BitCodeAbbrev>();
3047   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
3048   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
3049   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
3050   unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3051 
3052   Abbrev = std::make_shared<BitCodeAbbrev>();
3053   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
3054   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
3055   unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3056 
3057   Abbrev = std::make_shared<BitCodeAbbrev>();
3058   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
3059   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
3060   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
3061   unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3062 
3063   Abbrev = std::make_shared<BitCodeAbbrev>();
3064   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
3065   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
3066   unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3067 
3068   // Write the submodule metadata block.
3069   RecordData::value_type Record[] = {
3070       getNumberOfModules(WritingModule),
3071       FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
3072   Stream.EmitRecord(SUBMODULE_METADATA, Record);
3073 
3074   // Write all of the submodules.
3075   std::queue<Module *> Q;
3076   Q.push(WritingModule);
3077   while (!Q.empty()) {
3078     Module *Mod = Q.front();
3079     Q.pop();
3080     unsigned ID = getSubmoduleID(Mod);
3081 
3082     uint64_t ParentID = 0;
3083     if (Mod->Parent) {
3084       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
3085       ParentID = SubmoduleIDs[Mod->Parent];
3086     }
3087 
3088     SourceLocationEncoding::RawLocEncoding DefinitionLoc =
3089         getRawSourceLocationEncoding(getAdjustedLocation(Mod->DefinitionLoc));
3090 
3091     ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
3092     FileID UnadjustedInferredFID;
3093     if (Mod->IsInferred)
3094       UnadjustedInferredFID = ModMap.getModuleMapFileIDForUniquing(Mod);
3095     int InferredFID = getAdjustedFileID(UnadjustedInferredFID).getOpaqueValue();
3096 
3097     // Emit the definition of the block.
3098     {
3099       RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
3100                                          ID,
3101                                          ParentID,
3102                                          (RecordData::value_type)Mod->Kind,
3103                                          DefinitionLoc,
3104                                          (RecordData::value_type)InferredFID,
3105                                          Mod->IsFramework,
3106                                          Mod->IsExplicit,
3107                                          Mod->IsSystem,
3108                                          Mod->IsExternC,
3109                                          Mod->InferSubmodules,
3110                                          Mod->InferExplicitSubmodules,
3111                                          Mod->InferExportWildcard,
3112                                          Mod->ConfigMacrosExhaustive,
3113                                          Mod->ModuleMapIsPrivate,
3114                                          Mod->NamedModuleHasInit};
3115       Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
3116     }
3117 
3118     // Emit the requirements.
3119     for (const auto &R : Mod->Requirements) {
3120       RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.RequiredState};
3121       Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.FeatureName);
3122     }
3123 
3124     // Emit the umbrella header, if there is one.
3125     if (std::optional<Module::Header> UmbrellaHeader =
3126             Mod->getUmbrellaHeaderAsWritten()) {
3127       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
3128       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
3129                                 UmbrellaHeader->NameAsWritten);
3130     } else if (std::optional<Module::DirectoryName> UmbrellaDir =
3131                    Mod->getUmbrellaDirAsWritten()) {
3132       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
3133       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
3134                                 UmbrellaDir->NameAsWritten);
3135     }
3136 
3137     // Emit the headers.
3138     struct {
3139       unsigned RecordKind;
3140       unsigned Abbrev;
3141       Module::HeaderKind HeaderKind;
3142     } HeaderLists[] = {
3143       {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
3144       {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
3145       {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
3146       {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
3147         Module::HK_PrivateTextual},
3148       {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
3149     };
3150     for (const auto &HL : HeaderLists) {
3151       RecordData::value_type Record[] = {HL.RecordKind};
3152       for (const auto &H : Mod->getHeaders(HL.HeaderKind))
3153         Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
3154     }
3155 
3156     // Emit the top headers.
3157     {
3158       RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
3159       for (FileEntryRef H : Mod->getTopHeaders(PP->getFileManager())) {
3160         SmallString<128> HeaderName(H.getName());
3161         PreparePathForOutput(HeaderName);
3162         Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
3163       }
3164     }
3165 
3166     // Emit the imports.
3167     if (!Mod->Imports.empty()) {
3168       RecordData Record;
3169       for (auto *I : Mod->Imports)
3170         Record.push_back(getSubmoduleID(I));
3171       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
3172     }
3173 
3174     // Emit the modules affecting compilation that were not imported.
3175     if (!Mod->AffectingClangModules.empty()) {
3176       RecordData Record;
3177       for (auto *I : Mod->AffectingClangModules)
3178         Record.push_back(getSubmoduleID(I));
3179       Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
3180     }
3181 
3182     // Emit the exports.
3183     if (!Mod->Exports.empty()) {
3184       RecordData Record;
3185       for (const auto &E : Mod->Exports) {
3186         // FIXME: This may fail; we don't require that all exported modules
3187         // are local or imported.
3188         Record.push_back(getSubmoduleID(E.getPointer()));
3189         Record.push_back(E.getInt());
3190       }
3191       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3192     }
3193 
3194     //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
3195     // Might be unnecessary as use declarations are only used to build the
3196     // module itself.
3197 
3198     // TODO: Consider serializing undeclared uses of modules.
3199 
3200     // Emit the link libraries.
3201     for (const auto &LL : Mod->LinkLibraries) {
3202       RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3203                                          LL.IsFramework};
3204       Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3205     }
3206 
3207     // Emit the conflicts.
3208     for (const auto &C : Mod->Conflicts) {
3209       // FIXME: This may fail; we don't require that all conflicting modules
3210       // are local or imported.
3211       RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3212                                          getSubmoduleID(C.Other)};
3213       Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3214     }
3215 
3216     // Emit the configuration macros.
3217     for (const auto &CM : Mod->ConfigMacros) {
3218       RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3219       Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3220     }
3221 
3222     // Emit the reachable initializers.
3223     // The initializer may only be unreachable in reduced BMI.
3224     if (Context) {
3225       RecordData Inits;
3226       for (Decl *D : Context->getModuleInitializers(Mod))
3227         if (wasDeclEmitted(D))
3228           AddDeclRef(D, Inits);
3229       if (!Inits.empty())
3230         Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3231     }
3232 
3233     // Emit the name of the re-exported module, if any.
3234     if (!Mod->ExportAsModule.empty()) {
3235       RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3236       Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3237     }
3238 
3239     // Queue up the submodules of this module.
3240     for (auto *M : Mod->submodules())
3241       Q.push(M);
3242   }
3243 
3244   Stream.ExitBlock();
3245 
3246   assert((NextSubmoduleID - FirstSubmoduleID ==
3247           getNumberOfModules(WritingModule)) &&
3248          "Wrong # of submodules; found a reference to a non-local, "
3249          "non-imported submodule?");
3250 }
3251 
3252 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3253                                               bool isModule) {
3254   llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3255       DiagStateIDMap;
3256   unsigned CurrID = 0;
3257   RecordData Record;
3258 
3259   auto EncodeDiagStateFlags =
3260       [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3261     unsigned Result = (unsigned)DS->ExtBehavior;
3262     for (unsigned Val :
3263          {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3264           (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3265           (unsigned)DS->SuppressSystemWarnings})
3266       Result = (Result << 1) | Val;
3267     return Result;
3268   };
3269 
3270   unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3271   Record.push_back(Flags);
3272 
3273   auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3274                           bool IncludeNonPragmaStates) {
3275     // Ensure that the diagnostic state wasn't modified since it was created.
3276     // We will not correctly round-trip this information otherwise.
3277     assert(Flags == EncodeDiagStateFlags(State) &&
3278            "diag state flags vary in single AST file");
3279 
3280     // If we ever serialize non-pragma mappings outside the initial state, the
3281     // code below will need to consider more than getDefaultMapping.
3282     assert(!IncludeNonPragmaStates ||
3283            State == Diag.DiagStatesByLoc.FirstDiagState);
3284 
3285     unsigned &DiagStateID = DiagStateIDMap[State];
3286     Record.push_back(DiagStateID);
3287 
3288     if (DiagStateID == 0) {
3289       DiagStateID = ++CurrID;
3290       SmallVector<std::pair<unsigned, DiagnosticMapping>> Mappings;
3291 
3292       // Add a placeholder for the number of mappings.
3293       auto SizeIdx = Record.size();
3294       Record.emplace_back();
3295       for (const auto &I : *State) {
3296         // Maybe skip non-pragmas.
3297         if (!I.second.isPragma() && !IncludeNonPragmaStates)
3298           continue;
3299         // Skip default mappings. We have a mapping for every diagnostic ever
3300         // emitted, regardless of whether it was customized.
3301         if (!I.second.isPragma() &&
3302             I.second == Diag.getDiagnosticIDs()->getDefaultMapping(I.first))
3303           continue;
3304         Mappings.push_back(I);
3305       }
3306 
3307       // Sort by diag::kind for deterministic output.
3308       llvm::sort(Mappings, llvm::less_first());
3309 
3310       for (const auto &I : Mappings) {
3311         Record.push_back(I.first);
3312         Record.push_back(I.second.serialize());
3313       }
3314       // Update the placeholder.
3315       Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3316     }
3317   };
3318 
3319   AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3320 
3321   // Reserve a spot for the number of locations with state transitions.
3322   auto NumLocationsIdx = Record.size();
3323   Record.emplace_back();
3324 
3325   // Emit the state transitions.
3326   unsigned NumLocations = 0;
3327   for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3328     if (!FileIDAndFile.first.isValid() ||
3329         !FileIDAndFile.second.HasLocalTransitions)
3330       continue;
3331     ++NumLocations;
3332 
3333     AddFileID(FileIDAndFile.first, Record);
3334 
3335     Record.push_back(FileIDAndFile.second.StateTransitions.size());
3336     for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3337       Record.push_back(getAdjustedOffset(StatePoint.Offset));
3338       AddDiagState(StatePoint.State, false);
3339     }
3340   }
3341 
3342   // Backpatch the number of locations.
3343   Record[NumLocationsIdx] = NumLocations;
3344 
3345   // Emit CurDiagStateLoc.  Do it last in order to match source order.
3346   //
3347   // This also protects against a hypothetical corner case with simulating
3348   // -Werror settings for implicit modules in the ASTReader, where reading
3349   // CurDiagState out of context could change whether warning pragmas are
3350   // treated as errors.
3351   AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3352   AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3353 
3354   Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3355 }
3356 
3357 //===----------------------------------------------------------------------===//
3358 // Type Serialization
3359 //===----------------------------------------------------------------------===//
3360 
3361 /// Write the representation of a type to the AST stream.
3362 void ASTWriter::WriteType(ASTContext &Context, QualType T) {
3363   TypeIdx &IdxRef = TypeIdxs[T];
3364   if (IdxRef.getValue() == 0) // we haven't seen this type before.
3365     IdxRef = TypeIdx(0, NextTypeID++);
3366   TypeIdx Idx = IdxRef;
3367 
3368   assert(Idx.getModuleFileIndex() == 0 && "Re-writing a type from a prior AST");
3369   assert(Idx.getValue() >= FirstTypeID && "Writing predefined type");
3370 
3371   // Emit the type's representation.
3372   uint64_t Offset =
3373       ASTTypeWriter(Context, *this).write(T) - DeclTypesBlockStartOffset;
3374 
3375   // Record the offset for this type.
3376   uint64_t Index = Idx.getValue() - FirstTypeID;
3377   if (TypeOffsets.size() == Index)
3378     TypeOffsets.emplace_back(Offset);
3379   else if (TypeOffsets.size() < Index) {
3380     TypeOffsets.resize(Index + 1);
3381     TypeOffsets[Index].set(Offset);
3382   } else {
3383     llvm_unreachable("Types emitted in wrong order");
3384   }
3385 }
3386 
3387 //===----------------------------------------------------------------------===//
3388 // Declaration Serialization
3389 //===----------------------------------------------------------------------===//
3390 
3391 static bool IsInternalDeclFromFileContext(const Decl *D) {
3392   auto *ND = dyn_cast<NamedDecl>(D);
3393   if (!ND)
3394     return false;
3395 
3396   if (!D->getDeclContext()->getRedeclContext()->isFileContext())
3397     return false;
3398 
3399   return ND->getFormalLinkage() == Linkage::Internal;
3400 }
3401 
3402 /// Write the block containing all of the declaration IDs
3403 /// lexically declared within the given DeclContext.
3404 ///
3405 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3406 /// bitstream, or 0 if no block was written.
3407 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3408                                                  const DeclContext *DC) {
3409   if (DC->decls_empty())
3410     return 0;
3411 
3412   // In reduced BMI, we don't care the declarations in functions.
3413   if (GeneratingReducedBMI && DC->isFunctionOrMethod())
3414     return 0;
3415 
3416   uint64_t Offset = Stream.GetCurrentBitNo();
3417   SmallVector<DeclID, 128> KindDeclPairs;
3418   for (const auto *D : DC->decls()) {
3419     if (DoneWritingDeclsAndTypes && !wasDeclEmitted(D))
3420       continue;
3421 
3422     // We don't need to write decls with internal linkage into reduced BMI.
3423     // If such decls gets emitted due to it get used from inline functions,
3424     // the program illegal. However, there are too many use of static inline
3425     // functions in the global module fragment and it will be breaking change
3426     // to forbid that. So we have to allow to emit such declarations from GMF.
3427     if (GeneratingReducedBMI && !D->isFromExplicitGlobalModule() &&
3428         IsInternalDeclFromFileContext(D))
3429       continue;
3430 
3431     KindDeclPairs.push_back(D->getKind());
3432     KindDeclPairs.push_back(GetDeclRef(D).getRawValue());
3433   }
3434 
3435   ++NumLexicalDeclContexts;
3436   RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3437   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3438                             bytes(KindDeclPairs));
3439   return Offset;
3440 }
3441 
3442 void ASTWriter::WriteTypeDeclOffsets() {
3443   using namespace llvm;
3444 
3445   // Write the type offsets array
3446   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3447   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3448   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3449   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3450   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3451   {
3452     RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size()};
3453     Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3454   }
3455 
3456   // Write the declaration offsets array
3457   Abbrev = std::make_shared<BitCodeAbbrev>();
3458   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3459   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3460   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3461   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3462   {
3463     RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size()};
3464     Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3465   }
3466 }
3467 
3468 void ASTWriter::WriteFileDeclIDsMap() {
3469   using namespace llvm;
3470 
3471   SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3472   SortedFileDeclIDs.reserve(FileDeclIDs.size());
3473   for (const auto &P : FileDeclIDs)
3474     SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3475   llvm::sort(SortedFileDeclIDs, llvm::less_first());
3476 
3477   // Join the vectors of DeclIDs from all files.
3478   SmallVector<DeclID, 256> FileGroupedDeclIDs;
3479   for (auto &FileDeclEntry : SortedFileDeclIDs) {
3480     DeclIDInFileInfo &Info = *FileDeclEntry.second;
3481     Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3482     llvm::stable_sort(Info.DeclIDs);
3483     for (auto &LocDeclEntry : Info.DeclIDs)
3484       FileGroupedDeclIDs.push_back(LocDeclEntry.second.getRawValue());
3485   }
3486 
3487   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3488   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3489   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3490   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3491   unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3492   RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3493                                      FileGroupedDeclIDs.size()};
3494   Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3495 }
3496 
3497 void ASTWriter::WriteComments(ASTContext &Context) {
3498   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3499   auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3500   if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3501     return;
3502 
3503   // Don't write comments to BMI to reduce the size of BMI.
3504   // If language services (e.g., clangd) want such abilities,
3505   // we can offer a special option then.
3506   if (isWritingStdCXXNamedModules())
3507     return;
3508 
3509   RecordData Record;
3510   for (const auto &FO : Context.Comments.OrderedComments) {
3511     for (const auto &OC : FO.second) {
3512       const RawComment *I = OC.second;
3513       Record.clear();
3514       AddSourceRange(I->getSourceRange(), Record);
3515       Record.push_back(I->getKind());
3516       Record.push_back(I->isTrailingComment());
3517       Record.push_back(I->isAlmostTrailingComment());
3518       Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3519     }
3520   }
3521 }
3522 
3523 //===----------------------------------------------------------------------===//
3524 // Global Method Pool and Selector Serialization
3525 //===----------------------------------------------------------------------===//
3526 
3527 namespace {
3528 
3529 // Trait used for the on-disk hash table used in the method pool.
3530 class ASTMethodPoolTrait {
3531   ASTWriter &Writer;
3532 
3533 public:
3534   using key_type = Selector;
3535   using key_type_ref = key_type;
3536 
3537   struct data_type {
3538     SelectorID ID;
3539     ObjCMethodList Instance, Factory;
3540   };
3541   using data_type_ref = const data_type &;
3542 
3543   using hash_value_type = unsigned;
3544   using offset_type = unsigned;
3545 
3546   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3547 
3548   static hash_value_type ComputeHash(Selector Sel) {
3549     return serialization::ComputeHash(Sel);
3550   }
3551 
3552   std::pair<unsigned, unsigned>
3553     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3554                       data_type_ref Methods) {
3555     unsigned KeyLen =
3556         2 + (Sel.getNumArgs() ? Sel.getNumArgs() * sizeof(IdentifierID)
3557                               : sizeof(IdentifierID));
3558     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3559     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3560          Method = Method->getNext())
3561       if (ShouldWriteMethodListNode(Method))
3562         DataLen += sizeof(DeclID);
3563     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3564          Method = Method->getNext())
3565       if (ShouldWriteMethodListNode(Method))
3566         DataLen += sizeof(DeclID);
3567     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3568   }
3569 
3570   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3571     using namespace llvm::support;
3572 
3573     endian::Writer LE(Out, llvm::endianness::little);
3574     uint64_t Start = Out.tell();
3575     assert((Start >> 32) == 0 && "Selector key offset too large");
3576     Writer.SetSelectorOffset(Sel, Start);
3577     unsigned N = Sel.getNumArgs();
3578     LE.write<uint16_t>(N);
3579     if (N == 0)
3580       N = 1;
3581     for (unsigned I = 0; I != N; ++I)
3582       LE.write<IdentifierID>(
3583           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3584   }
3585 
3586   void EmitData(raw_ostream& Out, key_type_ref,
3587                 data_type_ref Methods, unsigned DataLen) {
3588     using namespace llvm::support;
3589 
3590     endian::Writer LE(Out, llvm::endianness::little);
3591     uint64_t Start = Out.tell(); (void)Start;
3592     LE.write<uint32_t>(Methods.ID);
3593     unsigned NumInstanceMethods = 0;
3594     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3595          Method = Method->getNext())
3596       if (ShouldWriteMethodListNode(Method))
3597         ++NumInstanceMethods;
3598 
3599     unsigned NumFactoryMethods = 0;
3600     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3601          Method = Method->getNext())
3602       if (ShouldWriteMethodListNode(Method))
3603         ++NumFactoryMethods;
3604 
3605     unsigned InstanceBits = Methods.Instance.getBits();
3606     assert(InstanceBits < 4);
3607     unsigned InstanceHasMoreThanOneDeclBit =
3608         Methods.Instance.hasMoreThanOneDecl();
3609     unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3610                                 (InstanceHasMoreThanOneDeclBit << 2) |
3611                                 InstanceBits;
3612     unsigned FactoryBits = Methods.Factory.getBits();
3613     assert(FactoryBits < 4);
3614     unsigned FactoryHasMoreThanOneDeclBit =
3615         Methods.Factory.hasMoreThanOneDecl();
3616     unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3617                                (FactoryHasMoreThanOneDeclBit << 2) |
3618                                FactoryBits;
3619     LE.write<uint16_t>(FullInstanceBits);
3620     LE.write<uint16_t>(FullFactoryBits);
3621     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3622          Method = Method->getNext())
3623       if (ShouldWriteMethodListNode(Method))
3624         LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3625     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3626          Method = Method->getNext())
3627       if (ShouldWriteMethodListNode(Method))
3628         LE.write<DeclID>((DeclID)Writer.getDeclID(Method->getMethod()));
3629 
3630     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3631   }
3632 
3633 private:
3634   static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3635     return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3636   }
3637 };
3638 
3639 } // namespace
3640 
3641 /// Write ObjC data: selectors and the method pool.
3642 ///
3643 /// The method pool contains both instance and factory methods, stored
3644 /// in an on-disk hash table indexed by the selector. The hash table also
3645 /// contains an empty entry for every other selector known to Sema.
3646 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3647   using namespace llvm;
3648 
3649   // Do we have to do anything at all?
3650   if (SemaRef.ObjC().MethodPool.empty() && SelectorIDs.empty())
3651     return;
3652   unsigned NumTableEntries = 0;
3653   // Create and write out the blob that contains selectors and the method pool.
3654   {
3655     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3656     ASTMethodPoolTrait Trait(*this);
3657 
3658     // Create the on-disk hash table representation. We walk through every
3659     // selector we've seen and look it up in the method pool.
3660     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3661     for (auto &SelectorAndID : SelectorIDs) {
3662       Selector S = SelectorAndID.first;
3663       SelectorID ID = SelectorAndID.second;
3664       SemaObjC::GlobalMethodPool::iterator F =
3665           SemaRef.ObjC().MethodPool.find(S);
3666       ASTMethodPoolTrait::data_type Data = {
3667         ID,
3668         ObjCMethodList(),
3669         ObjCMethodList()
3670       };
3671       if (F != SemaRef.ObjC().MethodPool.end()) {
3672         Data.Instance = F->second.first;
3673         Data.Factory = F->second.second;
3674       }
3675       // Only write this selector if it's not in an existing AST or something
3676       // changed.
3677       if (Chain && ID < FirstSelectorID) {
3678         // Selector already exists. Did it change?
3679         bool changed = false;
3680         for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3681              M = M->getNext()) {
3682           if (!M->getMethod()->isFromASTFile()) {
3683             changed = true;
3684             Data.Instance = *M;
3685             break;
3686           }
3687         }
3688         for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3689              M = M->getNext()) {
3690           if (!M->getMethod()->isFromASTFile()) {
3691             changed = true;
3692             Data.Factory = *M;
3693             break;
3694           }
3695         }
3696         if (!changed)
3697           continue;
3698       } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3699         // A new method pool entry.
3700         ++NumTableEntries;
3701       }
3702       Generator.insert(S, Data, Trait);
3703     }
3704 
3705     // Create the on-disk hash table in a buffer.
3706     SmallString<4096> MethodPool;
3707     uint32_t BucketOffset;
3708     {
3709       using namespace llvm::support;
3710 
3711       ASTMethodPoolTrait Trait(*this);
3712       llvm::raw_svector_ostream Out(MethodPool);
3713       // Make sure that no bucket is at offset 0
3714       endian::write<uint32_t>(Out, 0, llvm::endianness::little);
3715       BucketOffset = Generator.Emit(Out, Trait);
3716     }
3717 
3718     // Create a blob abbreviation
3719     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3720     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3721     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3722     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3723     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3724     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3725 
3726     // Write the method pool
3727     {
3728       RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3729                                          NumTableEntries};
3730       Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3731     }
3732 
3733     // Create a blob abbreviation for the selector table offsets.
3734     Abbrev = std::make_shared<BitCodeAbbrev>();
3735     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3736     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3737     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3738     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3739     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3740 
3741     // Write the selector offsets table.
3742     {
3743       RecordData::value_type Record[] = {
3744           SELECTOR_OFFSETS, SelectorOffsets.size(),
3745           FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3746       Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3747                                 bytes(SelectorOffsets));
3748     }
3749   }
3750 }
3751 
3752 /// Write the selectors referenced in @selector expression into AST file.
3753 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3754   using namespace llvm;
3755 
3756   if (SemaRef.ObjC().ReferencedSelectors.empty())
3757     return;
3758 
3759   RecordData Record;
3760   ASTRecordWriter Writer(SemaRef.Context, *this, Record);
3761 
3762   // Note: this writes out all references even for a dependent AST. But it is
3763   // very tricky to fix, and given that @selector shouldn't really appear in
3764   // headers, probably not worth it. It's not a correctness issue.
3765   for (auto &SelectorAndLocation : SemaRef.ObjC().ReferencedSelectors) {
3766     Selector Sel = SelectorAndLocation.first;
3767     SourceLocation Loc = SelectorAndLocation.second;
3768     Writer.AddSelectorRef(Sel);
3769     Writer.AddSourceLocation(Loc);
3770   }
3771   Writer.Emit(REFERENCED_SELECTOR_POOL);
3772 }
3773 
3774 //===----------------------------------------------------------------------===//
3775 // Identifier Table Serialization
3776 //===----------------------------------------------------------------------===//
3777 
3778 /// Determine the declaration that should be put into the name lookup table to
3779 /// represent the given declaration in this module. This is usually D itself,
3780 /// but if D was imported and merged into a local declaration, we want the most
3781 /// recent local declaration instead. The chosen declaration will be the most
3782 /// recent declaration in any module that imports this one.
3783 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3784                                         NamedDecl *D) {
3785   if (!LangOpts.Modules || !D->isFromASTFile())
3786     return D;
3787 
3788   if (Decl *Redecl = D->getPreviousDecl()) {
3789     // For Redeclarable decls, a prior declaration might be local.
3790     for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3791       // If we find a local decl, we're done.
3792       if (!Redecl->isFromASTFile()) {
3793         // Exception: in very rare cases (for injected-class-names), not all
3794         // redeclarations are in the same semantic context. Skip ones in a
3795         // different context. They don't go in this lookup table at all.
3796         if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3797                 D->getDeclContext()->getRedeclContext()))
3798           continue;
3799         return cast<NamedDecl>(Redecl);
3800       }
3801 
3802       // If we find a decl from a (chained-)PCH stop since we won't find a
3803       // local one.
3804       if (Redecl->getOwningModuleID() == 0)
3805         break;
3806     }
3807   } else if (Decl *First = D->getCanonicalDecl()) {
3808     // For Mergeable decls, the first decl might be local.
3809     if (!First->isFromASTFile())
3810       return cast<NamedDecl>(First);
3811   }
3812 
3813   // All declarations are imported. Our most recent declaration will also be
3814   // the most recent one in anyone who imports us.
3815   return D;
3816 }
3817 
3818 namespace {
3819 
3820 bool IsInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset,
3821                              bool IsModule, bool IsCPlusPlus) {
3822   bool NeedDecls = !IsModule || !IsCPlusPlus;
3823 
3824   bool IsInteresting =
3825       II->getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
3826       II->getBuiltinID() != Builtin::ID::NotBuiltin ||
3827       II->getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
3828   if (MacroOffset ||
3829       (II->hasMacroDefinition() &&
3830        II->hasFETokenInfoChangedSinceDeserialization()) ||
3831       II->isPoisoned() || (!IsModule && IsInteresting) ||
3832       II->hasRevertedTokenIDToIdentifier() ||
3833       (NeedDecls && II->getFETokenInfo()))
3834     return true;
3835 
3836   return false;
3837 }
3838 
3839 bool IsInterestingNonMacroIdentifier(const IdentifierInfo *II,
3840                                      ASTWriter &Writer) {
3841   bool IsModule = Writer.isWritingModule();
3842   bool IsCPlusPlus = Writer.getLangOpts().CPlusPlus;
3843   return IsInterestingIdentifier(II, /*MacroOffset=*/0, IsModule, IsCPlusPlus);
3844 }
3845 
3846 class ASTIdentifierTableTrait {
3847   ASTWriter &Writer;
3848   Preprocessor &PP;
3849   IdentifierResolver *IdResolver;
3850   bool IsModule;
3851   bool NeedDecls;
3852   ASTWriter::RecordData *InterestingIdentifierOffsets;
3853 
3854   /// Determines whether this is an "interesting" identifier that needs a
3855   /// full IdentifierInfo structure written into the hash table. Notably, this
3856   /// doesn't check whether the name has macros defined; use PublicMacroIterator
3857   /// to check that.
3858   bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3859     return IsInterestingIdentifier(II, MacroOffset, IsModule,
3860                                    Writer.getLangOpts().CPlusPlus);
3861   }
3862 
3863 public:
3864   using key_type = const IdentifierInfo *;
3865   using key_type_ref = key_type;
3866 
3867   using data_type = IdentifierID;
3868   using data_type_ref = data_type;
3869 
3870   using hash_value_type = unsigned;
3871   using offset_type = unsigned;
3872 
3873   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3874                           IdentifierResolver *IdResolver, bool IsModule,
3875                           ASTWriter::RecordData *InterestingIdentifierOffsets)
3876       : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3877         NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3878         InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3879 
3880   bool needDecls() const { return NeedDecls; }
3881 
3882   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3883     return llvm::djbHash(II->getName());
3884   }
3885 
3886   bool isInterestingIdentifier(const IdentifierInfo *II) {
3887     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3888     return isInterestingIdentifier(II, MacroOffset);
3889   }
3890 
3891   std::pair<unsigned, unsigned>
3892   EmitKeyDataLength(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID) {
3893     // Record the location of the identifier data. This is used when generating
3894     // the mapping from persistent IDs to strings.
3895     Writer.SetIdentifierOffset(II, Out.tell());
3896 
3897     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3898 
3899     // Emit the offset of the key/data length information to the interesting
3900     // identifiers table if necessary.
3901     if (InterestingIdentifierOffsets &&
3902         isInterestingIdentifier(II, MacroOffset))
3903       InterestingIdentifierOffsets->push_back(Out.tell());
3904 
3905     unsigned KeyLen = II->getLength() + 1;
3906     unsigned DataLen = sizeof(IdentifierID); // bytes for the persistent ID << 1
3907     if (isInterestingIdentifier(II, MacroOffset)) {
3908       DataLen += 2; // 2 bytes for builtin ID
3909       DataLen += 2; // 2 bytes for flags
3910       if (MacroOffset || (II->hasMacroDefinition() &&
3911                           II->hasFETokenInfoChangedSinceDeserialization()))
3912         DataLen += 4; // MacroDirectives offset.
3913 
3914       if (NeedDecls && IdResolver)
3915         DataLen += std::distance(IdResolver->begin(II), IdResolver->end()) *
3916                    sizeof(DeclID);
3917     }
3918     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3919   }
3920 
3921   void EmitKey(raw_ostream &Out, const IdentifierInfo *II, unsigned KeyLen) {
3922     Out.write(II->getNameStart(), KeyLen);
3923   }
3924 
3925   void EmitData(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID,
3926                 unsigned) {
3927     using namespace llvm::support;
3928 
3929     endian::Writer LE(Out, llvm::endianness::little);
3930 
3931     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3932     if (!isInterestingIdentifier(II, MacroOffset)) {
3933       LE.write<IdentifierID>(ID << 1);
3934       return;
3935     }
3936 
3937     LE.write<IdentifierID>((ID << 1) | 0x01);
3938     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3939     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3940     LE.write<uint16_t>(Bits);
3941     Bits = 0;
3942     bool HasMacroDefinition =
3943         (MacroOffset != 0) || (II->hasMacroDefinition() &&
3944                                II->hasFETokenInfoChangedSinceDeserialization());
3945     Bits = (Bits << 1) | unsigned(HasMacroDefinition);
3946     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3947     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3948     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3949     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3950     LE.write<uint16_t>(Bits);
3951 
3952     if (HasMacroDefinition)
3953       LE.write<uint32_t>(MacroOffset);
3954 
3955     if (NeedDecls && IdResolver) {
3956       // Emit the declaration IDs in reverse order, because the
3957       // IdentifierResolver provides the declarations as they would be
3958       // visible (e.g., the function "stat" would come before the struct
3959       // "stat"), but the ASTReader adds declarations to the end of the list
3960       // (so we need to see the struct "stat" before the function "stat").
3961       // Only emit declarations that aren't from a chained PCH, though.
3962       SmallVector<NamedDecl *, 16> Decls(IdResolver->decls(II));
3963       for (NamedDecl *D : llvm::reverse(Decls))
3964         LE.write<DeclID>((DeclID)Writer.getDeclID(
3965             getDeclForLocalLookup(PP.getLangOpts(), D)));
3966     }
3967   }
3968 };
3969 
3970 } // namespace
3971 
3972 /// If the \param IdentifierID ID is a local Identifier ID. If the higher
3973 /// bits of ID is 0, it implies that the ID doesn't come from AST files.
3974 static bool isLocalIdentifierID(IdentifierID ID) { return !(ID >> 32); }
3975 
3976 /// Write the identifier table into the AST file.
3977 ///
3978 /// The identifier table consists of a blob containing string data
3979 /// (the actual identifiers themselves) and a separate "offsets" index
3980 /// that maps identifier IDs to locations within the blob.
3981 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3982                                      IdentifierResolver *IdResolver,
3983                                      bool IsModule) {
3984   using namespace llvm;
3985 
3986   RecordData InterestingIdents;
3987 
3988   // Create and write out the blob that contains the identifier
3989   // strings.
3990   {
3991     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3992     ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule,
3993                                   IsModule ? &InterestingIdents : nullptr);
3994 
3995     // Create the on-disk hash table representation. We only store offsets
3996     // for identifiers that appear here for the first time.
3997     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3998     for (auto IdentIDPair : IdentifierIDs) {
3999       const IdentifierInfo *II = IdentIDPair.first;
4000       IdentifierID ID = IdentIDPair.second;
4001       assert(II && "NULL identifier in identifier table");
4002 
4003       // Write out identifiers if either the ID is local or the identifier has
4004       // changed since it was loaded.
4005       if (isLocalIdentifierID(ID) || II->hasChangedSinceDeserialization() ||
4006           (Trait.needDecls() &&
4007            II->hasFETokenInfoChangedSinceDeserialization()))
4008         Generator.insert(II, ID, Trait);
4009     }
4010 
4011     // Create the on-disk hash table in a buffer.
4012     SmallString<4096> IdentifierTable;
4013     uint32_t BucketOffset;
4014     {
4015       using namespace llvm::support;
4016 
4017       llvm::raw_svector_ostream Out(IdentifierTable);
4018       // Make sure that no bucket is at offset 0
4019       endian::write<uint32_t>(Out, 0, llvm::endianness::little);
4020       BucketOffset = Generator.Emit(Out, Trait);
4021     }
4022 
4023     // Create a blob abbreviation
4024     auto Abbrev = std::make_shared<BitCodeAbbrev>();
4025     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
4026     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4027     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4028     unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4029 
4030     // Write the identifier table
4031     RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
4032     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
4033   }
4034 
4035   // Write the offsets table for identifier IDs.
4036   auto Abbrev = std::make_shared<BitCodeAbbrev>();
4037   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
4038   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
4039   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4040   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4041 
4042 #ifndef NDEBUG
4043   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
4044     assert(IdentifierOffsets[I] && "Missing identifier offset?");
4045 #endif
4046 
4047   RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
4048                                      IdentifierOffsets.size()};
4049   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
4050                             bytes(IdentifierOffsets));
4051 
4052   // In C++, write the list of interesting identifiers (those that are
4053   // defined as macros, poisoned, or similar unusual things).
4054   if (!InterestingIdents.empty())
4055     Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
4056 }
4057 
4058 void ASTWriter::handleVTable(CXXRecordDecl *RD) {
4059   if (!RD->isInNamedModule())
4060     return;
4061 
4062   PendingEmittingVTables.push_back(RD);
4063 }
4064 
4065 void ASTWriter::addTouchedModuleFile(serialization::ModuleFile *MF) {
4066   TouchedModuleFiles.insert(MF);
4067 }
4068 
4069 //===----------------------------------------------------------------------===//
4070 // DeclContext's Name Lookup Table Serialization
4071 //===----------------------------------------------------------------------===//
4072 
4073 namespace {
4074 
4075 class ASTDeclContextNameLookupTraitBase {
4076 protected:
4077   ASTWriter &Writer;
4078   using DeclIDsTy = llvm::SmallVector<LocalDeclID, 64>;
4079   DeclIDsTy DeclIDs;
4080 
4081 public:
4082   /// A start and end index into DeclIDs, representing a sequence of decls.
4083   using data_type = std::pair<unsigned, unsigned>;
4084   using data_type_ref = const data_type &;
4085 
4086   using hash_value_type = unsigned;
4087   using offset_type = unsigned;
4088 
4089   explicit ASTDeclContextNameLookupTraitBase(ASTWriter &Writer)
4090       : Writer(Writer) {}
4091 
4092   data_type getData(const DeclIDsTy &LocalIDs) {
4093     unsigned Start = DeclIDs.size();
4094     for (auto ID : LocalIDs)
4095       DeclIDs.push_back(ID);
4096     return std::make_pair(Start, DeclIDs.size());
4097   }
4098 
4099   data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
4100     unsigned Start = DeclIDs.size();
4101     DeclIDs.insert(
4102         DeclIDs.end(),
4103         DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.begin()),
4104         DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.end()));
4105     return std::make_pair(Start, DeclIDs.size());
4106   }
4107 
4108   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4109     assert(Writer.hasChain() &&
4110            "have reference to loaded module file but no chain?");
4111 
4112     using namespace llvm::support;
4113     Writer.addTouchedModuleFile(F);
4114     endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
4115                             llvm::endianness::little);
4116   }
4117 
4118   std::pair<unsigned, unsigned> EmitKeyDataLengthBase(raw_ostream &Out,
4119                                                       DeclarationNameKey Name,
4120                                                       data_type_ref Lookup) {
4121     unsigned KeyLen = 1;
4122     switch (Name.getKind()) {
4123     case DeclarationName::Identifier:
4124     case DeclarationName::CXXLiteralOperatorName:
4125     case DeclarationName::CXXDeductionGuideName:
4126       KeyLen += sizeof(IdentifierID);
4127       break;
4128     case DeclarationName::ObjCZeroArgSelector:
4129     case DeclarationName::ObjCOneArgSelector:
4130     case DeclarationName::ObjCMultiArgSelector:
4131       KeyLen += 4;
4132       break;
4133     case DeclarationName::CXXOperatorName:
4134       KeyLen += 1;
4135       break;
4136     case DeclarationName::CXXConstructorName:
4137     case DeclarationName::CXXDestructorName:
4138     case DeclarationName::CXXConversionFunctionName:
4139     case DeclarationName::CXXUsingDirective:
4140       break;
4141     }
4142 
4143     // length of DeclIDs.
4144     unsigned DataLen = sizeof(DeclID) * (Lookup.second - Lookup.first);
4145 
4146     return {KeyLen, DataLen};
4147   }
4148 
4149   void EmitKeyBase(raw_ostream &Out, DeclarationNameKey Name) {
4150     using namespace llvm::support;
4151 
4152     endian::Writer LE(Out, llvm::endianness::little);
4153     LE.write<uint8_t>(Name.getKind());
4154     switch (Name.getKind()) {
4155     case DeclarationName::Identifier:
4156     case DeclarationName::CXXLiteralOperatorName:
4157     case DeclarationName::CXXDeductionGuideName:
4158       LE.write<IdentifierID>(Writer.getIdentifierRef(Name.getIdentifier()));
4159       return;
4160     case DeclarationName::ObjCZeroArgSelector:
4161     case DeclarationName::ObjCOneArgSelector:
4162     case DeclarationName::ObjCMultiArgSelector:
4163       LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
4164       return;
4165     case DeclarationName::CXXOperatorName:
4166       assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
4167              "Invalid operator?");
4168       LE.write<uint8_t>(Name.getOperatorKind());
4169       return;
4170     case DeclarationName::CXXConstructorName:
4171     case DeclarationName::CXXDestructorName:
4172     case DeclarationName::CXXConversionFunctionName:
4173     case DeclarationName::CXXUsingDirective:
4174       return;
4175     }
4176 
4177     llvm_unreachable("Invalid name kind?");
4178   }
4179 
4180   void EmitDataBase(raw_ostream &Out, data_type Lookup, unsigned DataLen) {
4181     using namespace llvm::support;
4182 
4183     endian::Writer LE(Out, llvm::endianness::little);
4184     uint64_t Start = Out.tell(); (void)Start;
4185     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
4186       LE.write<DeclID>((DeclID)DeclIDs[I]);
4187     assert(Out.tell() - Start == DataLen && "Data length is wrong");
4188   }
4189 };
4190 
4191 class ModuleLevelNameLookupTrait : public ASTDeclContextNameLookupTraitBase {
4192 public:
4193   using primary_module_hash_type = unsigned;
4194 
4195   using key_type = std::pair<DeclarationNameKey, primary_module_hash_type>;
4196   using key_type_ref = key_type;
4197 
4198   explicit ModuleLevelNameLookupTrait(ASTWriter &Writer)
4199       : ASTDeclContextNameLookupTraitBase(Writer) {}
4200 
4201   static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4202 
4203   hash_value_type ComputeHash(key_type Key) {
4204     llvm::FoldingSetNodeID ID;
4205     ID.AddInteger(Key.first.getHash());
4206     ID.AddInteger(Key.second);
4207     return ID.computeStableHash();
4208   }
4209 
4210   std::pair<unsigned, unsigned>
4211   EmitKeyDataLength(raw_ostream &Out, key_type Key, data_type_ref Lookup) {
4212     auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Key.first, Lookup);
4213     KeyLen += sizeof(Key.second);
4214     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4215   }
4216 
4217   void EmitKey(raw_ostream &Out, key_type Key, unsigned) {
4218     EmitKeyBase(Out, Key.first);
4219     llvm::support::endian::Writer LE(Out, llvm::endianness::little);
4220     LE.write<primary_module_hash_type>(Key.second);
4221   }
4222 
4223   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4224                 unsigned DataLen) {
4225     EmitDataBase(Out, Lookup, DataLen);
4226   }
4227 };
4228 
4229 class ASTDeclContextNameTrivialLookupTrait
4230     : public ASTDeclContextNameLookupTraitBase {
4231 public:
4232   using key_type = DeclarationNameKey;
4233   using key_type_ref = key_type;
4234 
4235 public:
4236   using ASTDeclContextNameLookupTraitBase::ASTDeclContextNameLookupTraitBase;
4237 
4238   using ASTDeclContextNameLookupTraitBase::getData;
4239 
4240   static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4241 
4242   hash_value_type ComputeHash(key_type Name) { return Name.getHash(); }
4243 
4244   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4245                                                   DeclarationNameKey Name,
4246                                                   data_type_ref Lookup) {
4247     auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Name, Lookup);
4248     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4249   }
4250 
4251   void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
4252     return EmitKeyBase(Out, Name);
4253   }
4254 
4255   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4256                 unsigned DataLen) {
4257     EmitDataBase(Out, Lookup, DataLen);
4258   }
4259 };
4260 
4261 static bool isModuleLocalDecl(NamedDecl *D) {
4262   // For decls not in a file context, they should have the same visibility
4263   // with their parent.
4264   if (auto *Parent = dyn_cast<NamedDecl>(D->getNonTransparentDeclContext());
4265       Parent && !D->getNonTransparentDeclContext()->isFileContext())
4266     return isModuleLocalDecl(Parent);
4267 
4268   // Deduction Guide are special here. Since their logical parent context are
4269   // not their actual parent.
4270   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4271     if (auto *CDGD = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl()))
4272       return isModuleLocalDecl(CDGD->getDeducedTemplate());
4273 
4274   if (D->getFormalLinkage() == Linkage::Module)
4275     return true;
4276 
4277   return false;
4278 }
4279 
4280 static bool isTULocalInNamedModules(NamedDecl *D) {
4281   Module *NamedModule = D->getTopLevelOwningNamedModule();
4282   if (!NamedModule)
4283     return false;
4284 
4285   // For none-top level decls, we choose to move it to the general visible
4286   // lookup table. Since the consumer may get its parent somehow and performs
4287   // a lookup in it (considering looking up the operator function in lambda).
4288   // The difference between module local lookup table and TU local lookup table
4289   // is, the consumers still have a chance to lookup in the module local lookup
4290   // table but **now** the consumers won't read the TU local lookup table if
4291   // the consumer is not the original TU.
4292   //
4293   // FIXME: It seems to be an optimization chance (and also a more correct
4294   // semantics) to remain the TULocal lookup table and performing similar lookup
4295   // with the module local lookup table except that we only allow the lookups
4296   // with the same module unit.
4297   if (!D->getNonTransparentDeclContext()->isFileContext())
4298     return false;
4299 
4300   return D->getLinkageInternal() == Linkage::Internal;
4301 }
4302 
4303 class ASTDeclContextNameLookupTrait
4304     : public ASTDeclContextNameTrivialLookupTrait {
4305 public:
4306   using TULocalDeclsMapTy = llvm::DenseMap<key_type, DeclIDsTy>;
4307 
4308   using ModuleLevelDeclsMapTy =
4309       llvm::DenseMap<ModuleLevelNameLookupTrait::key_type, DeclIDsTy>;
4310 
4311 private:
4312   enum class LookupVisibility {
4313     GenerallyVisibile,
4314     // The decls can only be found by other TU in the same module.
4315     // Note a clang::Module models a module unit instead of logical module
4316     // in C++20.
4317     ModuleLocalVisible,
4318     // The decls can only be found by the TU itself that defines it.
4319     TULocal,
4320   };
4321 
4322   LookupVisibility getLookupVisibility(NamedDecl *D) const {
4323     // Only named modules have other lookup visibility.
4324     if (!Writer.isWritingStdCXXNamedModules())
4325       return LookupVisibility::GenerallyVisibile;
4326 
4327     if (isModuleLocalDecl(D))
4328       return LookupVisibility::ModuleLocalVisible;
4329     if (isTULocalInNamedModules(D))
4330       return LookupVisibility::TULocal;
4331 
4332     // A trick to handle enum constants. The enum constants is special since
4333     // they can be found directly without their parent context. This makes it
4334     // tricky to decide if an EnumConstantDecl is visible or not by their own
4335     // visibilities. E.g., for a class member, we can assume it is visible if
4336     // the user get its parent somehow. But for an enum constant, the users may
4337     // access if without its parent context. Although we can fix the problem in
4338     // Sema lookup process, it might be too complex, we just make a trick here.
4339     // Note that we only removes enum constant from the lookup table from its
4340     // parent of parent. We DON'T remove the enum constant from its parent. So
4341     // we don't need to care about merging problems here.
4342     if (auto *ECD = dyn_cast<EnumConstantDecl>(D);
4343         ECD && DC.isFileContext() && ECD->getOwningModule() &&
4344         ECD->getTopLevelOwningNamedModule()->isNamedModule()) {
4345       if (llvm::all_of(
4346               DC.noload_lookup(
4347                   cast<EnumDecl>(ECD->getDeclContext())->getDeclName()),
4348               [](auto *Found) {
4349                 return Found->isInvisibleOutsideTheOwningModule();
4350               }))
4351         return ECD->isFromExplicitGlobalModule() ||
4352                        ECD->isInAnonymousNamespace()
4353                    ? LookupVisibility::TULocal
4354                    : LookupVisibility::ModuleLocalVisible;
4355     }
4356 
4357     return LookupVisibility::GenerallyVisibile;
4358   }
4359 
4360   DeclContext &DC;
4361   ModuleLevelDeclsMapTy ModuleLocalDeclsMap;
4362   TULocalDeclsMapTy TULocalDeclsMap;
4363 
4364 public:
4365   using ASTDeclContextNameTrivialLookupTrait::
4366       ASTDeclContextNameTrivialLookupTrait;
4367 
4368   ASTDeclContextNameLookupTrait(ASTWriter &Writer, DeclContext &DC)
4369       : ASTDeclContextNameTrivialLookupTrait(Writer), DC(DC) {}
4370 
4371   template <typename Coll> data_type getData(const Coll &Decls) {
4372     unsigned Start = DeclIDs.size();
4373     for (NamedDecl *D : Decls) {
4374       NamedDecl *DeclForLocalLookup =
4375           getDeclForLocalLookup(Writer.getLangOpts(), D);
4376 
4377       if (Writer.getDoneWritingDeclsAndTypes() &&
4378           !Writer.wasDeclEmitted(DeclForLocalLookup))
4379         continue;
4380 
4381       // Try to avoid writing internal decls to reduced BMI.
4382       // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
4383       if (Writer.isGeneratingReducedBMI() &&
4384           !DeclForLocalLookup->isFromExplicitGlobalModule() &&
4385           IsInternalDeclFromFileContext(DeclForLocalLookup))
4386         continue;
4387 
4388       auto ID = Writer.GetDeclRef(DeclForLocalLookup);
4389 
4390       switch (getLookupVisibility(DeclForLocalLookup)) {
4391       case LookupVisibility::ModuleLocalVisible:
4392         if (UnsignedOrNone PrimaryModuleHash =
4393                 getPrimaryModuleHash(D->getOwningModule())) {
4394           auto Key = std::make_pair(D->getDeclName(), *PrimaryModuleHash);
4395           auto Iter = ModuleLocalDeclsMap.find(Key);
4396           if (Iter == ModuleLocalDeclsMap.end())
4397             ModuleLocalDeclsMap.insert({Key, DeclIDsTy{ID}});
4398           else
4399             Iter->second.push_back(ID);
4400           continue;
4401         }
4402         break;
4403       case LookupVisibility::TULocal: {
4404         auto Iter = TULocalDeclsMap.find(D->getDeclName());
4405         if (Iter == TULocalDeclsMap.end())
4406           TULocalDeclsMap.insert({D->getDeclName(), DeclIDsTy{ID}});
4407         else
4408           Iter->second.push_back(ID);
4409         continue;
4410       }
4411       case LookupVisibility::GenerallyVisibile:
4412         // Generally visible decls go into the general lookup table.
4413         break;
4414       }
4415 
4416       DeclIDs.push_back(ID);
4417     }
4418     return std::make_pair(Start, DeclIDs.size());
4419   }
4420 
4421   const ModuleLevelDeclsMapTy &getModuleLocalDecls() {
4422     return ModuleLocalDeclsMap;
4423   }
4424 
4425   const TULocalDeclsMapTy &getTULocalDecls() { return TULocalDeclsMap; }
4426 };
4427 
4428 } // namespace
4429 
4430 namespace {
4431 class LazySpecializationInfoLookupTrait {
4432   ASTWriter &Writer;
4433   llvm::SmallVector<serialization::reader::LazySpecializationInfo, 64> Specs;
4434 
4435 public:
4436   using key_type = unsigned;
4437   using key_type_ref = key_type;
4438 
4439   /// A start and end index into Specs, representing a sequence of decls.
4440   using data_type = std::pair<unsigned, unsigned>;
4441   using data_type_ref = const data_type &;
4442 
4443   using hash_value_type = unsigned;
4444   using offset_type = unsigned;
4445 
4446   explicit LazySpecializationInfoLookupTrait(ASTWriter &Writer)
4447       : Writer(Writer) {}
4448 
4449   template <typename Col, typename Col2>
4450   data_type getData(Col &&C, Col2 &ExistingInfo) {
4451     unsigned Start = Specs.size();
4452     for (auto *D : C) {
4453       NamedDecl *ND = getDeclForLocalLookup(Writer.getLangOpts(),
4454                                             const_cast<NamedDecl *>(D));
4455       Specs.push_back(GlobalDeclID(Writer.GetDeclRef(ND).getRawValue()));
4456     }
4457     for (const serialization::reader::LazySpecializationInfo &Info :
4458          ExistingInfo)
4459       Specs.push_back(Info);
4460     return std::make_pair(Start, Specs.size());
4461   }
4462 
4463   data_type ImportData(
4464       const reader::LazySpecializationInfoLookupTrait::data_type &FromReader) {
4465     unsigned Start = Specs.size();
4466     for (auto ID : FromReader)
4467       Specs.push_back(ID);
4468     return std::make_pair(Start, Specs.size());
4469   }
4470 
4471   static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4472 
4473   hash_value_type ComputeHash(key_type Name) { return Name; }
4474 
4475   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4476     assert(Writer.hasChain() &&
4477            "have reference to loaded module file but no chain?");
4478 
4479     using namespace llvm::support;
4480     Writer.addTouchedModuleFile(F);
4481     endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F),
4482                             llvm::endianness::little);
4483   }
4484 
4485   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4486                                                   key_type HashValue,
4487                                                   data_type_ref Lookup) {
4488     // 4 bytes for each slot.
4489     unsigned KeyLen = 4;
4490     unsigned DataLen = sizeof(serialization::reader::LazySpecializationInfo) *
4491                        (Lookup.second - Lookup.first);
4492 
4493     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4494   }
4495 
4496   void EmitKey(raw_ostream &Out, key_type HashValue, unsigned) {
4497     using namespace llvm::support;
4498 
4499     endian::Writer LE(Out, llvm::endianness::little);
4500     LE.write<uint32_t>(HashValue);
4501   }
4502 
4503   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4504                 unsigned DataLen) {
4505     using namespace llvm::support;
4506 
4507     endian::Writer LE(Out, llvm::endianness::little);
4508     uint64_t Start = Out.tell();
4509     (void)Start;
4510     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) {
4511       LE.write<DeclID>(Specs[I].getRawValue());
4512     }
4513     assert(Out.tell() - Start == DataLen && "Data length is wrong");
4514   }
4515 };
4516 
4517 unsigned CalculateODRHashForSpecs(const Decl *Spec) {
4518   ArrayRef<TemplateArgument> Args;
4519   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Spec))
4520     Args = CTSD->getTemplateArgs().asArray();
4521   else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Spec))
4522     Args = VTSD->getTemplateArgs().asArray();
4523   else if (auto *FD = dyn_cast<FunctionDecl>(Spec))
4524     Args = FD->getTemplateSpecializationArgs()->asArray();
4525   else
4526     llvm_unreachable("New Specialization Kind?");
4527 
4528   return StableHashForTemplateArguments(Args);
4529 }
4530 } // namespace
4531 
4532 void ASTWriter::GenerateSpecializationInfoLookupTable(
4533     const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4534     llvm::SmallVectorImpl<char> &LookupTable, bool IsPartial) {
4535   assert(D->isFirstDecl());
4536 
4537   // Create the on-disk hash table representation.
4538   MultiOnDiskHashTableGenerator<reader::LazySpecializationInfoLookupTrait,
4539                                 LazySpecializationInfoLookupTrait>
4540       Generator;
4541   LazySpecializationInfoLookupTrait Trait(*this);
4542 
4543   llvm::MapVector<unsigned, llvm::SmallVector<const NamedDecl *, 4>>
4544       SpecializationMaps;
4545 
4546   for (auto *Specialization : Specializations) {
4547     unsigned HashedValue = CalculateODRHashForSpecs(Specialization);
4548 
4549     auto Iter = SpecializationMaps.find(HashedValue);
4550     if (Iter == SpecializationMaps.end())
4551       Iter = SpecializationMaps
4552                  .try_emplace(HashedValue,
4553                               llvm::SmallVector<const NamedDecl *, 4>())
4554                  .first;
4555 
4556     Iter->second.push_back(cast<NamedDecl>(Specialization));
4557   }
4558 
4559   auto *Lookups =
4560       Chain ? Chain->getLoadedSpecializationsLookupTables(D, IsPartial)
4561             : nullptr;
4562 
4563   for (auto &[HashValue, Specs] : SpecializationMaps) {
4564     SmallVector<serialization::reader::LazySpecializationInfo, 16>
4565         ExisitingSpecs;
4566     // We have to merge the lookup table manually here. We can't depend on the
4567     // merge mechanism offered by
4568     // clang::serialization::MultiOnDiskHashTableGenerator since that generator
4569     // assumes the we'll get the same value with the same key.
4570     // And also underlying llvm::OnDiskChainedHashTableGenerator assumes that we
4571     // won't insert the values with the same key twice. So we have to merge the
4572     // lookup table here manually.
4573     if (Lookups)
4574       ExisitingSpecs = Lookups->Table.find(HashValue);
4575 
4576     Generator.insert(HashValue, Trait.getData(Specs, ExisitingSpecs), Trait);
4577   }
4578 
4579   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4580 }
4581 
4582 uint64_t ASTWriter::WriteSpecializationInfoLookupTable(
4583     const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4584     bool IsPartial) {
4585 
4586   llvm::SmallString<4096> LookupTable;
4587   GenerateSpecializationInfoLookupTable(D, Specializations, LookupTable,
4588                                         IsPartial);
4589 
4590   uint64_t Offset = Stream.GetCurrentBitNo();
4591   RecordData::value_type Record[] = {static_cast<RecordData::value_type>(
4592       IsPartial ? DECL_PARTIAL_SPECIALIZATIONS : DECL_SPECIALIZATIONS)};
4593   Stream.EmitRecordWithBlob(IsPartial ? DeclPartialSpecializationsAbbrev
4594                                       : DeclSpecializationsAbbrev,
4595                             Record, LookupTable);
4596 
4597   return Offset;
4598 }
4599 
4600 /// Returns ture if all of the lookup result are either external, not emitted or
4601 /// predefined. In such cases, the lookup result is not interesting and we don't
4602 /// need to record the result in the current being written module. Return false
4603 /// otherwise.
4604 static bool isLookupResultNotInteresting(ASTWriter &Writer,
4605                                          StoredDeclsList &Result) {
4606   for (auto *D : Result.getLookupResult()) {
4607     auto *LocalD = getDeclForLocalLookup(Writer.getLangOpts(), D);
4608     if (LocalD->isFromASTFile())
4609       continue;
4610 
4611     // We can only be sure whether the local declaration is reachable
4612     // after we done writing the declarations and types.
4613     if (Writer.getDoneWritingDeclsAndTypes() && !Writer.wasDeclEmitted(LocalD))
4614       continue;
4615 
4616     // We don't need to emit the predefined decls.
4617     if (Writer.isDeclPredefined(LocalD))
4618       continue;
4619 
4620     return false;
4621   }
4622 
4623   return true;
4624 }
4625 
4626 void ASTWriter::GenerateNameLookupTable(
4627     ASTContext &Context, const DeclContext *ConstDC,
4628     llvm::SmallVectorImpl<char> &LookupTable,
4629     llvm::SmallVectorImpl<char> &ModuleLocalLookupTable,
4630     llvm::SmallVectorImpl<char> &TULookupTable) {
4631   assert(!ConstDC->hasLazyLocalLexicalLookups() &&
4632          !ConstDC->hasLazyExternalLexicalLookups() &&
4633          "must call buildLookups first");
4634 
4635   // FIXME: We need to build the lookups table, which is logically const.
4636   auto *DC = const_cast<DeclContext*>(ConstDC);
4637   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
4638 
4639   // Create the on-disk hash table representation.
4640   MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
4641                                 ASTDeclContextNameLookupTrait>
4642       Generator;
4643   ASTDeclContextNameLookupTrait Trait(*this, *DC);
4644 
4645   // The first step is to collect the declaration names which we need to
4646   // serialize into the name lookup table, and to collect them in a stable
4647   // order.
4648   SmallVector<DeclarationName, 16> Names;
4649 
4650   // We also track whether we're writing out the DeclarationNameKey for
4651   // constructors or conversion functions.
4652   bool IncludeConstructorNames = false;
4653   bool IncludeConversionNames = false;
4654 
4655   for (auto &[Name, Result] : *DC->buildLookup()) {
4656     // If there are no local declarations in our lookup result, we
4657     // don't need to write an entry for the name at all. If we can't
4658     // write out a lookup set without performing more deserialization,
4659     // just skip this entry.
4660     //
4661     // Also in reduced BMI, we'd like to avoid writing unreachable
4662     // declarations in GMF, so we need to avoid writing declarations
4663     // that entirely external or unreachable.
4664     if (GeneratingReducedBMI && isLookupResultNotInteresting(*this, Result))
4665       continue;
4666     // We also skip empty results. If any of the results could be external and
4667     // the currently available results are empty, then all of the results are
4668     // external and we skip it above. So the only way we get here with an empty
4669     // results is when no results could have been external *and* we have
4670     // external results.
4671     //
4672     // FIXME: While we might want to start emitting on-disk entries for negative
4673     // lookups into a decl context as an optimization, today we *have* to skip
4674     // them because there are names with empty lookup results in decl contexts
4675     // which we can't emit in any stable ordering: we lookup constructors and
4676     // conversion functions in the enclosing namespace scope creating empty
4677     // results for them. This in almost certainly a bug in Clang's name lookup,
4678     // but that is likely to be hard or impossible to fix and so we tolerate it
4679     // here by omitting lookups with empty results.
4680     if (Result.getLookupResult().empty())
4681       continue;
4682 
4683     switch (Name.getNameKind()) {
4684     default:
4685       Names.push_back(Name);
4686       break;
4687 
4688     case DeclarationName::CXXConstructorName:
4689       IncludeConstructorNames = true;
4690       break;
4691 
4692     case DeclarationName::CXXConversionFunctionName:
4693       IncludeConversionNames = true;
4694       break;
4695     }
4696   }
4697 
4698   // Sort the names into a stable order.
4699   llvm::sort(Names);
4700 
4701   if (IncludeConstructorNames || IncludeConversionNames) {
4702     // We need to establish an ordering of constructor and conversion function
4703     // names, and they don't have an intrinsic ordering. We also need to write
4704     // out all constructor and conversion function results if we write out any
4705     // of them, because they're all tracked under the same lookup key.
4706     llvm::SmallPtrSet<DeclarationName, 8> AddedNames;
4707     for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) {
4708       if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4709         auto Name = ChildND->getDeclName();
4710         switch (Name.getNameKind()) {
4711         default:
4712           continue;
4713 
4714         case DeclarationName::CXXConstructorName:
4715           if (!IncludeConstructorNames)
4716             continue;
4717           break;
4718 
4719         case DeclarationName::CXXConversionFunctionName:
4720           if (!IncludeConversionNames)
4721             continue;
4722           break;
4723         }
4724         if (AddedNames.insert(Name).second)
4725           Names.push_back(Name);
4726       }
4727     }
4728   }
4729   // Next we need to do a lookup with each name into this decl context to fully
4730   // populate any results from external sources. We don't actually use the
4731   // results of these lookups because we only want to use the results after all
4732   // results have been loaded and the pointers into them will be stable.
4733   for (auto &Name : Names)
4734     DC->lookup(Name);
4735 
4736   // Now we need to insert the results for each name into the hash table. For
4737   // constructor names and conversion function names, we actually need to merge
4738   // all of the results for them into one list of results each and insert
4739   // those.
4740   SmallVector<NamedDecl *, 8> ConstructorDecls;
4741   SmallVector<NamedDecl *, 8> ConversionDecls;
4742 
4743   // Now loop over the names, either inserting them or appending for the two
4744   // special cases.
4745   for (auto &Name : Names) {
4746     DeclContext::lookup_result Result = DC->noload_lookup(Name);
4747 
4748     switch (Name.getNameKind()) {
4749     default:
4750       Generator.insert(Name, Trait.getData(Result), Trait);
4751       break;
4752 
4753     case DeclarationName::CXXConstructorName:
4754       ConstructorDecls.append(Result.begin(), Result.end());
4755       break;
4756 
4757     case DeclarationName::CXXConversionFunctionName:
4758       ConversionDecls.append(Result.begin(), Result.end());
4759       break;
4760     }
4761   }
4762 
4763   // Handle our two special cases if we ended up having any. We arbitrarily use
4764   // the first declaration's name here because the name itself isn't part of
4765   // the key, only the kind of name is used.
4766   if (!ConstructorDecls.empty())
4767     Generator.insert(ConstructorDecls.front()->getDeclName(),
4768                      Trait.getData(ConstructorDecls), Trait);
4769   if (!ConversionDecls.empty())
4770     Generator.insert(ConversionDecls.front()->getDeclName(),
4771                      Trait.getData(ConversionDecls), Trait);
4772 
4773   // Create the on-disk hash table. Also emit the existing imported and
4774   // merged table if there is one.
4775   auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4776   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4777 
4778   const auto &ModuleLocalDecls = Trait.getModuleLocalDecls();
4779   if (!ModuleLocalDecls.empty()) {
4780     MultiOnDiskHashTableGenerator<reader::ModuleLocalNameLookupTrait,
4781                                   ModuleLevelNameLookupTrait>
4782         ModuleLocalLookupGenerator;
4783     ModuleLevelNameLookupTrait ModuleLocalTrait(*this);
4784 
4785     for (const auto &ModuleLocalIter : ModuleLocalDecls) {
4786       const auto &Key = ModuleLocalIter.first;
4787       const auto &IDs = ModuleLocalIter.second;
4788       ModuleLocalLookupGenerator.insert(Key, ModuleLocalTrait.getData(IDs),
4789                                         ModuleLocalTrait);
4790     }
4791 
4792     auto *ModuleLocalLookups =
4793         Chain ? Chain->getModuleLocalLookupTables(DC) : nullptr;
4794     ModuleLocalLookupGenerator.emit(
4795         ModuleLocalLookupTable, ModuleLocalTrait,
4796         ModuleLocalLookups ? &ModuleLocalLookups->Table : nullptr);
4797   }
4798 
4799   const auto &TULocalDecls = Trait.getTULocalDecls();
4800   if (!TULocalDecls.empty() && !isGeneratingReducedBMI()) {
4801     MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
4802                                   ASTDeclContextNameTrivialLookupTrait>
4803         TULookupGenerator;
4804     ASTDeclContextNameTrivialLookupTrait TULocalTrait(*this);
4805 
4806     for (const auto &TULocalIter : TULocalDecls) {
4807       const auto &Key = TULocalIter.first;
4808       const auto &IDs = TULocalIter.second;
4809       TULookupGenerator.insert(Key, TULocalTrait.getData(IDs), TULocalTrait);
4810     }
4811 
4812     auto *TULocalLookups = Chain ? Chain->getTULocalLookupTables(DC) : nullptr;
4813     TULookupGenerator.emit(TULookupTable, TULocalTrait,
4814                            TULocalLookups ? &TULocalLookups->Table : nullptr);
4815   }
4816 }
4817 
4818 /// Write the block containing all of the declaration IDs
4819 /// visible from the given DeclContext.
4820 ///
4821 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4822 /// bitstream, or 0 if no block was written.
4823 void ASTWriter::WriteDeclContextVisibleBlock(
4824     ASTContext &Context, DeclContext *DC, VisibleLookupBlockOffsets &Offsets) {
4825   assert(!Offsets);
4826 
4827   // If we imported a key declaration of this namespace, write the visible
4828   // lookup results as an update record for it rather than including them
4829   // on this declaration. We will only look at key declarations on reload.
4830   if (isa<NamespaceDecl>(DC) && Chain &&
4831       Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4832     // Only do this once, for the first local declaration of the namespace.
4833     for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4834          Prev = Prev->getPreviousDecl())
4835       if (!Prev->isFromASTFile())
4836         return;
4837 
4838     // Note that we need to emit an update record for the primary context.
4839     UpdatedDeclContexts.insert(DC->getPrimaryContext());
4840 
4841     // Make sure all visible decls are written. They will be recorded later. We
4842     // do this using a side data structure so we can sort the names into
4843     // a deterministic order.
4844     StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4845     SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4846         LookupResults;
4847     if (Map) {
4848       LookupResults.reserve(Map->size());
4849       for (auto &Entry : *Map)
4850         LookupResults.push_back(
4851             std::make_pair(Entry.first, Entry.second.getLookupResult()));
4852     }
4853 
4854     llvm::sort(LookupResults, llvm::less_first());
4855     for (auto &NameAndResult : LookupResults) {
4856       DeclarationName Name = NameAndResult.first;
4857       DeclContext::lookup_result Result = NameAndResult.second;
4858       if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4859           Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4860         // We have to work around a name lookup bug here where negative lookup
4861         // results for these names get cached in namespace lookup tables (these
4862         // names should never be looked up in a namespace).
4863         assert(Result.empty() && "Cannot have a constructor or conversion "
4864                                  "function name in a namespace!");
4865         continue;
4866       }
4867 
4868       for (NamedDecl *ND : Result) {
4869         if (ND->isFromASTFile())
4870           continue;
4871 
4872         if (DoneWritingDeclsAndTypes && !wasDeclEmitted(ND))
4873           continue;
4874 
4875         // We don't need to force emitting internal decls into reduced BMI.
4876         // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
4877         if (GeneratingReducedBMI && !ND->isFromExplicitGlobalModule() &&
4878             IsInternalDeclFromFileContext(ND))
4879           continue;
4880 
4881         GetDeclRef(ND);
4882       }
4883     }
4884 
4885     return;
4886   }
4887 
4888   if (DC->getPrimaryContext() != DC)
4889     return;
4890 
4891   // Skip contexts which don't support name lookup.
4892   if (!DC->isLookupContext())
4893     return;
4894 
4895   // If not in C++, we perform name lookup for the translation unit via the
4896   // IdentifierInfo chains, don't bother to build a visible-declarations table.
4897   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4898     return;
4899 
4900   // Serialize the contents of the mapping used for lookup. Note that,
4901   // although we have two very different code paths, the serialized
4902   // representation is the same for both cases: a declaration name,
4903   // followed by a size, followed by references to the visible
4904   // declarations that have that name.
4905   StoredDeclsMap *Map = DC->buildLookup();
4906   if (!Map || Map->empty())
4907     return;
4908 
4909   Offsets.VisibleOffset = Stream.GetCurrentBitNo();
4910   // Create the on-disk hash table in a buffer.
4911   SmallString<4096> LookupTable;
4912   SmallString<4096> ModuleLocalLookupTable;
4913   SmallString<4096> TULookupTable;
4914   GenerateNameLookupTable(Context, DC, LookupTable, ModuleLocalLookupTable,
4915                           TULookupTable);
4916 
4917   // Write the lookup table
4918   RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4919   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4920                             LookupTable);
4921   ++NumVisibleDeclContexts;
4922 
4923   if (!ModuleLocalLookupTable.empty()) {
4924     Offsets.ModuleLocalOffset = Stream.GetCurrentBitNo();
4925     assert(Offsets.ModuleLocalOffset > Offsets.VisibleOffset);
4926     // Write the lookup table
4927     RecordData::value_type ModuleLocalRecord[] = {
4928         DECL_CONTEXT_MODULE_LOCAL_VISIBLE};
4929     Stream.EmitRecordWithBlob(DeclModuleLocalVisibleLookupAbbrev,
4930                               ModuleLocalRecord, ModuleLocalLookupTable);
4931     ++NumModuleLocalDeclContexts;
4932   }
4933 
4934   if (!TULookupTable.empty()) {
4935     Offsets.TULocalOffset = Stream.GetCurrentBitNo();
4936     // Write the lookup table
4937     RecordData::value_type TULocalDeclsRecord[] = {
4938         DECL_CONTEXT_TU_LOCAL_VISIBLE};
4939     Stream.EmitRecordWithBlob(DeclTULocalLookupAbbrev, TULocalDeclsRecord,
4940                               TULookupTable);
4941     ++NumTULocalDeclContexts;
4942   }
4943 }
4944 
4945 /// Write an UPDATE_VISIBLE block for the given context.
4946 ///
4947 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4948 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4949 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4950 /// enumeration members (in C++11).
4951 void ASTWriter::WriteDeclContextVisibleUpdate(ASTContext &Context,
4952                                               const DeclContext *DC) {
4953   StoredDeclsMap *Map = DC->getLookupPtr();
4954   if (!Map || Map->empty())
4955     return;
4956 
4957   // Create the on-disk hash table in a buffer.
4958   SmallString<4096> LookupTable;
4959   SmallString<4096> ModuleLocalLookupTable;
4960   SmallString<4096> TULookupTable;
4961   GenerateNameLookupTable(Context, DC, LookupTable, ModuleLocalLookupTable,
4962                           TULookupTable);
4963 
4964   // If we're updating a namespace, select a key declaration as the key for the
4965   // update record; those are the only ones that will be checked on reload.
4966   if (isa<NamespaceDecl>(DC))
4967     DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4968 
4969   // Write the lookup table
4970   RecordData::value_type Record[] = {UPDATE_VISIBLE,
4971                                      getDeclID(cast<Decl>(DC)).getRawValue()};
4972   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4973 
4974   if (!ModuleLocalLookupTable.empty()) {
4975     // Write the module local lookup table
4976     RecordData::value_type ModuleLocalRecord[] = {
4977         UPDATE_MODULE_LOCAL_VISIBLE, getDeclID(cast<Decl>(DC)).getRawValue()};
4978     Stream.EmitRecordWithBlob(ModuleLocalUpdateVisibleAbbrev, ModuleLocalRecord,
4979                               ModuleLocalLookupTable);
4980   }
4981 
4982   if (!TULookupTable.empty()) {
4983     RecordData::value_type GMFRecord[] = {
4984         UPDATE_TU_LOCAL_VISIBLE, getDeclID(cast<Decl>(DC)).getRawValue()};
4985     Stream.EmitRecordWithBlob(TULocalUpdateVisibleAbbrev, GMFRecord,
4986                               TULookupTable);
4987   }
4988 }
4989 
4990 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4991 void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4992   RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4993   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4994 }
4995 
4996 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4997 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4998   if (!SemaRef.Context.getLangOpts().OpenCL)
4999     return;
5000 
5001   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
5002   RecordData Record;
5003   for (const auto &I:Opts.OptMap) {
5004     AddString(I.getKey(), Record);
5005     auto V = I.getValue();
5006     Record.push_back(V.Supported ? 1 : 0);
5007     Record.push_back(V.Enabled ? 1 : 0);
5008     Record.push_back(V.WithPragma ? 1 : 0);
5009     Record.push_back(V.Avail);
5010     Record.push_back(V.Core);
5011     Record.push_back(V.Opt);
5012   }
5013   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
5014 }
5015 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
5016   if (SemaRef.CUDA().ForceHostDeviceDepth > 0) {
5017     RecordData::value_type Record[] = {SemaRef.CUDA().ForceHostDeviceDepth};
5018     Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
5019   }
5020 }
5021 
5022 void ASTWriter::WriteObjCCategories() {
5023   if (ObjCClassesWithCategories.empty())
5024     return;
5025 
5026   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
5027   RecordData Categories;
5028 
5029   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
5030     unsigned Size = 0;
5031     unsigned StartIndex = Categories.size();
5032 
5033     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
5034 
5035     // Allocate space for the size.
5036     Categories.push_back(0);
5037 
5038     // Add the categories.
5039     for (ObjCInterfaceDecl::known_categories_iterator
5040            Cat = Class->known_categories_begin(),
5041            CatEnd = Class->known_categories_end();
5042          Cat != CatEnd; ++Cat, ++Size) {
5043       assert(getDeclID(*Cat).isValid() && "Bogus category");
5044       AddDeclRef(*Cat, Categories);
5045     }
5046 
5047     // Update the size.
5048     Categories[StartIndex] = Size;
5049 
5050     // Record this interface -> category map.
5051     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
5052     CategoriesMap.push_back(CatInfo);
5053   }
5054 
5055   // Sort the categories map by the definition ID, since the reader will be
5056   // performing binary searches on this information.
5057   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
5058 
5059   // Emit the categories map.
5060   using namespace llvm;
5061 
5062   auto Abbrev = std::make_shared<BitCodeAbbrev>();
5063   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
5064   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
5065   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5066   unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
5067 
5068   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
5069   Stream.EmitRecordWithBlob(AbbrevID, Record,
5070                             reinterpret_cast<char *>(CategoriesMap.data()),
5071                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
5072 
5073   // Emit the category lists.
5074   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
5075 }
5076 
5077 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
5078   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
5079 
5080   if (LPTMap.empty())
5081     return;
5082 
5083   RecordData Record;
5084   for (auto &LPTMapEntry : LPTMap) {
5085     const FunctionDecl *FD = LPTMapEntry.first;
5086     LateParsedTemplate &LPT = *LPTMapEntry.second;
5087     AddDeclRef(FD, Record);
5088     AddDeclRef(LPT.D, Record);
5089     Record.push_back(LPT.FPO.getAsOpaqueInt());
5090     Record.push_back(LPT.Toks.size());
5091 
5092     for (const auto &Tok : LPT.Toks) {
5093       AddToken(Tok, Record);
5094     }
5095   }
5096   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
5097 }
5098 
5099 /// Write the state of 'pragma clang optimize' at the end of the module.
5100 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
5101   RecordData Record;
5102   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
5103   AddSourceLocation(PragmaLoc, Record);
5104   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
5105 }
5106 
5107 /// Write the state of 'pragma ms_struct' at the end of the module.
5108 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
5109   RecordData Record;
5110   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
5111   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
5112 }
5113 
5114 /// Write the state of 'pragma pointers_to_members' at the end of the
5115 //module.
5116 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
5117   RecordData Record;
5118   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
5119   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
5120   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
5121 }
5122 
5123 /// Write the state of 'pragma align/pack' at the end of the module.
5124 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
5125   // Don't serialize pragma align/pack state for modules, since it should only
5126   // take effect on a per-submodule basis.
5127   if (WritingModule)
5128     return;
5129 
5130   RecordData Record;
5131   AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
5132   AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
5133   Record.push_back(SemaRef.AlignPackStack.Stack.size());
5134   for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
5135     AddAlignPackInfo(StackEntry.Value, Record);
5136     AddSourceLocation(StackEntry.PragmaLocation, Record);
5137     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
5138     AddString(StackEntry.StackSlotLabel, Record);
5139   }
5140   Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
5141 }
5142 
5143 /// Write the state of 'pragma float_control' at the end of the module.
5144 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
5145   // Don't serialize pragma float_control state for modules,
5146   // since it should only take effect on a per-submodule basis.
5147   if (WritingModule)
5148     return;
5149 
5150   RecordData Record;
5151   Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
5152   AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
5153   Record.push_back(SemaRef.FpPragmaStack.Stack.size());
5154   for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
5155     Record.push_back(StackEntry.Value.getAsOpaqueInt());
5156     AddSourceLocation(StackEntry.PragmaLocation, Record);
5157     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
5158     AddString(StackEntry.StackSlotLabel, Record);
5159   }
5160   Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
5161 }
5162 
5163 /// Write Sema's collected list of declarations with unverified effects.
5164 void ASTWriter::WriteDeclsWithEffectsToVerify(Sema &SemaRef) {
5165   if (SemaRef.DeclsWithEffectsToVerify.empty())
5166     return;
5167   RecordData Record;
5168   for (const auto *D : SemaRef.DeclsWithEffectsToVerify) {
5169     AddDeclRef(D, Record);
5170   }
5171   Stream.EmitRecord(DECLS_WITH_EFFECTS_TO_VERIFY, Record);
5172 }
5173 
5174 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
5175                                          ModuleFileExtensionWriter &Writer) {
5176   // Enter the extension block.
5177   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
5178 
5179   // Emit the metadata record abbreviation.
5180   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
5181   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
5182   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5183   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5184   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5185   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5186   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
5187   unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
5188 
5189   // Emit the metadata record.
5190   RecordData Record;
5191   auto Metadata = Writer.getExtension()->getExtensionMetadata();
5192   Record.push_back(EXTENSION_METADATA);
5193   Record.push_back(Metadata.MajorVersion);
5194   Record.push_back(Metadata.MinorVersion);
5195   Record.push_back(Metadata.BlockName.size());
5196   Record.push_back(Metadata.UserInfo.size());
5197   SmallString<64> Buffer;
5198   Buffer += Metadata.BlockName;
5199   Buffer += Metadata.UserInfo;
5200   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
5201 
5202   // Emit the contents of the extension block.
5203   Writer.writeExtensionContents(SemaRef, Stream);
5204 
5205   // Exit the extension block.
5206   Stream.ExitBlock();
5207 }
5208 
5209 //===----------------------------------------------------------------------===//
5210 // General Serialization Routines
5211 //===----------------------------------------------------------------------===//
5212 
5213 void ASTRecordWriter::AddAttr(const Attr *A) {
5214   auto &Record = *this;
5215   // FIXME: Clang can't handle the serialization/deserialization of
5216   // preferred_name properly now. See
5217   // https://github.com/llvm/llvm-project/issues/56490 for example.
5218   if (!A ||
5219       (isa<PreferredNameAttr>(A) && (Writer->isWritingStdCXXNamedModules() ||
5220                                      Writer->isWritingStdCXXHeaderUnit())))
5221     return Record.push_back(0);
5222 
5223   Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
5224 
5225   Record.AddIdentifierRef(A->getAttrName());
5226   Record.AddIdentifierRef(A->getScopeName());
5227   Record.AddSourceRange(A->getRange());
5228   Record.AddSourceLocation(A->getScopeLoc());
5229   Record.push_back(A->getParsedKind());
5230   Record.push_back(A->getSyntax());
5231   Record.push_back(A->getAttributeSpellingListIndexRaw());
5232   Record.push_back(A->isRegularKeywordAttribute());
5233 
5234 #include "clang/Serialization/AttrPCHWrite.inc"
5235 }
5236 
5237 /// Emit the list of attributes to the specified record.
5238 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
5239   push_back(Attrs.size());
5240   for (const auto *A : Attrs)
5241     AddAttr(A);
5242 }
5243 
5244 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
5245   AddSourceLocation(Tok.getLocation(), Record);
5246   // FIXME: Should translate token kind to a stable encoding.
5247   Record.push_back(Tok.getKind());
5248   // FIXME: Should translate token flags to a stable encoding.
5249   Record.push_back(Tok.getFlags());
5250 
5251   if (Tok.isAnnotation()) {
5252     AddSourceLocation(Tok.getAnnotationEndLoc(), Record);
5253     switch (Tok.getKind()) {
5254     case tok::annot_pragma_loop_hint: {
5255       auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
5256       AddToken(Info->PragmaName, Record);
5257       AddToken(Info->Option, Record);
5258       Record.push_back(Info->Toks.size());
5259       for (const auto &T : Info->Toks)
5260         AddToken(T, Record);
5261       break;
5262     }
5263     case tok::annot_pragma_pack: {
5264       auto *Info =
5265           static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
5266       Record.push_back(static_cast<unsigned>(Info->Action));
5267       AddString(Info->SlotLabel, Record);
5268       AddToken(Info->Alignment, Record);
5269       break;
5270     }
5271     // Some annotation tokens do not use the PtrData field.
5272     case tok::annot_pragma_openmp:
5273     case tok::annot_pragma_openmp_end:
5274     case tok::annot_pragma_unused:
5275     case tok::annot_pragma_openacc:
5276     case tok::annot_pragma_openacc_end:
5277     case tok::annot_repl_input_end:
5278       break;
5279     default:
5280       llvm_unreachable("missing serialization code for annotation token");
5281     }
5282   } else {
5283     Record.push_back(Tok.getLength());
5284     // FIXME: When reading literal tokens, reconstruct the literal pointer if it
5285     // is needed.
5286     AddIdentifierRef(Tok.getIdentifierInfo(), Record);
5287   }
5288 }
5289 
5290 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
5291   Record.push_back(Str.size());
5292   llvm::append_range(Record, Str);
5293 }
5294 
5295 void ASTWriter::AddStringBlob(StringRef Str, RecordDataImpl &Record,
5296                               SmallVectorImpl<char> &Blob) {
5297   Record.push_back(Str.size());
5298   llvm::append_range(Blob, Str);
5299 }
5300 
5301 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
5302   assert(WritingAST && "can't prepare path for output when not writing AST");
5303 
5304   // Leave special file names as they are.
5305   StringRef PathStr(Path.data(), Path.size());
5306   if (PathStr == "<built-in>" || PathStr == "<command line>")
5307     return false;
5308 
5309   bool Changed = cleanPathForOutput(PP->getFileManager(), Path);
5310 
5311   // Remove a prefix to make the path relative, if relevant.
5312   const char *PathBegin = Path.data();
5313   const char *PathPtr =
5314       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
5315   if (PathPtr != PathBegin) {
5316     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
5317     Changed = true;
5318   }
5319 
5320   return Changed;
5321 }
5322 
5323 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
5324   SmallString<128> FilePath(Path);
5325   PreparePathForOutput(FilePath);
5326   AddString(FilePath, Record);
5327 }
5328 
5329 void ASTWriter::AddPathBlob(StringRef Path, RecordDataImpl &Record,
5330                             SmallVectorImpl<char> &Blob) {
5331   SmallString<128> FilePath(Path);
5332   PreparePathForOutput(FilePath);
5333   AddStringBlob(FilePath, Record, Blob);
5334 }
5335 
5336 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
5337                                    StringRef Path) {
5338   SmallString<128> FilePath(Path);
5339   PreparePathForOutput(FilePath);
5340   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
5341 }
5342 
5343 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
5344                                 RecordDataImpl &Record) {
5345   Record.push_back(Version.getMajor());
5346   if (std::optional<unsigned> Minor = Version.getMinor())
5347     Record.push_back(*Minor + 1);
5348   else
5349     Record.push_back(0);
5350   if (std::optional<unsigned> Subminor = Version.getSubminor())
5351     Record.push_back(*Subminor + 1);
5352   else
5353     Record.push_back(0);
5354 }
5355 
5356 /// Note that the identifier II occurs at the given offset
5357 /// within the identifier table.
5358 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
5359   IdentifierID ID = IdentifierIDs[II];
5360   // Only store offsets new to this AST file. Other identifier names are looked
5361   // up earlier in the chain and thus don't need an offset.
5362   if (!isLocalIdentifierID(ID))
5363     return;
5364 
5365   // For local identifiers, the module file index must be 0.
5366 
5367   assert(ID != 0);
5368   ID -= NUM_PREDEF_IDENT_IDS;
5369   assert(ID < IdentifierOffsets.size());
5370   IdentifierOffsets[ID] = Offset;
5371 }
5372 
5373 /// Note that the selector Sel occurs at the given offset
5374 /// within the method pool/selector table.
5375 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
5376   unsigned ID = SelectorIDs[Sel];
5377   assert(ID && "Unknown selector");
5378   // Don't record offsets for selectors that are also available in a different
5379   // file.
5380   if (ID < FirstSelectorID)
5381     return;
5382   SelectorOffsets[ID - FirstSelectorID] = Offset;
5383 }
5384 
5385 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
5386                      SmallVectorImpl<char> &Buffer, ModuleCache &ModCache,
5387                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
5388                      bool IncludeTimestamps, bool BuildingImplicitModule,
5389                      bool GeneratingReducedBMI)
5390     : Stream(Stream), Buffer(Buffer), ModCache(ModCache),
5391       IncludeTimestamps(IncludeTimestamps),
5392       BuildingImplicitModule(BuildingImplicitModule),
5393       GeneratingReducedBMI(GeneratingReducedBMI) {
5394   for (const auto &Ext : Extensions) {
5395     if (auto Writer = Ext->createExtensionWriter(*this))
5396       ModuleFileExtensionWriters.push_back(std::move(Writer));
5397   }
5398 }
5399 
5400 ASTWriter::~ASTWriter() = default;
5401 
5402 const LangOptions &ASTWriter::getLangOpts() const {
5403   assert(WritingAST && "can't determine lang opts when not writing AST");
5404   return PP->getLangOpts();
5405 }
5406 
5407 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
5408   return IncludeTimestamps ? E->getModificationTime() : 0;
5409 }
5410 
5411 ASTFileSignature
5412 ASTWriter::WriteAST(llvm::PointerUnion<Sema *, Preprocessor *> Subject,
5413                     StringRef OutputFile, Module *WritingModule,
5414                     StringRef isysroot, bool ShouldCacheASTInMemory) {
5415   llvm::TimeTraceScope scope("WriteAST", OutputFile);
5416   WritingAST = true;
5417 
5418   Sema *SemaPtr = dyn_cast<Sema *>(Subject);
5419   Preprocessor &PPRef =
5420       SemaPtr ? SemaPtr->getPreprocessor() : *cast<Preprocessor *>(Subject);
5421 
5422   ASTHasCompilerErrors = PPRef.getDiagnostics().hasUncompilableErrorOccurred();
5423 
5424   // Emit the file header.
5425   Stream.Emit((unsigned)'C', 8);
5426   Stream.Emit((unsigned)'P', 8);
5427   Stream.Emit((unsigned)'C', 8);
5428   Stream.Emit((unsigned)'H', 8);
5429 
5430   WriteBlockInfoBlock();
5431 
5432   PP = &PPRef;
5433   this->WritingModule = WritingModule;
5434   ASTFileSignature Signature = WriteASTCore(SemaPtr, isysroot, WritingModule);
5435   PP = nullptr;
5436   this->WritingModule = nullptr;
5437   this->BaseDirectory.clear();
5438 
5439   WritingAST = false;
5440 
5441   if (WritingModule && PPRef.getHeaderSearchInfo()
5442                            .getHeaderSearchOpts()
5443                            .ModulesValidateOncePerBuildSession)
5444     ModCache.updateModuleTimestamp(OutputFile);
5445 
5446   if (ShouldCacheASTInMemory) {
5447     // Construct MemoryBuffer and update buffer manager.
5448     ModCache.getInMemoryModuleCache().addBuiltPCM(
5449         OutputFile, llvm::MemoryBuffer::getMemBufferCopy(
5450                         StringRef(Buffer.begin(), Buffer.size())));
5451   }
5452   return Signature;
5453 }
5454 
5455 template<typename Vector>
5456 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec) {
5457   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5458        I != E; ++I) {
5459     Writer.GetDeclRef(*I);
5460   }
5461 }
5462 
5463 template <typename Vector>
5464 static void AddLazyVectorEmiitedDecls(ASTWriter &Writer, Vector &Vec,
5465                                       ASTWriter::RecordData &Record) {
5466   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5467        I != E; ++I) {
5468     Writer.AddEmittedDeclRef(*I, Record);
5469   }
5470 }
5471 
5472 void ASTWriter::computeNonAffectingInputFiles() {
5473   SourceManager &SrcMgr = PP->getSourceManager();
5474   unsigned N = SrcMgr.local_sloc_entry_size();
5475 
5476   IsSLocAffecting.resize(N, true);
5477   IsSLocFileEntryAffecting.resize(N, true);
5478 
5479   if (!WritingModule)
5480     return;
5481 
5482   auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
5483 
5484   unsigned FileIDAdjustment = 0;
5485   unsigned OffsetAdjustment = 0;
5486 
5487   NonAffectingFileIDAdjustments.reserve(N);
5488   NonAffectingOffsetAdjustments.reserve(N);
5489 
5490   NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
5491   NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
5492 
5493   for (unsigned I = 1; I != N; ++I) {
5494     const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
5495     FileID FID = FileID::get(I);
5496     assert(&SrcMgr.getSLocEntry(FID) == SLoc);
5497 
5498     if (!SLoc->isFile())
5499       continue;
5500     const SrcMgr::FileInfo &File = SLoc->getFile();
5501     const SrcMgr::ContentCache *Cache = &File.getContentCache();
5502     if (!Cache->OrigEntry)
5503       continue;
5504 
5505     // Don't prune anything other than module maps.
5506     if (!isModuleMap(File.getFileCharacteristic()))
5507       continue;
5508 
5509     // Don't prune module maps if all are guaranteed to be affecting.
5510     if (!AffectingModuleMaps)
5511       continue;
5512 
5513     // Don't prune module maps that are affecting.
5514     if (AffectingModuleMaps->DefinitionFileIDs.contains(FID))
5515       continue;
5516 
5517     IsSLocAffecting[I] = false;
5518     IsSLocFileEntryAffecting[I] =
5519         AffectingModuleMaps->DefinitionFiles.contains(*Cache->OrigEntry);
5520 
5521     FileIDAdjustment += 1;
5522     // Even empty files take up one element in the offset table.
5523     OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
5524 
5525     // If the previous file was non-affecting as well, just extend its entry
5526     // with our information.
5527     if (!NonAffectingFileIDs.empty() &&
5528         NonAffectingFileIDs.back().ID == FID.ID - 1) {
5529       NonAffectingFileIDs.back() = FID;
5530       NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
5531       NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
5532       NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
5533       continue;
5534     }
5535 
5536     NonAffectingFileIDs.push_back(FID);
5537     NonAffectingRanges.emplace_back(SrcMgr.getLocForStartOfFile(FID),
5538                                     SrcMgr.getLocForEndOfFile(FID));
5539     NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
5540     NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
5541   }
5542 
5543   if (!PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesIncludeVFSUsage)
5544     return;
5545 
5546   FileManager &FileMgr = PP->getFileManager();
5547   FileMgr.trackVFSUsage(true);
5548   // Lookup the paths in the VFS to trigger `-ivfsoverlay` usage tracking.
5549   for (StringRef Path :
5550        PP->getHeaderSearchInfo().getHeaderSearchOpts().VFSOverlayFiles)
5551     FileMgr.getVirtualFileSystem().exists(Path);
5552   for (unsigned I = 1; I != N; ++I) {
5553     if (IsSLocAffecting[I]) {
5554       const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
5555       if (!SLoc->isFile())
5556         continue;
5557       const SrcMgr::FileInfo &File = SLoc->getFile();
5558       const SrcMgr::ContentCache *Cache = &File.getContentCache();
5559       if (!Cache->OrigEntry)
5560         continue;
5561       FileMgr.getVirtualFileSystem().exists(
5562           Cache->OrigEntry->getNameAsRequested());
5563     }
5564   }
5565   FileMgr.trackVFSUsage(false);
5566 }
5567 
5568 void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) {
5569   ASTContext &Context = SemaRef.Context;
5570 
5571   bool isModule = WritingModule != nullptr;
5572 
5573   // Set up predefined declaration IDs.
5574   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
5575     if (D) {
5576       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
5577       DeclIDs[D] = ID;
5578       PredefinedDecls.insert(D);
5579     }
5580   };
5581   RegisterPredefDecl(Context.getTranslationUnitDecl(),
5582                      PREDEF_DECL_TRANSLATION_UNIT_ID);
5583   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
5584   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
5585   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
5586   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
5587                      PREDEF_DECL_OBJC_PROTOCOL_ID);
5588   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
5589   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
5590   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
5591                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
5592   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
5593   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
5594   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
5595                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
5596   RegisterPredefDecl(Context.MSGuidTagDecl,
5597                      PREDEF_DECL_BUILTIN_MS_GUID_ID);
5598   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
5599   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
5600                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
5601   RegisterPredefDecl(Context.CFConstantStringTagDecl,
5602                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
5603 #define BuiltinTemplate(BTName)                                                \
5604   RegisterPredefDecl(Context.Decl##BTName, PREDEF_DECL##BTName##_ID);
5605 #include "clang/Basic/BuiltinTemplates.inc"
5606 
5607   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5608 
5609   // Force all top level declarations to be emitted.
5610   //
5611   // We start emitting top level declarations from the module purview to
5612   // implement the eliding unreachable declaration feature.
5613   for (const auto *D : TU->noload_decls()) {
5614     if (D->isFromASTFile())
5615       continue;
5616 
5617     if (GeneratingReducedBMI) {
5618       if (D->isFromExplicitGlobalModule())
5619         continue;
5620 
5621       // Don't force emitting static entities.
5622       //
5623       // Technically, all static entities shouldn't be in reduced BMI. The
5624       // language also specifies that the program exposes TU-local entities
5625       // is ill-formed. However, in practice, there are a lot of projects
5626       // uses `static inline` in the headers. So we can't get rid of all
5627       // static entities in reduced BMI now.
5628       if (IsInternalDeclFromFileContext(D))
5629         continue;
5630     }
5631 
5632     // If we're writing C++ named modules, don't emit declarations which are
5633     // not from modules by default. They may be built in declarations (be
5634     // handled above) or implcit declarations (see the implementation of
5635     // `Sema::Initialize()` for example).
5636     if (isWritingStdCXXNamedModules() && !D->getOwningModule() &&
5637         D->isImplicit())
5638       continue;
5639 
5640     GetDeclRef(D);
5641   }
5642 
5643   if (GeneratingReducedBMI)
5644     return;
5645 
5646   // Writing all of the tentative definitions in this file, in
5647   // TentativeDefinitions order.  Generally, this record will be empty for
5648   // headers.
5649   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions);
5650 
5651   // Writing all of the file scoped decls in this file.
5652   if (!isModule)
5653     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls);
5654 
5655   // Writing all of the delegating constructors we still need
5656   // to resolve.
5657   if (!isModule)
5658     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls);
5659 
5660   // Writing all of the ext_vector declarations.
5661   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls);
5662 
5663   // Writing all of the VTable uses information.
5664   if (!SemaRef.VTableUses.empty())
5665     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I)
5666       GetDeclRef(SemaRef.VTableUses[I].first);
5667 
5668   // Writing all of the UnusedLocalTypedefNameCandidates.
5669   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
5670     GetDeclRef(TD);
5671 
5672   // Writing all of pending implicit instantiations.
5673   for (const auto &I : SemaRef.PendingInstantiations)
5674     GetDeclRef(I.first);
5675   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
5676          "There are local ones at end of translation unit!");
5677 
5678   // Writing some declaration references.
5679   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5680     GetDeclRef(SemaRef.getStdNamespace());
5681     GetDeclRef(SemaRef.getStdBadAlloc());
5682     GetDeclRef(SemaRef.getStdAlignValT());
5683   }
5684 
5685   if (Context.getcudaConfigureCallDecl())
5686     GetDeclRef(Context.getcudaConfigureCallDecl());
5687 
5688   // Writing all of the known namespaces.
5689   for (const auto &I : SemaRef.KnownNamespaces)
5690     if (!I.second)
5691       GetDeclRef(I.first);
5692 
5693   // Writing all used, undefined objects that require definitions.
5694   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
5695   SemaRef.getUndefinedButUsed(Undefined);
5696   for (const auto &I : Undefined)
5697     GetDeclRef(I.first);
5698 
5699   // Writing all delete-expressions that we would like to
5700   // analyze later in AST.
5701   if (!isModule)
5702     for (const auto &DeleteExprsInfo :
5703          SemaRef.getMismatchingDeleteExpressions())
5704       GetDeclRef(DeleteExprsInfo.first);
5705 
5706   // Make sure visible decls, added to DeclContexts previously loaded from
5707   // an AST file, are registered for serialization. Likewise for template
5708   // specializations added to imported templates.
5709   for (const auto *I : DeclsToEmitEvenIfUnreferenced)
5710     GetDeclRef(I);
5711   DeclsToEmitEvenIfUnreferenced.clear();
5712 
5713   // Make sure all decls associated with an identifier are registered for
5714   // serialization, if we're storing decls with identifiers.
5715   if (!WritingModule || !getLangOpts().CPlusPlus) {
5716     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
5717     for (const auto &ID : SemaRef.PP.getIdentifierTable()) {
5718       const IdentifierInfo *II = ID.second;
5719       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization() ||
5720           II->hasFETokenInfoChangedSinceDeserialization())
5721         IIs.push_back(II);
5722     }
5723     // Sort the identifiers to visit based on their name.
5724     llvm::sort(IIs, llvm::deref<std::less<>>());
5725     const LangOptions &LangOpts = getLangOpts();
5726     for (const IdentifierInfo *II : IIs)
5727       for (NamedDecl *D : SemaRef.IdResolver.decls(II))
5728         GetDeclRef(getDeclForLocalLookup(LangOpts, D));
5729   }
5730 
5731   // Write all of the DeclsToCheckForDeferredDiags.
5732   for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5733     GetDeclRef(D);
5734 
5735   // Write all classes that need to emit the vtable definitions if required.
5736   if (isWritingStdCXXNamedModules())
5737     for (CXXRecordDecl *RD : PendingEmittingVTables)
5738       GetDeclRef(RD);
5739   else
5740     PendingEmittingVTables.clear();
5741 }
5742 
5743 void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
5744   ASTContext &Context = SemaRef.Context;
5745 
5746   bool isModule = WritingModule != nullptr;
5747 
5748   // Write the record containing external, unnamed definitions.
5749   if (!EagerlyDeserializedDecls.empty())
5750     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5751 
5752   if (!ModularCodegenDecls.empty())
5753     Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5754 
5755   // Write the record containing tentative definitions.
5756   RecordData TentativeDefinitions;
5757   AddLazyVectorEmiitedDecls(*this, SemaRef.TentativeDefinitions,
5758                             TentativeDefinitions);
5759   if (!TentativeDefinitions.empty())
5760     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5761 
5762   // Write the record containing unused file scoped decls.
5763   RecordData UnusedFileScopedDecls;
5764   if (!isModule)
5765     AddLazyVectorEmiitedDecls(*this, SemaRef.UnusedFileScopedDecls,
5766                               UnusedFileScopedDecls);
5767   if (!UnusedFileScopedDecls.empty())
5768     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5769 
5770   // Write the record containing ext_vector type names.
5771   RecordData ExtVectorDecls;
5772   AddLazyVectorEmiitedDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
5773   if (!ExtVectorDecls.empty())
5774     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5775 
5776   // Write the record containing VTable uses information.
5777   RecordData VTableUses;
5778   if (!SemaRef.VTableUses.empty()) {
5779     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
5780       CXXRecordDecl *D = SemaRef.VTableUses[I].first;
5781       if (!wasDeclEmitted(D))
5782         continue;
5783 
5784       AddDeclRef(D, VTableUses);
5785       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
5786       VTableUses.push_back(SemaRef.VTablesUsed[D]);
5787     }
5788     Stream.EmitRecord(VTABLE_USES, VTableUses);
5789   }
5790 
5791   // Write the record containing potentially unused local typedefs.
5792   RecordData UnusedLocalTypedefNameCandidates;
5793   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
5794     AddEmittedDeclRef(TD, UnusedLocalTypedefNameCandidates);
5795   if (!UnusedLocalTypedefNameCandidates.empty())
5796     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5797                       UnusedLocalTypedefNameCandidates);
5798 
5799   // Write the record containing pending implicit instantiations.
5800   RecordData PendingInstantiations;
5801   for (const auto &I : SemaRef.PendingInstantiations) {
5802     if (!wasDeclEmitted(I.first))
5803       continue;
5804 
5805     AddDeclRef(I.first, PendingInstantiations);
5806     AddSourceLocation(I.second, PendingInstantiations);
5807   }
5808   if (!PendingInstantiations.empty())
5809     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5810 
5811   // Write the record containing declaration references of Sema.
5812   RecordData SemaDeclRefs;
5813   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5814     auto AddEmittedDeclRefOrZero = [this, &SemaDeclRefs](Decl *D) {
5815       if (!D || !wasDeclEmitted(D))
5816         SemaDeclRefs.push_back(0);
5817       else
5818         AddDeclRef(D, SemaDeclRefs);
5819     };
5820 
5821     AddEmittedDeclRefOrZero(SemaRef.getStdNamespace());
5822     AddEmittedDeclRefOrZero(SemaRef.getStdBadAlloc());
5823     AddEmittedDeclRefOrZero(SemaRef.getStdAlignValT());
5824   }
5825   if (!SemaDeclRefs.empty())
5826     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5827 
5828   // Write the record containing decls to be checked for deferred diags.
5829   RecordData DeclsToCheckForDeferredDiags;
5830   for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5831     if (wasDeclEmitted(D))
5832       AddDeclRef(D, DeclsToCheckForDeferredDiags);
5833   if (!DeclsToCheckForDeferredDiags.empty())
5834     Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
5835         DeclsToCheckForDeferredDiags);
5836 
5837   // Write the record containing CUDA-specific declaration references.
5838   RecordData CUDASpecialDeclRefs;
5839   if (auto *CudaCallDecl = Context.getcudaConfigureCallDecl();
5840       CudaCallDecl && wasDeclEmitted(CudaCallDecl)) {
5841     AddDeclRef(CudaCallDecl, CUDASpecialDeclRefs);
5842     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5843   }
5844 
5845   // Write the delegating constructors.
5846   RecordData DelegatingCtorDecls;
5847   if (!isModule)
5848     AddLazyVectorEmiitedDecls(*this, SemaRef.DelegatingCtorDecls,
5849                               DelegatingCtorDecls);
5850   if (!DelegatingCtorDecls.empty())
5851     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5852 
5853   // Write the known namespaces.
5854   RecordData KnownNamespaces;
5855   for (const auto &I : SemaRef.KnownNamespaces) {
5856     if (!I.second && wasDeclEmitted(I.first))
5857       AddDeclRef(I.first, KnownNamespaces);
5858   }
5859   if (!KnownNamespaces.empty())
5860     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5861 
5862   // Write the undefined internal functions and variables, and inline functions.
5863   RecordData UndefinedButUsed;
5864   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
5865   SemaRef.getUndefinedButUsed(Undefined);
5866   for (const auto &I : Undefined) {
5867     if (!wasDeclEmitted(I.first))
5868       continue;
5869 
5870     AddDeclRef(I.first, UndefinedButUsed);
5871     AddSourceLocation(I.second, UndefinedButUsed);
5872   }
5873   if (!UndefinedButUsed.empty())
5874     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5875 
5876   // Write all delete-expressions that we would like to
5877   // analyze later in AST.
5878   RecordData DeleteExprsToAnalyze;
5879   if (!isModule) {
5880     for (const auto &DeleteExprsInfo :
5881          SemaRef.getMismatchingDeleteExpressions()) {
5882       if (!wasDeclEmitted(DeleteExprsInfo.first))
5883         continue;
5884 
5885       AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
5886       DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
5887       for (const auto &DeleteLoc : DeleteExprsInfo.second) {
5888         AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
5889         DeleteExprsToAnalyze.push_back(DeleteLoc.second);
5890       }
5891     }
5892   }
5893   if (!DeleteExprsToAnalyze.empty())
5894     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5895 
5896   RecordData VTablesToEmit;
5897   for (CXXRecordDecl *RD : PendingEmittingVTables) {
5898     if (!wasDeclEmitted(RD))
5899       continue;
5900 
5901     AddDeclRef(RD, VTablesToEmit);
5902   }
5903 
5904   if (!VTablesToEmit.empty())
5905     Stream.EmitRecord(VTABLES_TO_EMIT, VTablesToEmit);
5906 }
5907 
5908 ASTFileSignature ASTWriter::WriteASTCore(Sema *SemaPtr, StringRef isysroot,
5909                                          Module *WritingModule) {
5910   using namespace llvm;
5911 
5912   bool isModule = WritingModule != nullptr;
5913 
5914   // Make sure that the AST reader knows to finalize itself.
5915   if (Chain)
5916     Chain->finalizeForWriting();
5917 
5918   // This needs to be done very early, since everything that writes
5919   // SourceLocations or FileIDs depends on it.
5920   computeNonAffectingInputFiles();
5921 
5922   writeUnhashedControlBlock(*PP);
5923 
5924   // Don't reuse type ID and Identifier ID from readers for C++ standard named
5925   // modules since we want to support no-transitive-change model for named
5926   // modules. The theory for no-transitive-change model is,
5927   // for a user of a named module, the user can only access the indirectly
5928   // imported decls via the directly imported module. So that it is possible to
5929   // control what matters to the users when writing the module. It would be
5930   // problematic if the users can reuse the type IDs and identifier IDs from
5931   // indirectly imported modules arbitrarily. So we choose to clear these ID
5932   // here.
5933   if (isWritingStdCXXNamedModules()) {
5934     TypeIdxs.clear();
5935     IdentifierIDs.clear();
5936   }
5937 
5938   // Look for any identifiers that were named while processing the
5939   // headers, but are otherwise not needed. We add these to the hash
5940   // table to enable checking of the predefines buffer in the case
5941   // where the user adds new macro definitions when building the AST
5942   // file.
5943   //
5944   // We do this before emitting any Decl and Types to make sure the
5945   // Identifier ID is stable.
5946   SmallVector<const IdentifierInfo *, 128> IIs;
5947   for (const auto &ID : PP->getIdentifierTable())
5948     if (IsInterestingNonMacroIdentifier(ID.second, *this))
5949       IIs.push_back(ID.second);
5950   // Sort the identifiers lexicographically before getting the references so
5951   // that their order is stable.
5952   llvm::sort(IIs, llvm::deref<std::less<>>());
5953   for (const IdentifierInfo *II : IIs)
5954     getIdentifierRef(II);
5955 
5956   // Write the set of weak, undeclared identifiers. We always write the
5957   // entire table, since later PCH files in a PCH chain are only interested in
5958   // the results at the end of the chain.
5959   RecordData WeakUndeclaredIdentifiers;
5960   if (SemaPtr) {
5961     for (const auto &WeakUndeclaredIdentifierList :
5962          SemaPtr->WeakUndeclaredIdentifiers) {
5963       const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
5964       for (const auto &WI : WeakUndeclaredIdentifierList.second) {
5965         AddIdentifierRef(II, WeakUndeclaredIdentifiers);
5966         AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
5967         AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
5968       }
5969     }
5970   }
5971 
5972   // Form the record of special types.
5973   RecordData SpecialTypes;
5974   if (SemaPtr) {
5975     ASTContext &Context = SemaPtr->Context;
5976     AddTypeRef(Context, Context.getRawCFConstantStringType(), SpecialTypes);
5977     AddTypeRef(Context, Context.getFILEType(), SpecialTypes);
5978     AddTypeRef(Context, Context.getjmp_bufType(), SpecialTypes);
5979     AddTypeRef(Context, Context.getsigjmp_bufType(), SpecialTypes);
5980     AddTypeRef(Context, Context.ObjCIdRedefinitionType, SpecialTypes);
5981     AddTypeRef(Context, Context.ObjCClassRedefinitionType, SpecialTypes);
5982     AddTypeRef(Context, Context.ObjCSelRedefinitionType, SpecialTypes);
5983     AddTypeRef(Context, Context.getucontext_tType(), SpecialTypes);
5984   }
5985 
5986   if (SemaPtr)
5987     PrepareWritingSpecialDecls(*SemaPtr);
5988 
5989   // Write the control block
5990   WriteControlBlock(*PP, isysroot);
5991 
5992   // Write the remaining AST contents.
5993   Stream.FlushToWord();
5994   ASTBlockRange.first = Stream.GetCurrentBitNo() >> 3;
5995   Stream.EnterSubblock(AST_BLOCK_ID, 5);
5996   ASTBlockStartOffset = Stream.GetCurrentBitNo();
5997 
5998   // This is so that older clang versions, before the introduction
5999   // of the control block, can read and reject the newer PCH format.
6000   {
6001     RecordData Record = {VERSION_MAJOR};
6002     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
6003   }
6004 
6005   // For method pool in the module, if it contains an entry for a selector,
6006   // the entry should be complete, containing everything introduced by that
6007   // module and all modules it imports. It's possible that the entry is out of
6008   // date, so we need to pull in the new content here.
6009 
6010   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
6011   // safe, we copy all selectors out.
6012   if (SemaPtr) {
6013     llvm::SmallVector<Selector, 256> AllSelectors;
6014     for (auto &SelectorAndID : SelectorIDs)
6015       AllSelectors.push_back(SelectorAndID.first);
6016     for (auto &Selector : AllSelectors)
6017       SemaPtr->ObjC().updateOutOfDateSelector(Selector);
6018   }
6019 
6020   if (Chain) {
6021     // Write the mapping information describing our module dependencies and how
6022     // each of those modules were mapped into our own offset/ID space, so that
6023     // the reader can build the appropriate mapping to its own offset/ID space.
6024     // The map consists solely of a blob with the following format:
6025     // *(module-kind:i8
6026     //   module-name-len:i16 module-name:len*i8
6027     //   source-location-offset:i32
6028     //   identifier-id:i32
6029     //   preprocessed-entity-id:i32
6030     //   macro-definition-id:i32
6031     //   submodule-id:i32
6032     //   selector-id:i32
6033     //   declaration-id:i32
6034     //   c++-base-specifiers-id:i32
6035     //   type-id:i32)
6036     //
6037     // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
6038     // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
6039     // module name. Otherwise, it is the module file name.
6040     auto Abbrev = std::make_shared<BitCodeAbbrev>();
6041     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
6042     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
6043     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
6044     SmallString<2048> Buffer;
6045     {
6046       llvm::raw_svector_ostream Out(Buffer);
6047       for (ModuleFile &M : Chain->ModuleMgr) {
6048         using namespace llvm::support;
6049 
6050         endian::Writer LE(Out, llvm::endianness::little);
6051         LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
6052         StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
6053         LE.write<uint16_t>(Name.size());
6054         Out.write(Name.data(), Name.size());
6055 
6056         // Note: if a base ID was uint max, it would not be possible to load
6057         // another module after it or have more than one entity inside it.
6058         uint32_t None = std::numeric_limits<uint32_t>::max();
6059 
6060         auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
6061           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
6062           if (ShouldWrite)
6063             LE.write<uint32_t>(BaseID);
6064           else
6065             LE.write<uint32_t>(None);
6066         };
6067 
6068         // These values should be unique within a chain, since they will be read
6069         // as keys into ContinuousRangeMaps.
6070         writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
6071         writeBaseIDOrNone(M.BasePreprocessedEntityID,
6072                           M.NumPreprocessedEntities);
6073         writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
6074         writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
6075       }
6076     }
6077     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
6078     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
6079                               Buffer.data(), Buffer.size());
6080   }
6081 
6082   if (SemaPtr)
6083     WriteDeclAndTypes(SemaPtr->Context);
6084 
6085   WriteFileDeclIDsMap();
6086   WriteSourceManagerBlock(PP->getSourceManager());
6087   if (SemaPtr)
6088     WriteComments(SemaPtr->Context);
6089   WritePreprocessor(*PP, isModule);
6090   WriteHeaderSearch(PP->getHeaderSearchInfo());
6091   if (SemaPtr) {
6092     WriteSelectors(*SemaPtr);
6093     WriteReferencedSelectorsPool(*SemaPtr);
6094     WriteLateParsedTemplates(*SemaPtr);
6095   }
6096   WriteIdentifierTable(*PP, SemaPtr ? &SemaPtr->IdResolver : nullptr, isModule);
6097   if (SemaPtr) {
6098     WriteFPPragmaOptions(SemaPtr->CurFPFeatureOverrides());
6099     WriteOpenCLExtensions(*SemaPtr);
6100     WriteCUDAPragmas(*SemaPtr);
6101   }
6102 
6103   // If we're emitting a module, write out the submodule information.
6104   if (WritingModule)
6105     WriteSubmodules(WritingModule, SemaPtr ? &SemaPtr->Context : nullptr);
6106 
6107   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
6108 
6109   if (SemaPtr)
6110     WriteSpecialDeclRecords(*SemaPtr);
6111 
6112   // Write the record containing weak undeclared identifiers.
6113   if (!WeakUndeclaredIdentifiers.empty())
6114     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
6115                       WeakUndeclaredIdentifiers);
6116 
6117   if (!WritingModule) {
6118     // Write the submodules that were imported, if any.
6119     struct ModuleInfo {
6120       uint64_t ID;
6121       Module *M;
6122       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
6123     };
6124     llvm::SmallVector<ModuleInfo, 64> Imports;
6125     if (SemaPtr) {
6126       for (const auto *I : SemaPtr->Context.local_imports()) {
6127         assert(SubmoduleIDs.contains(I->getImportedModule()));
6128         Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
6129                                      I->getImportedModule()));
6130       }
6131     }
6132 
6133     if (!Imports.empty()) {
6134       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
6135         return A.ID < B.ID;
6136       };
6137       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
6138         return A.ID == B.ID;
6139       };
6140 
6141       // Sort and deduplicate module IDs.
6142       llvm::sort(Imports, Cmp);
6143       Imports.erase(llvm::unique(Imports, Eq), Imports.end());
6144 
6145       RecordData ImportedModules;
6146       for (const auto &Import : Imports) {
6147         ImportedModules.push_back(Import.ID);
6148         // FIXME: If the module has macros imported then later has declarations
6149         // imported, this location won't be the right one as a location for the
6150         // declaration imports.
6151         AddSourceLocation(PP->getModuleImportLoc(Import.M), ImportedModules);
6152       }
6153 
6154       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
6155     }
6156   }
6157 
6158   WriteObjCCategories();
6159   if (SemaPtr) {
6160     if (!WritingModule) {
6161       WriteOptimizePragmaOptions(*SemaPtr);
6162       WriteMSStructPragmaOptions(*SemaPtr);
6163       WriteMSPointersToMembersPragmaOptions(*SemaPtr);
6164     }
6165     WritePackPragmaOptions(*SemaPtr);
6166     WriteFloatControlPragmaOptions(*SemaPtr);
6167     WriteDeclsWithEffectsToVerify(*SemaPtr);
6168   }
6169 
6170   // Some simple statistics
6171   RecordData::value_type Record[] = {NumStatements,
6172                                      NumMacros,
6173                                      NumLexicalDeclContexts,
6174                                      NumVisibleDeclContexts,
6175                                      NumModuleLocalDeclContexts,
6176                                      NumTULocalDeclContexts};
6177   Stream.EmitRecord(STATISTICS, Record);
6178   Stream.ExitBlock();
6179   Stream.FlushToWord();
6180   ASTBlockRange.second = Stream.GetCurrentBitNo() >> 3;
6181 
6182   // Write the module file extension blocks.
6183   if (SemaPtr)
6184     for (const auto &ExtWriter : ModuleFileExtensionWriters)
6185       WriteModuleFileExtension(*SemaPtr, *ExtWriter);
6186 
6187   return backpatchSignature();
6188 }
6189 
6190 void ASTWriter::EnteringModulePurview() {
6191   // In C++20 named modules, all entities before entering the module purview
6192   // lives in the GMF.
6193   if (GeneratingReducedBMI)
6194     DeclUpdatesFromGMF.swap(DeclUpdates);
6195 }
6196 
6197 // Add update records for all mangling numbers and static local numbers.
6198 // These aren't really update records, but this is a convenient way of
6199 // tagging this rare extra data onto the declarations.
6200 void ASTWriter::AddedManglingNumber(const Decl *D, unsigned Number) {
6201   if (D->isFromASTFile())
6202     return;
6203 
6204   DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::ManglingNumber, Number));
6205 }
6206 void ASTWriter::AddedStaticLocalNumbers(const Decl *D, unsigned Number) {
6207   if (D->isFromASTFile())
6208     return;
6209 
6210   DeclUpdates[D].push_back(
6211       DeclUpdate(DeclUpdateKind::StaticLocalNumber, Number));
6212 }
6213 
6214 void ASTWriter::AddedAnonymousNamespace(const TranslationUnitDecl *TU,
6215                                         NamespaceDecl *AnonNamespace) {
6216   // If the translation unit has an anonymous namespace, and we don't already
6217   // have an update block for it, write it as an update block.
6218   // FIXME: Why do we not do this if there's already an update block?
6219   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
6220     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
6221     if (Record.empty())
6222       Record.push_back(
6223           DeclUpdate(DeclUpdateKind::CXXAddedAnonymousNamespace, NS));
6224   }
6225 }
6226 
6227 void ASTWriter::WriteDeclAndTypes(ASTContext &Context) {
6228   // Keep writing types, declarations, and declaration update records
6229   // until we've emitted all of them.
6230   RecordData DeclUpdatesOffsetsRecord;
6231   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/ 6);
6232   DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
6233   WriteTypeAbbrevs();
6234   WriteDeclAbbrevs();
6235   do {
6236     WriteDeclUpdatesBlocks(Context, DeclUpdatesOffsetsRecord);
6237     while (!DeclTypesToEmit.empty()) {
6238       DeclOrType DOT = DeclTypesToEmit.front();
6239       DeclTypesToEmit.pop();
6240       if (DOT.isType())
6241         WriteType(Context, DOT.getType());
6242       else
6243         WriteDecl(Context, DOT.getDecl());
6244     }
6245   } while (!DeclUpdates.empty());
6246 
6247   DoneWritingDeclsAndTypes = true;
6248 
6249   // DelayedNamespace is only meaningful in reduced BMI.
6250   // See the comments of DelayedNamespace for details.
6251   assert(DelayedNamespace.empty() || GeneratingReducedBMI);
6252   RecordData DelayedNamespaceRecord;
6253   for (NamespaceDecl *NS : DelayedNamespace) {
6254     LookupBlockOffsets Offsets;
6255 
6256     Offsets.LexicalOffset = WriteDeclContextLexicalBlock(Context, NS);
6257     WriteDeclContextVisibleBlock(Context, NS, Offsets);
6258 
6259     if (Offsets.LexicalOffset)
6260       Offsets.LexicalOffset -= DeclTypesBlockStartOffset;
6261 
6262     // Write the offset relative to current block.
6263     if (Offsets.VisibleOffset)
6264       Offsets.VisibleOffset -= DeclTypesBlockStartOffset;
6265 
6266     if (Offsets.ModuleLocalOffset)
6267       Offsets.ModuleLocalOffset -= DeclTypesBlockStartOffset;
6268 
6269     if (Offsets.TULocalOffset)
6270       Offsets.TULocalOffset -= DeclTypesBlockStartOffset;
6271 
6272     AddDeclRef(NS, DelayedNamespaceRecord);
6273     AddLookupOffsets(Offsets, DelayedNamespaceRecord);
6274   }
6275 
6276   // The process of writing lexical and visible block for delayed namespace
6277   // shouldn't introduce any new decls, types or update to emit.
6278   assert(DeclTypesToEmit.empty());
6279   assert(DeclUpdates.empty());
6280 
6281   Stream.ExitBlock();
6282 
6283   // These things can only be done once we've written out decls and types.
6284   WriteTypeDeclOffsets();
6285   if (!DeclUpdatesOffsetsRecord.empty())
6286     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
6287 
6288   if (!DelayedNamespaceRecord.empty())
6289     Stream.EmitRecord(DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD,
6290                       DelayedNamespaceRecord);
6291 
6292   if (!RelatedDeclsMap.empty()) {
6293     // TODO: on disk hash table for related decls mapping might be more
6294     // efficent becuase it allows lazy deserialization.
6295     RecordData RelatedDeclsMapRecord;
6296     for (const auto &Pair : RelatedDeclsMap) {
6297       RelatedDeclsMapRecord.push_back(Pair.first.getRawValue());
6298       RelatedDeclsMapRecord.push_back(Pair.second.size());
6299       for (const auto &Lambda : Pair.second)
6300         RelatedDeclsMapRecord.push_back(Lambda.getRawValue());
6301     }
6302 
6303     auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6304     Abv->Add(llvm::BitCodeAbbrevOp(RELATED_DECLS_MAP));
6305     Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Array));
6306     Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6307     unsigned FunctionToLambdaMapAbbrev = Stream.EmitAbbrev(std::move(Abv));
6308     Stream.EmitRecord(RELATED_DECLS_MAP, RelatedDeclsMapRecord,
6309                       FunctionToLambdaMapAbbrev);
6310   }
6311 
6312   if (!SpecializationsUpdates.empty()) {
6313     WriteSpecializationsUpdates(/*IsPartial=*/false);
6314     SpecializationsUpdates.clear();
6315   }
6316 
6317   if (!PartialSpecializationsUpdates.empty()) {
6318     WriteSpecializationsUpdates(/*IsPartial=*/true);
6319     PartialSpecializationsUpdates.clear();
6320   }
6321 
6322   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6323   // Create a lexical update block containing all of the declarations in the
6324   // translation unit that do not come from other AST files.
6325   SmallVector<DeclID, 128> NewGlobalKindDeclPairs;
6326   for (const auto *D : TU->noload_decls()) {
6327     if (D->isFromASTFile())
6328       continue;
6329 
6330     // In reduced BMI, skip unreached declarations.
6331     if (!wasDeclEmitted(D))
6332       continue;
6333 
6334     NewGlobalKindDeclPairs.push_back(D->getKind());
6335     NewGlobalKindDeclPairs.push_back(GetDeclRef(D).getRawValue());
6336   }
6337 
6338   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6339   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
6340   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6341   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
6342 
6343   RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
6344   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
6345                             bytes(NewGlobalKindDeclPairs));
6346 
6347   Abv = std::make_shared<llvm::BitCodeAbbrev>();
6348   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
6349   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6350   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6351   UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6352 
6353   Abv = std::make_shared<llvm::BitCodeAbbrev>();
6354   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_MODULE_LOCAL_VISIBLE));
6355   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6356   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6357   ModuleLocalUpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6358 
6359   Abv = std::make_shared<llvm::BitCodeAbbrev>();
6360   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_TU_LOCAL_VISIBLE));
6361   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6362   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6363   TULocalUpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
6364 
6365   // And a visible updates block for the translation unit.
6366   WriteDeclContextVisibleUpdate(Context, TU);
6367 
6368   // If we have any extern "C" names, write out a visible update for them.
6369   if (Context.ExternCContext)
6370     WriteDeclContextVisibleUpdate(Context, Context.ExternCContext);
6371 
6372   // Write the visible updates to DeclContexts.
6373   for (auto *DC : UpdatedDeclContexts)
6374     WriteDeclContextVisibleUpdate(Context, DC);
6375 }
6376 
6377 void ASTWriter::WriteSpecializationsUpdates(bool IsPartial) {
6378   auto RecordType = IsPartial ? CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
6379                               : CXX_ADDED_TEMPLATE_SPECIALIZATION;
6380 
6381   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6382   Abv->Add(llvm::BitCodeAbbrevOp(RecordType));
6383   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6384   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6385   auto UpdateSpecializationAbbrev = Stream.EmitAbbrev(std::move(Abv));
6386 
6387   auto &SpecUpdates =
6388       IsPartial ? PartialSpecializationsUpdates : SpecializationsUpdates;
6389   for (auto &SpecializationUpdate : SpecUpdates) {
6390     const NamedDecl *D = SpecializationUpdate.first;
6391 
6392     llvm::SmallString<4096> LookupTable;
6393     GenerateSpecializationInfoLookupTable(D, SpecializationUpdate.second,
6394                                           LookupTable, IsPartial);
6395 
6396     // Write the lookup table
6397     RecordData::value_type Record[] = {
6398         static_cast<RecordData::value_type>(RecordType),
6399         getDeclID(D).getRawValue()};
6400     Stream.EmitRecordWithBlob(UpdateSpecializationAbbrev, Record, LookupTable);
6401   }
6402 }
6403 
6404 void ASTWriter::WriteDeclUpdatesBlocks(ASTContext &Context,
6405                                        RecordDataImpl &OffsetsRecord) {
6406   if (DeclUpdates.empty())
6407     return;
6408 
6409   DeclUpdateMap LocalUpdates;
6410   LocalUpdates.swap(DeclUpdates);
6411 
6412   for (auto &DeclUpdate : LocalUpdates) {
6413     const Decl *D = DeclUpdate.first;
6414 
6415     bool HasUpdatedBody = false;
6416     bool HasAddedVarDefinition = false;
6417     RecordData RecordData;
6418     ASTRecordWriter Record(Context, *this, RecordData);
6419     for (auto &Update : DeclUpdate.second) {
6420       DeclUpdateKind Kind = Update.getKind();
6421 
6422       // An updated body is emitted last, so that the reader doesn't need
6423       // to skip over the lazy body to reach statements for other records.
6424       if (Kind == DeclUpdateKind::CXXAddedFunctionDefinition)
6425         HasUpdatedBody = true;
6426       else if (Kind == DeclUpdateKind::CXXAddedVarDefinition)
6427         HasAddedVarDefinition = true;
6428       else
6429         Record.push_back(llvm::to_underlying(Kind));
6430 
6431       switch (Kind) {
6432       case DeclUpdateKind::CXXAddedImplicitMember:
6433       case DeclUpdateKind::CXXAddedAnonymousNamespace:
6434         assert(Update.getDecl() && "no decl to add?");
6435         Record.AddDeclRef(Update.getDecl());
6436         break;
6437       case DeclUpdateKind::CXXAddedFunctionDefinition:
6438       case DeclUpdateKind::CXXAddedVarDefinition:
6439         break;
6440 
6441       case DeclUpdateKind::CXXPointOfInstantiation:
6442         // FIXME: Do we need to also save the template specialization kind here?
6443         Record.AddSourceLocation(Update.getLoc());
6444         break;
6445 
6446       case DeclUpdateKind::CXXInstantiatedDefaultArgument:
6447         Record.writeStmtRef(
6448             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg());
6449         break;
6450 
6451       case DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer:
6452         Record.AddStmt(
6453             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
6454         break;
6455 
6456       case DeclUpdateKind::CXXInstantiatedClassDefinition: {
6457         auto *RD = cast<CXXRecordDecl>(D);
6458         UpdatedDeclContexts.insert(RD->getPrimaryContext());
6459         Record.push_back(RD->isParamDestroyedInCallee());
6460         Record.push_back(llvm::to_underlying(RD->getArgPassingRestrictions()));
6461         Record.AddCXXDefinitionData(RD);
6462         Record.AddOffset(WriteDeclContextLexicalBlock(Context, RD));
6463 
6464         // This state is sometimes updated by template instantiation, when we
6465         // switch from the specialization referring to the template declaration
6466         // to it referring to the template definition.
6467         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
6468           Record.push_back(MSInfo->getTemplateSpecializationKind());
6469           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
6470         } else {
6471           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
6472           Record.push_back(Spec->getTemplateSpecializationKind());
6473           Record.AddSourceLocation(Spec->getPointOfInstantiation());
6474 
6475           // The instantiation might have been resolved to a partial
6476           // specialization. If so, record which one.
6477           auto From = Spec->getInstantiatedFrom();
6478           if (auto PartialSpec =
6479                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
6480             Record.push_back(true);
6481             Record.AddDeclRef(PartialSpec);
6482             Record.AddTemplateArgumentList(
6483                 &Spec->getTemplateInstantiationArgs());
6484           } else {
6485             Record.push_back(false);
6486           }
6487         }
6488         Record.push_back(llvm::to_underlying(RD->getTagKind()));
6489         Record.AddSourceLocation(RD->getLocation());
6490         Record.AddSourceLocation(RD->getBeginLoc());
6491         Record.AddSourceRange(RD->getBraceRange());
6492 
6493         // Instantiation may change attributes; write them all out afresh.
6494         Record.push_back(D->hasAttrs());
6495         if (D->hasAttrs())
6496           Record.AddAttributes(D->getAttrs());
6497 
6498         // FIXME: Ensure we don't get here for explicit instantiations.
6499         break;
6500       }
6501 
6502       case DeclUpdateKind::CXXResolvedDtorDelete:
6503         Record.AddDeclRef(Update.getDecl());
6504         Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
6505         break;
6506 
6507       case DeclUpdateKind::CXXResolvedExceptionSpec: {
6508         auto prototype =
6509           cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
6510         Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
6511         break;
6512       }
6513 
6514       case DeclUpdateKind::CXXDeducedReturnType:
6515         Record.push_back(GetOrCreateTypeID(Context, Update.getType()));
6516         break;
6517 
6518       case DeclUpdateKind::DeclMarkedUsed:
6519         break;
6520 
6521       case DeclUpdateKind::ManglingNumber:
6522       case DeclUpdateKind::StaticLocalNumber:
6523         Record.push_back(Update.getNumber());
6524         break;
6525 
6526       case DeclUpdateKind::DeclMarkedOpenMPThreadPrivate:
6527         Record.AddSourceRange(
6528             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
6529         break;
6530 
6531       case DeclUpdateKind::DeclMarkedOpenMPAllocate: {
6532         auto *A = D->getAttr<OMPAllocateDeclAttr>();
6533         Record.push_back(A->getAllocatorType());
6534         Record.AddStmt(A->getAllocator());
6535         Record.AddStmt(A->getAlignment());
6536         Record.AddSourceRange(A->getRange());
6537         break;
6538       }
6539 
6540       case DeclUpdateKind::DeclMarkedOpenMPDeclareTarget:
6541         Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
6542         Record.AddSourceRange(
6543             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
6544         break;
6545 
6546       case DeclUpdateKind::DeclExported:
6547         Record.push_back(getSubmoduleID(Update.getModule()));
6548         break;
6549 
6550       case DeclUpdateKind::AddedAttrToRecord:
6551         Record.AddAttributes(llvm::ArrayRef(Update.getAttr()));
6552         break;
6553       }
6554     }
6555 
6556     // Add a trailing update record, if any. These must go last because we
6557     // lazily load their attached statement.
6558     if (!GeneratingReducedBMI || !CanElideDeclDef(D)) {
6559       if (HasUpdatedBody) {
6560         const auto *Def = cast<FunctionDecl>(D);
6561         Record.push_back(
6562             llvm::to_underlying(DeclUpdateKind::CXXAddedFunctionDefinition));
6563         Record.push_back(Def->isInlined());
6564         Record.AddSourceLocation(Def->getInnerLocStart());
6565         Record.AddFunctionDefinition(Def);
6566       } else if (HasAddedVarDefinition) {
6567         const auto *VD = cast<VarDecl>(D);
6568         Record.push_back(
6569             llvm::to_underlying(DeclUpdateKind::CXXAddedVarDefinition));
6570         Record.push_back(VD->isInline());
6571         Record.push_back(VD->isInlineSpecified());
6572         Record.AddVarDeclInit(VD);
6573       }
6574     }
6575 
6576     AddDeclRef(D, OffsetsRecord);
6577     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
6578   }
6579 }
6580 
6581 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
6582                                  RecordDataImpl &Record) {
6583   uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
6584   Record.push_back(Raw);
6585 }
6586 
6587 FileID ASTWriter::getAdjustedFileID(FileID FID) const {
6588   if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
6589       NonAffectingFileIDs.empty())
6590     return FID;
6591   auto It = llvm::lower_bound(NonAffectingFileIDs, FID);
6592   unsigned Idx = std::distance(NonAffectingFileIDs.begin(), It);
6593   unsigned Offset = NonAffectingFileIDAdjustments[Idx];
6594   return FileID::get(FID.getOpaqueValue() - Offset);
6595 }
6596 
6597 unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
6598   unsigned NumCreatedFIDs = PP->getSourceManager()
6599                                 .getLocalSLocEntry(FID.ID)
6600                                 .getFile()
6601                                 .NumCreatedFIDs;
6602 
6603   unsigned AdjustedNumCreatedFIDs = 0;
6604   for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
6605     if (IsSLocAffecting[I])
6606       ++AdjustedNumCreatedFIDs;
6607   return AdjustedNumCreatedFIDs;
6608 }
6609 
6610 SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
6611   if (Loc.isInvalid())
6612     return Loc;
6613   return Loc.getLocWithOffset(-getAdjustment(Loc.getOffset()));
6614 }
6615 
6616 SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
6617   return SourceRange(getAdjustedLocation(Range.getBegin()),
6618                      getAdjustedLocation(Range.getEnd()));
6619 }
6620 
6621 SourceLocation::UIntTy
6622 ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
6623   return Offset - getAdjustment(Offset);
6624 }
6625 
6626 SourceLocation::UIntTy
6627 ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
6628   if (NonAffectingRanges.empty())
6629     return 0;
6630 
6631   if (PP->getSourceManager().isLoadedOffset(Offset))
6632     return 0;
6633 
6634   if (Offset > NonAffectingRanges.back().getEnd().getOffset())
6635     return NonAffectingOffsetAdjustments.back();
6636 
6637   if (Offset < NonAffectingRanges.front().getBegin().getOffset())
6638     return 0;
6639 
6640   auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
6641     return Range.getEnd().getOffset() < Offset;
6642   };
6643 
6644   auto It = llvm::lower_bound(NonAffectingRanges, Offset, Contains);
6645   unsigned Idx = std::distance(NonAffectingRanges.begin(), It);
6646   return NonAffectingOffsetAdjustments[Idx];
6647 }
6648 
6649 void ASTWriter::AddFileID(FileID FID, RecordDataImpl &Record) {
6650   Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
6651 }
6652 
6653 SourceLocationEncoding::RawLocEncoding
6654 ASTWriter::getRawSourceLocationEncoding(SourceLocation Loc) {
6655   SourceLocation::UIntTy BaseOffset = 0;
6656   unsigned ModuleFileIndex = 0;
6657 
6658   // See SourceLocationEncoding.h for the encoding details.
6659   if (PP->getSourceManager().isLoadedSourceLocation(Loc) && Loc.isValid()) {
6660     assert(getChain());
6661     auto SLocMapI = getChain()->GlobalSLocOffsetMap.find(
6662         SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6663     assert(SLocMapI != getChain()->GlobalSLocOffsetMap.end() &&
6664            "Corrupted global sloc offset map");
6665     ModuleFile *F = SLocMapI->second;
6666     BaseOffset = F->SLocEntryBaseOffset - 2;
6667     // 0 means the location is not loaded. So we need to add 1 to the index to
6668     // make it clear.
6669     ModuleFileIndex = F->Index + 1;
6670     assert(&getChain()->getModuleManager()[F->Index] == F);
6671   }
6672 
6673   return SourceLocationEncoding::encode(Loc, BaseOffset, ModuleFileIndex);
6674 }
6675 
6676 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
6677   Loc = getAdjustedLocation(Loc);
6678   Record.push_back(getRawSourceLocationEncoding(Loc));
6679 }
6680 
6681 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
6682   AddSourceLocation(Range.getBegin(), Record);
6683   AddSourceLocation(Range.getEnd(), Record);
6684 }
6685 
6686 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
6687   AddAPInt(Value.bitcastToAPInt());
6688 }
6689 
6690 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
6691   Record.push_back(getIdentifierRef(II));
6692 }
6693 
6694 IdentifierID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
6695   if (!II)
6696     return 0;
6697 
6698   IdentifierID &ID = IdentifierIDs[II];
6699   if (ID == 0)
6700     ID = NextIdentID++;
6701   return ID;
6702 }
6703 
6704 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
6705   // Don't emit builtin macros like __LINE__ to the AST file unless they
6706   // have been redefined by the header (in which case they are not
6707   // isBuiltinMacro).
6708   if (!MI || MI->isBuiltinMacro())
6709     return 0;
6710 
6711   MacroID &ID = MacroIDs[MI];
6712   if (ID == 0) {
6713     ID = NextMacroID++;
6714     MacroInfoToEmitData Info = { Name, MI, ID };
6715     MacroInfosToEmit.push_back(Info);
6716   }
6717   return ID;
6718 }
6719 
6720 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
6721   return IdentMacroDirectivesOffsetMap.lookup(Name);
6722 }
6723 
6724 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
6725   Record->push_back(Writer->getSelectorRef(SelRef));
6726 }
6727 
6728 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
6729   if (Sel.getAsOpaquePtr() == nullptr) {
6730     return 0;
6731   }
6732 
6733   SelectorID SID = SelectorIDs[Sel];
6734   if (SID == 0 && Chain) {
6735     // This might trigger a ReadSelector callback, which will set the ID for
6736     // this selector.
6737     Chain->LoadSelector(Sel);
6738     SID = SelectorIDs[Sel];
6739   }
6740   if (SID == 0) {
6741     SID = NextSelectorID++;
6742     SelectorIDs[Sel] = SID;
6743   }
6744   return SID;
6745 }
6746 
6747 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
6748   AddDeclRef(Temp->getDestructor());
6749 }
6750 
6751 void ASTRecordWriter::AddTemplateArgumentLocInfo(
6752     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
6753   switch (Kind) {
6754   case TemplateArgument::Expression:
6755     AddStmt(Arg.getAsExpr());
6756     break;
6757   case TemplateArgument::Type:
6758     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
6759     break;
6760   case TemplateArgument::Template:
6761     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
6762     AddSourceLocation(Arg.getTemplateNameLoc());
6763     break;
6764   case TemplateArgument::TemplateExpansion:
6765     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
6766     AddSourceLocation(Arg.getTemplateNameLoc());
6767     AddSourceLocation(Arg.getTemplateEllipsisLoc());
6768     break;
6769   case TemplateArgument::Null:
6770   case TemplateArgument::Integral:
6771   case TemplateArgument::Declaration:
6772   case TemplateArgument::NullPtr:
6773   case TemplateArgument::StructuralValue:
6774   case TemplateArgument::Pack:
6775     // FIXME: Is this right?
6776     break;
6777   }
6778 }
6779 
6780 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
6781   AddTemplateArgument(Arg.getArgument());
6782 
6783   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
6784     bool InfoHasSameExpr
6785       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
6786     Record->push_back(InfoHasSameExpr);
6787     if (InfoHasSameExpr)
6788       return; // Avoid storing the same expr twice.
6789   }
6790   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
6791 }
6792 
6793 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
6794   if (!TInfo) {
6795     AddTypeRef(QualType());
6796     return;
6797   }
6798 
6799   AddTypeRef(TInfo->getType());
6800   AddTypeLoc(TInfo->getTypeLoc());
6801 }
6802 
6803 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
6804   TypeLocWriter TLW(*this);
6805   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6806     TLW.Visit(TL);
6807 }
6808 
6809 void ASTWriter::AddTypeRef(ASTContext &Context, QualType T,
6810                            RecordDataImpl &Record) {
6811   Record.push_back(GetOrCreateTypeID(Context, T));
6812 }
6813 
6814 template <typename IdxForTypeTy>
6815 static TypeID MakeTypeID(ASTContext &Context, QualType T,
6816                          IdxForTypeTy IdxForType) {
6817   if (T.isNull())
6818     return PREDEF_TYPE_NULL_ID;
6819 
6820   unsigned FastQuals = T.getLocalFastQualifiers();
6821   T.removeLocalFastQualifiers();
6822 
6823   if (T.hasLocalNonFastQualifiers())
6824     return IdxForType(T).asTypeID(FastQuals);
6825 
6826   assert(!T.hasLocalQualifiers());
6827 
6828   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr()))
6829     return TypeIdxFromBuiltin(BT).asTypeID(FastQuals);
6830 
6831   if (T == Context.AutoDeductTy)
6832     return TypeIdx(0, PREDEF_TYPE_AUTO_DEDUCT).asTypeID(FastQuals);
6833   if (T == Context.AutoRRefDeductTy)
6834     return TypeIdx(0, PREDEF_TYPE_AUTO_RREF_DEDUCT).asTypeID(FastQuals);
6835 
6836   return IdxForType(T).asTypeID(FastQuals);
6837 }
6838 
6839 TypeID ASTWriter::GetOrCreateTypeID(ASTContext &Context, QualType T) {
6840   return MakeTypeID(Context, T, [&](QualType T) -> TypeIdx {
6841     if (T.isNull())
6842       return TypeIdx();
6843     assert(!T.getLocalFastQualifiers());
6844 
6845     TypeIdx &Idx = TypeIdxs[T];
6846     if (Idx.getValue() == 0) {
6847       if (DoneWritingDeclsAndTypes) {
6848         assert(0 && "New type seen after serializing all the types to emit!");
6849         return TypeIdx();
6850       }
6851 
6852       // We haven't seen this type before. Assign it a new ID and put it
6853       // into the queue of types to emit.
6854       Idx = TypeIdx(0, NextTypeID++);
6855       DeclTypesToEmit.push(T);
6856     }
6857     return Idx;
6858   });
6859 }
6860 
6861 void ASTWriter::AddLookupOffsets(const LookupBlockOffsets &Offsets,
6862                                  RecordDataImpl &Record) {
6863   Record.push_back(Offsets.LexicalOffset);
6864   Record.push_back(Offsets.VisibleOffset);
6865   Record.push_back(Offsets.ModuleLocalOffset);
6866   Record.push_back(Offsets.TULocalOffset);
6867 }
6868 
6869 void ASTWriter::AddEmittedDeclRef(const Decl *D, RecordDataImpl &Record) {
6870   if (!wasDeclEmitted(D))
6871     return;
6872 
6873   AddDeclRef(D, Record);
6874 }
6875 
6876 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
6877   Record.push_back(GetDeclRef(D).getRawValue());
6878 }
6879 
6880 LocalDeclID ASTWriter::GetDeclRef(const Decl *D) {
6881   assert(WritingAST && "Cannot request a declaration ID before AST writing");
6882 
6883   if (!D) {
6884     return LocalDeclID();
6885   }
6886 
6887   // If the DeclUpdate from the GMF gets touched, emit it.
6888   if (auto *Iter = DeclUpdatesFromGMF.find(D);
6889       Iter != DeclUpdatesFromGMF.end()) {
6890     for (DeclUpdate &Update : Iter->second)
6891       DeclUpdates[D].push_back(Update);
6892     DeclUpdatesFromGMF.erase(Iter);
6893   }
6894 
6895   // If D comes from an AST file, its declaration ID is already known and
6896   // fixed.
6897   if (D->isFromASTFile()) {
6898     if (isWritingStdCXXNamedModules() && D->getOwningModule())
6899       TouchedTopLevelModules.insert(D->getOwningModule()->getTopLevelModule());
6900 
6901     return LocalDeclID(D->getGlobalID());
6902   }
6903 
6904   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
6905   LocalDeclID &ID = DeclIDs[D];
6906   if (ID.isInvalid()) {
6907     if (DoneWritingDeclsAndTypes) {
6908       assert(0 && "New decl seen after serializing all the decls to emit!");
6909       return LocalDeclID();
6910     }
6911 
6912     // We haven't seen this declaration before. Give it a new ID and
6913     // enqueue it in the list of declarations to emit.
6914     ID = NextDeclID++;
6915     DeclTypesToEmit.push(const_cast<Decl *>(D));
6916   }
6917 
6918   return ID;
6919 }
6920 
6921 LocalDeclID ASTWriter::getDeclID(const Decl *D) {
6922   if (!D)
6923     return LocalDeclID();
6924 
6925   // If D comes from an AST file, its declaration ID is already known and
6926   // fixed.
6927   if (D->isFromASTFile())
6928     return LocalDeclID(D->getGlobalID());
6929 
6930   assert(DeclIDs.contains(D) && "Declaration not emitted!");
6931   return DeclIDs[D];
6932 }
6933 
6934 bool ASTWriter::wasDeclEmitted(const Decl *D) const {
6935   assert(D);
6936 
6937   assert(DoneWritingDeclsAndTypes &&
6938          "wasDeclEmitted should only be called after writing declarations");
6939 
6940   if (D->isFromASTFile())
6941     return true;
6942 
6943   bool Emitted = DeclIDs.contains(D);
6944   assert((Emitted || (!D->getOwningModule() && isWritingStdCXXNamedModules()) ||
6945           GeneratingReducedBMI) &&
6946          "The declaration within modules can only be omitted in reduced BMI.");
6947   return Emitted;
6948 }
6949 
6950 void ASTWriter::associateDeclWithFile(const Decl *D, LocalDeclID ID) {
6951   assert(ID.isValid());
6952   assert(D);
6953 
6954   SourceLocation Loc = D->getLocation();
6955   if (Loc.isInvalid())
6956     return;
6957 
6958   // We only keep track of the file-level declarations of each file.
6959   if (!D->getLexicalDeclContext()->isFileContext())
6960     return;
6961   // FIXME: ParmVarDecls that are part of a function type of a parameter of
6962   // a function/objc method, should not have TU as lexical context.
6963   // TemplateTemplateParmDecls that are part of an alias template, should not
6964   // have TU as lexical context.
6965   if (isa<ParmVarDecl, TemplateTemplateParmDecl>(D))
6966     return;
6967 
6968   SourceManager &SM = PP->getSourceManager();
6969   SourceLocation FileLoc = SM.getFileLoc(Loc);
6970   assert(SM.isLocalSourceLocation(FileLoc));
6971   auto [FID, Offset] = SM.getDecomposedLoc(FileLoc);
6972   if (FID.isInvalid())
6973     return;
6974   assert(SM.getSLocEntry(FID).isFile());
6975   assert(IsSLocAffecting[FID.ID]);
6976 
6977   std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
6978   if (!Info)
6979     Info = std::make_unique<DeclIDInFileInfo>();
6980 
6981   std::pair<unsigned, LocalDeclID> LocDecl(Offset, ID);
6982   LocDeclIDsTy &Decls = Info->DeclIDs;
6983   Decls.push_back(LocDecl);
6984 }
6985 
6986 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
6987   assert(needsAnonymousDeclarationNumber(D) &&
6988          "expected an anonymous declaration");
6989 
6990   // Number the anonymous declarations within this context, if we've not
6991   // already done so.
6992   auto It = AnonymousDeclarationNumbers.find(D);
6993   if (It == AnonymousDeclarationNumbers.end()) {
6994     auto *DC = D->getLexicalDeclContext();
6995     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
6996       AnonymousDeclarationNumbers[ND] = Number;
6997     });
6998 
6999     It = AnonymousDeclarationNumbers.find(D);
7000     assert(It != AnonymousDeclarationNumbers.end() &&
7001            "declaration not found within its lexical context");
7002   }
7003 
7004   return It->second;
7005 }
7006 
7007 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
7008                                             DeclarationName Name) {
7009   switch (Name.getNameKind()) {
7010   case DeclarationName::CXXConstructorName:
7011   case DeclarationName::CXXDestructorName:
7012   case DeclarationName::CXXConversionFunctionName:
7013     AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
7014     break;
7015 
7016   case DeclarationName::CXXOperatorName:
7017     AddSourceRange(DNLoc.getCXXOperatorNameRange());
7018     break;
7019 
7020   case DeclarationName::CXXLiteralOperatorName:
7021     AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
7022     break;
7023 
7024   case DeclarationName::Identifier:
7025   case DeclarationName::ObjCZeroArgSelector:
7026   case DeclarationName::ObjCOneArgSelector:
7027   case DeclarationName::ObjCMultiArgSelector:
7028   case DeclarationName::CXXUsingDirective:
7029   case DeclarationName::CXXDeductionGuideName:
7030     break;
7031   }
7032 }
7033 
7034 void ASTRecordWriter::AddDeclarationNameInfo(
7035     const DeclarationNameInfo &NameInfo) {
7036   AddDeclarationName(NameInfo.getName());
7037   AddSourceLocation(NameInfo.getLoc());
7038   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
7039 }
7040 
7041 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
7042   AddNestedNameSpecifierLoc(Info.QualifierLoc);
7043   Record->push_back(Info.NumTemplParamLists);
7044   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
7045     AddTemplateParameterList(Info.TemplParamLists[i]);
7046 }
7047 
7048 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
7049   // Nested name specifiers usually aren't too long. I think that 8 would
7050   // typically accommodate the vast majority.
7051   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
7052 
7053   // Push each of the nested-name-specifiers's onto a stack for
7054   // serialization in reverse order.
7055   while (NNS) {
7056     NestedNames.push_back(NNS);
7057     NNS = NNS.getPrefix();
7058   }
7059 
7060   Record->push_back(NestedNames.size());
7061   while(!NestedNames.empty()) {
7062     NNS = NestedNames.pop_back_val();
7063     NestedNameSpecifier::SpecifierKind Kind
7064       = NNS.getNestedNameSpecifier()->getKind();
7065     Record->push_back(Kind);
7066     switch (Kind) {
7067     case NestedNameSpecifier::Identifier:
7068       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
7069       AddSourceRange(NNS.getLocalSourceRange());
7070       break;
7071 
7072     case NestedNameSpecifier::Namespace:
7073       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
7074       AddSourceRange(NNS.getLocalSourceRange());
7075       break;
7076 
7077     case NestedNameSpecifier::NamespaceAlias:
7078       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
7079       AddSourceRange(NNS.getLocalSourceRange());
7080       break;
7081 
7082     case NestedNameSpecifier::TypeSpec:
7083       AddTypeRef(NNS.getTypeLoc().getType());
7084       AddTypeLoc(NNS.getTypeLoc());
7085       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
7086       break;
7087 
7088     case NestedNameSpecifier::Global:
7089       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
7090       break;
7091 
7092     case NestedNameSpecifier::Super:
7093       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
7094       AddSourceRange(NNS.getLocalSourceRange());
7095       break;
7096     }
7097   }
7098 }
7099 
7100 void ASTRecordWriter::AddTemplateParameterList(
7101     const TemplateParameterList *TemplateParams) {
7102   assert(TemplateParams && "No TemplateParams!");
7103   AddSourceLocation(TemplateParams->getTemplateLoc());
7104   AddSourceLocation(TemplateParams->getLAngleLoc());
7105   AddSourceLocation(TemplateParams->getRAngleLoc());
7106 
7107   Record->push_back(TemplateParams->size());
7108   for (const auto &P : *TemplateParams)
7109     AddDeclRef(P);
7110   if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
7111     Record->push_back(true);
7112     writeStmtRef(RequiresClause);
7113   } else {
7114     Record->push_back(false);
7115   }
7116 }
7117 
7118 /// Emit a template argument list.
7119 void ASTRecordWriter::AddTemplateArgumentList(
7120     const TemplateArgumentList *TemplateArgs) {
7121   assert(TemplateArgs && "No TemplateArgs!");
7122   Record->push_back(TemplateArgs->size());
7123   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
7124     AddTemplateArgument(TemplateArgs->get(i));
7125 }
7126 
7127 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
7128     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
7129   assert(ASTTemplArgList && "No ASTTemplArgList!");
7130   AddSourceLocation(ASTTemplArgList->LAngleLoc);
7131   AddSourceLocation(ASTTemplArgList->RAngleLoc);
7132   Record->push_back(ASTTemplArgList->NumTemplateArgs);
7133   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
7134   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
7135     AddTemplateArgumentLoc(TemplArgs[i]);
7136 }
7137 
7138 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
7139   Record->push_back(Set.size());
7140   for (ASTUnresolvedSet::const_iterator
7141          I = Set.begin(), E = Set.end(); I != E; ++I) {
7142     AddDeclRef(I.getDecl());
7143     Record->push_back(I.getAccess());
7144   }
7145 }
7146 
7147 // FIXME: Move this out of the main ASTRecordWriter interface.
7148 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
7149   Record->push_back(Base.isVirtual());
7150   Record->push_back(Base.isBaseOfClass());
7151   Record->push_back(Base.getAccessSpecifierAsWritten());
7152   Record->push_back(Base.getInheritConstructors());
7153   AddTypeSourceInfo(Base.getTypeSourceInfo());
7154   AddSourceRange(Base.getSourceRange());
7155   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
7156                                           : SourceLocation());
7157 }
7158 
7159 static uint64_t EmitCXXBaseSpecifiers(ASTContext &Context, ASTWriter &W,
7160                                       ArrayRef<CXXBaseSpecifier> Bases) {
7161   ASTWriter::RecordData Record;
7162   ASTRecordWriter Writer(Context, W, Record);
7163   Writer.push_back(Bases.size());
7164 
7165   for (auto &Base : Bases)
7166     Writer.AddCXXBaseSpecifier(Base);
7167 
7168   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
7169 }
7170 
7171 // FIXME: Move this out of the main ASTRecordWriter interface.
7172 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
7173   AddOffset(EmitCXXBaseSpecifiers(getASTContext(), *Writer, Bases));
7174 }
7175 
7176 static uint64_t
7177 EmitCXXCtorInitializers(ASTContext &Context, ASTWriter &W,
7178                         ArrayRef<CXXCtorInitializer *> CtorInits) {
7179   ASTWriter::RecordData Record;
7180   ASTRecordWriter Writer(Context, W, Record);
7181   Writer.push_back(CtorInits.size());
7182 
7183   for (auto *Init : CtorInits) {
7184     if (Init->isBaseInitializer()) {
7185       Writer.push_back(CTOR_INITIALIZER_BASE);
7186       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
7187       Writer.push_back(Init->isBaseVirtual());
7188     } else if (Init->isDelegatingInitializer()) {
7189       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
7190       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
7191     } else if (Init->isMemberInitializer()){
7192       Writer.push_back(CTOR_INITIALIZER_MEMBER);
7193       Writer.AddDeclRef(Init->getMember());
7194     } else {
7195       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
7196       Writer.AddDeclRef(Init->getIndirectMember());
7197     }
7198 
7199     Writer.AddSourceLocation(Init->getMemberLocation());
7200     Writer.AddStmt(Init->getInit());
7201     Writer.AddSourceLocation(Init->getLParenLoc());
7202     Writer.AddSourceLocation(Init->getRParenLoc());
7203     Writer.push_back(Init->isWritten());
7204     if (Init->isWritten())
7205       Writer.push_back(Init->getSourceOrder());
7206   }
7207 
7208   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
7209 }
7210 
7211 // FIXME: Move this out of the main ASTRecordWriter interface.
7212 void ASTRecordWriter::AddCXXCtorInitializers(
7213     ArrayRef<CXXCtorInitializer *> CtorInits) {
7214   AddOffset(EmitCXXCtorInitializers(getASTContext(), *Writer, CtorInits));
7215 }
7216 
7217 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
7218   auto &Data = D->data();
7219 
7220   Record->push_back(Data.IsLambda);
7221 
7222   BitsPacker DefinitionBits;
7223 
7224 #define FIELD(Name, Width, Merge)                                              \
7225   if (!DefinitionBits.canWriteNextNBits(Width)) {                              \
7226     Record->push_back(DefinitionBits);                                         \
7227     DefinitionBits.reset(0);                                                   \
7228   }                                                                            \
7229   DefinitionBits.addBits(Data.Name, Width);
7230 
7231 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
7232 #undef FIELD
7233 
7234   Record->push_back(DefinitionBits);
7235 
7236   // getODRHash will compute the ODRHash if it has not been previously
7237   // computed.
7238   Record->push_back(D->getODRHash());
7239 
7240   bool ModulesCodegen =
7241       !D->isDependentType() &&
7242       D->getTemplateSpecializationKind() !=
7243           TSK_ExplicitInstantiationDeclaration &&
7244       (Writer->getLangOpts().ModulesDebugInfo || D->isInNamedModule());
7245   Record->push_back(ModulesCodegen);
7246   if (ModulesCodegen)
7247     Writer->AddDeclRef(D, Writer->ModularCodegenDecls);
7248 
7249   // IsLambda bit is already saved.
7250 
7251   AddUnresolvedSet(Data.Conversions.get(getASTContext()));
7252   Record->push_back(Data.ComputedVisibleConversions);
7253   if (Data.ComputedVisibleConversions)
7254     AddUnresolvedSet(Data.VisibleConversions.get(getASTContext()));
7255   // Data.Definition is the owning decl, no need to write it.
7256 
7257   if (!Data.IsLambda) {
7258     Record->push_back(Data.NumBases);
7259     if (Data.NumBases > 0)
7260       AddCXXBaseSpecifiers(Data.bases());
7261 
7262     // FIXME: Make VBases lazily computed when needed to avoid storing them.
7263     Record->push_back(Data.NumVBases);
7264     if (Data.NumVBases > 0)
7265       AddCXXBaseSpecifiers(Data.vbases());
7266 
7267     AddDeclRef(D->getFirstFriend());
7268   } else {
7269     auto &Lambda = D->getLambdaData();
7270 
7271     BitsPacker LambdaBits;
7272     LambdaBits.addBits(Lambda.DependencyKind, /*Width=*/2);
7273     LambdaBits.addBit(Lambda.IsGenericLambda);
7274     LambdaBits.addBits(Lambda.CaptureDefault, /*Width=*/2);
7275     LambdaBits.addBits(Lambda.NumCaptures, /*Width=*/15);
7276     LambdaBits.addBit(Lambda.HasKnownInternalLinkage);
7277     Record->push_back(LambdaBits);
7278 
7279     Record->push_back(Lambda.NumExplicitCaptures);
7280     Record->push_back(Lambda.ManglingNumber);
7281     Record->push_back(D->getDeviceLambdaManglingNumber());
7282     // The lambda context declaration and index within the context are provided
7283     // separately, so that they can be used for merging.
7284     AddTypeSourceInfo(Lambda.MethodTyInfo);
7285     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
7286       const LambdaCapture &Capture = Lambda.Captures.front()[I];
7287       AddSourceLocation(Capture.getLocation());
7288 
7289       BitsPacker CaptureBits;
7290       CaptureBits.addBit(Capture.isImplicit());
7291       CaptureBits.addBits(Capture.getCaptureKind(), /*Width=*/3);
7292       Record->push_back(CaptureBits);
7293 
7294       switch (Capture.getCaptureKind()) {
7295       case LCK_StarThis:
7296       case LCK_This:
7297       case LCK_VLAType:
7298         break;
7299       case LCK_ByCopy:
7300       case LCK_ByRef:
7301         ValueDecl *Var =
7302             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
7303         AddDeclRef(Var);
7304         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
7305                                                     : SourceLocation());
7306         break;
7307       }
7308     }
7309   }
7310 }
7311 
7312 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
7313   const Expr *Init = VD->getInit();
7314   if (!Init) {
7315     push_back(0);
7316     return;
7317   }
7318 
7319   uint64_t Val = 1;
7320   if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
7321     // This may trigger evaluation, so run it first
7322     if (VD->hasInitWithSideEffects())
7323       Val |= 16;
7324     assert(ES->CheckedForSideEffects);
7325     Val |= (ES->HasConstantInitialization ? 2 : 0);
7326     Val |= (ES->HasConstantDestruction ? 4 : 0);
7327     APValue *Evaluated = VD->getEvaluatedValue();
7328     // If the evaluated result is constant, emit it.
7329     if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
7330       Val |= 8;
7331   }
7332   push_back(Val);
7333   if (Val & 8) {
7334     AddAPValue(*VD->getEvaluatedValue());
7335   }
7336 
7337   writeStmtRef(Init);
7338 }
7339 
7340 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
7341   assert(Reader && "Cannot remove chain");
7342   assert((!Chain || Chain == Reader) && "Cannot replace chain");
7343   assert(FirstDeclID == NextDeclID &&
7344          FirstTypeID == NextTypeID &&
7345          FirstIdentID == NextIdentID &&
7346          FirstMacroID == NextMacroID &&
7347          FirstSubmoduleID == NextSubmoduleID &&
7348          FirstSelectorID == NextSelectorID &&
7349          "Setting chain after writing has started.");
7350 
7351   Chain = Reader;
7352 
7353   // Note, this will get called multiple times, once one the reader starts up
7354   // and again each time it's done reading a PCH or module.
7355   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
7356   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
7357   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
7358   NextMacroID = FirstMacroID;
7359   NextSelectorID = FirstSelectorID;
7360   NextSubmoduleID = FirstSubmoduleID;
7361 }
7362 
7363 void ASTWriter::IdentifierRead(IdentifierID ID, IdentifierInfo *II) {
7364   // Don't reuse Type ID from external modules for named modules. See the
7365   // comments in WriteASTCore for details.
7366   if (isWritingStdCXXNamedModules())
7367     return;
7368 
7369   IdentifierID &StoredID = IdentifierIDs[II];
7370   unsigned OriginalModuleFileIndex = StoredID >> 32;
7371 
7372   // Always keep the local identifier ID. See \p TypeRead() for more
7373   // information.
7374   if (OriginalModuleFileIndex == 0 && StoredID)
7375     return;
7376 
7377   // Otherwise, keep the highest ID since the module file comes later has
7378   // higher module file indexes.
7379   if (ID > StoredID)
7380     StoredID = ID;
7381 }
7382 
7383 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
7384   // Always keep the highest ID. See \p TypeRead() for more information.
7385   MacroID &StoredID = MacroIDs[MI];
7386   if (ID > StoredID)
7387     StoredID = ID;
7388 }
7389 
7390 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
7391   // Don't reuse Type ID from external modules for named modules. See the
7392   // comments in WriteASTCore for details.
7393   if (isWritingStdCXXNamedModules())
7394     return;
7395 
7396   // Always take the type index that comes in later module files.
7397   // This copes with an interesting
7398   // case for chained AST writing where we schedule writing the type and then,
7399   // later, deserialize the type from another AST. In this case, we want to
7400   // keep the entry from a later module so that we can properly write it out to
7401   // the AST file.
7402   TypeIdx &StoredIdx = TypeIdxs[T];
7403 
7404   // Ignore it if the type comes from the current being written module file.
7405   // Since the current module file being written logically has the highest
7406   // index.
7407   unsigned ModuleFileIndex = StoredIdx.getModuleFileIndex();
7408   if (ModuleFileIndex == 0 && StoredIdx.getValue())
7409     return;
7410 
7411   // Otherwise, keep the highest ID since the module file comes later has
7412   // higher module file indexes.
7413   if (Idx.getModuleFileIndex() >= StoredIdx.getModuleFileIndex())
7414     StoredIdx = Idx;
7415 }
7416 
7417 void ASTWriter::PredefinedDeclBuilt(PredefinedDeclIDs ID, const Decl *D) {
7418   assert(D->isCanonicalDecl() && "predefined decl is not canonical");
7419   DeclIDs[D] = LocalDeclID(ID);
7420   PredefinedDecls.insert(D);
7421 }
7422 
7423 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
7424   // Always keep the highest ID. See \p TypeRead() for more information.
7425   SelectorID &StoredID = SelectorIDs[S];
7426   if (ID > StoredID)
7427     StoredID = ID;
7428 }
7429 
7430 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
7431                                     MacroDefinitionRecord *MD) {
7432   assert(!MacroDefinitions.contains(MD));
7433   MacroDefinitions[MD] = ID;
7434 }
7435 
7436 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
7437   assert(!SubmoduleIDs.contains(Mod));
7438   SubmoduleIDs[Mod] = ID;
7439 }
7440 
7441 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
7442   if (Chain && Chain->isProcessingUpdateRecords()) return;
7443   assert(D->isCompleteDefinition());
7444   assert(!WritingAST && "Already writing the AST!");
7445   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7446     // We are interested when a PCH decl is modified.
7447     if (RD->isFromASTFile()) {
7448       // A forward reference was mutated into a definition. Rewrite it.
7449       // FIXME: This happens during template instantiation, should we
7450       // have created a new definition decl instead ?
7451       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
7452              "completed a tag from another module but not by instantiation?");
7453       DeclUpdates[RD].push_back(
7454           DeclUpdate(DeclUpdateKind::CXXInstantiatedClassDefinition));
7455     }
7456   }
7457 }
7458 
7459 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
7460   if (D->isFromASTFile())
7461     return true;
7462 
7463   // The predefined __va_list_tag struct is imported if we imported any decls.
7464   // FIXME: This is a gross hack.
7465   return D == D->getASTContext().getVaListTagDecl();
7466 }
7467 
7468 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
7469   if (Chain && Chain->isProcessingUpdateRecords()) return;
7470   assert(DC->isLookupContext() &&
7471           "Should not add lookup results to non-lookup contexts!");
7472 
7473   // TU is handled elsewhere.
7474   if (isa<TranslationUnitDecl>(DC))
7475     return;
7476 
7477   // Namespaces are handled elsewhere, except for template instantiations of
7478   // FunctionTemplateDecls in namespaces. We are interested in cases where the
7479   // local instantiations are added to an imported context. Only happens when
7480   // adding ADL lookup candidates, for example templated friends.
7481   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
7482       !isa<FunctionTemplateDecl>(D))
7483     return;
7484 
7485   // We're only interested in cases where a local declaration is added to an
7486   // imported context.
7487   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
7488     return;
7489 
7490   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
7491   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
7492   assert(!WritingAST && "Already writing the AST!");
7493   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
7494     // We're adding a visible declaration to a predefined decl context. Ensure
7495     // that we write out all of its lookup results so we don't get a nasty
7496     // surprise when we try to emit its lookup table.
7497     llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
7498   }
7499   DeclsToEmitEvenIfUnreferenced.push_back(D);
7500 }
7501 
7502 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
7503   if (Chain && Chain->isProcessingUpdateRecords()) return;
7504   assert(D->isImplicit());
7505 
7506   // We're only interested in cases where a local declaration is added to an
7507   // imported context.
7508   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
7509     return;
7510 
7511   if (!isa<CXXMethodDecl>(D))
7512     return;
7513 
7514   // A decl coming from PCH was modified.
7515   assert(RD->isCompleteDefinition());
7516   assert(!WritingAST && "Already writing the AST!");
7517   DeclUpdates[RD].push_back(
7518       DeclUpdate(DeclUpdateKind::CXXAddedImplicitMember, D));
7519 }
7520 
7521 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
7522   if (Chain && Chain->isProcessingUpdateRecords()) return;
7523   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
7524   if (!Chain) return;
7525   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7526     // If we don't already know the exception specification for this redecl
7527     // chain, add an update record for it.
7528     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
7529                                       ->getType()
7530                                       ->castAs<FunctionProtoType>()
7531                                       ->getExceptionSpecType()))
7532       DeclUpdates[D].push_back(DeclUpdateKind::CXXResolvedExceptionSpec);
7533   });
7534 }
7535 
7536 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
7537   if (Chain && Chain->isProcessingUpdateRecords()) return;
7538   assert(!WritingAST && "Already writing the AST!");
7539   if (!Chain) return;
7540   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7541     DeclUpdates[D].push_back(
7542         DeclUpdate(DeclUpdateKind::CXXDeducedReturnType, ReturnType));
7543   });
7544 }
7545 
7546 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
7547                                        const FunctionDecl *Delete,
7548                                        Expr *ThisArg) {
7549   if (Chain && Chain->isProcessingUpdateRecords()) return;
7550   assert(!WritingAST && "Already writing the AST!");
7551   assert(Delete && "Not given an operator delete");
7552   if (!Chain) return;
7553   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7554     DeclUpdates[D].push_back(
7555         DeclUpdate(DeclUpdateKind::CXXResolvedDtorDelete, Delete));
7556   });
7557 }
7558 
7559 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
7560   if (Chain && Chain->isProcessingUpdateRecords()) return;
7561   assert(!WritingAST && "Already writing the AST!");
7562   if (!D->isFromASTFile())
7563     return; // Declaration not imported from PCH.
7564 
7565   // The function definition may not have a body due to parsing errors.
7566   if (!D->doesThisDeclarationHaveABody())
7567     return;
7568 
7569   // Implicit function decl from a PCH was defined.
7570   DeclUpdates[D].push_back(
7571       DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7572 }
7573 
7574 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
7575   if (Chain && Chain->isProcessingUpdateRecords()) return;
7576   assert(!WritingAST && "Already writing the AST!");
7577   if (!D->isFromASTFile())
7578     return;
7579 
7580   DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::CXXAddedVarDefinition));
7581 }
7582 
7583 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
7584   if (Chain && Chain->isProcessingUpdateRecords()) return;
7585   assert(!WritingAST && "Already writing the AST!");
7586   if (!D->isFromASTFile())
7587     return;
7588 
7589   // The function definition may not have a body due to parsing errors.
7590   if (!D->doesThisDeclarationHaveABody())
7591     return;
7592 
7593   DeclUpdates[D].push_back(
7594       DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7595 }
7596 
7597 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
7598   if (Chain && Chain->isProcessingUpdateRecords()) return;
7599   assert(!WritingAST && "Already writing the AST!");
7600   if (!D->isFromASTFile())
7601     return;
7602 
7603   // Since the actual instantiation is delayed, this really means that we need
7604   // to update the instantiation location.
7605   SourceLocation POI;
7606   if (auto *VD = dyn_cast<VarDecl>(D))
7607     POI = VD->getPointOfInstantiation();
7608   else
7609     POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
7610   DeclUpdates[D].push_back(
7611       DeclUpdate(DeclUpdateKind::CXXPointOfInstantiation, POI));
7612 }
7613 
7614 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
7615   if (Chain && Chain->isProcessingUpdateRecords()) return;
7616   assert(!WritingAST && "Already writing the AST!");
7617   if (!D->isFromASTFile())
7618     return;
7619 
7620   DeclUpdates[D].push_back(
7621       DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultArgument, D));
7622 }
7623 
7624 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
7625   assert(!WritingAST && "Already writing the AST!");
7626   if (!D->isFromASTFile())
7627     return;
7628 
7629   DeclUpdates[D].push_back(
7630       DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer, D));
7631 }
7632 
7633 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
7634                                              const ObjCInterfaceDecl *IFD) {
7635   if (Chain && Chain->isProcessingUpdateRecords()) return;
7636   assert(!WritingAST && "Already writing the AST!");
7637   if (!IFD->isFromASTFile())
7638     return; // Declaration not imported from PCH.
7639 
7640   assert(IFD->getDefinition() && "Category on a class without a definition?");
7641   ObjCClassesWithCategories.insert(
7642     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
7643 }
7644 
7645 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
7646   if (Chain && Chain->isProcessingUpdateRecords()) return;
7647   assert(!WritingAST && "Already writing the AST!");
7648 
7649   // If there is *any* declaration of the entity that's not from an AST file,
7650   // we can skip writing the update record. We make sure that isUsed() triggers
7651   // completion of the redeclaration chain of the entity.
7652   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
7653     if (IsLocalDecl(Prev))
7654       return;
7655 
7656   DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::DeclMarkedUsed));
7657 }
7658 
7659 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
7660   if (Chain && Chain->isProcessingUpdateRecords()) return;
7661   assert(!WritingAST && "Already writing the AST!");
7662   if (!D->isFromASTFile())
7663     return;
7664 
7665   DeclUpdates[D].push_back(
7666       DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPThreadPrivate));
7667 }
7668 
7669 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
7670   if (Chain && Chain->isProcessingUpdateRecords()) return;
7671   assert(!WritingAST && "Already writing the AST!");
7672   if (!D->isFromASTFile())
7673     return;
7674 
7675   DeclUpdates[D].push_back(
7676       DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPAllocate, A));
7677 }
7678 
7679 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
7680                                                      const Attr *Attr) {
7681   if (Chain && Chain->isProcessingUpdateRecords()) return;
7682   assert(!WritingAST && "Already writing the AST!");
7683   if (!D->isFromASTFile())
7684     return;
7685 
7686   DeclUpdates[D].push_back(
7687       DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPDeclareTarget, Attr));
7688 }
7689 
7690 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
7691   if (Chain && Chain->isProcessingUpdateRecords()) return;
7692   assert(!WritingAST && "Already writing the AST!");
7693   assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
7694   DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::DeclExported, M));
7695 }
7696 
7697 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
7698                                        const RecordDecl *Record) {
7699   if (Chain && Chain->isProcessingUpdateRecords()) return;
7700   assert(!WritingAST && "Already writing the AST!");
7701   if (!Record->isFromASTFile())
7702     return;
7703   DeclUpdates[Record].push_back(
7704       DeclUpdate(DeclUpdateKind::AddedAttrToRecord, Attr));
7705 }
7706 
7707 void ASTWriter::AddedCXXTemplateSpecialization(
7708     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
7709   assert(!WritingAST && "Already writing the AST!");
7710 
7711   if (!TD->getFirstDecl()->isFromASTFile())
7712     return;
7713   if (Chain && Chain->isProcessingUpdateRecords())
7714     return;
7715 
7716   DeclsToEmitEvenIfUnreferenced.push_back(D);
7717 }
7718 
7719 void ASTWriter::AddedCXXTemplateSpecialization(
7720     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
7721   assert(!WritingAST && "Already writing the AST!");
7722 
7723   if (!TD->getFirstDecl()->isFromASTFile())
7724     return;
7725   if (Chain && Chain->isProcessingUpdateRecords())
7726     return;
7727 
7728   DeclsToEmitEvenIfUnreferenced.push_back(D);
7729 }
7730 
7731 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
7732                                                const FunctionDecl *D) {
7733   assert(!WritingAST && "Already writing the AST!");
7734 
7735   if (!TD->getFirstDecl()->isFromASTFile())
7736     return;
7737   if (Chain && Chain->isProcessingUpdateRecords())
7738     return;
7739 
7740   DeclsToEmitEvenIfUnreferenced.push_back(D);
7741 }
7742 
7743 //===----------------------------------------------------------------------===//
7744 //// OMPClause Serialization
7745 ////===----------------------------------------------------------------------===//
7746 
7747 namespace {
7748 
7749 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
7750   ASTRecordWriter &Record;
7751 
7752 public:
7753   OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
7754 #define GEN_CLANG_CLAUSE_CLASS
7755 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
7756 #include "llvm/Frontend/OpenMP/OMP.inc"
7757   void writeClause(OMPClause *C);
7758   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
7759   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
7760 };
7761 
7762 }
7763 
7764 void ASTRecordWriter::writeOMPClause(OMPClause *C) {
7765   OMPClauseWriter(*this).writeClause(C);
7766 }
7767 
7768 void OMPClauseWriter::writeClause(OMPClause *C) {
7769   Record.push_back(unsigned(C->getClauseKind()));
7770   Visit(C);
7771   Record.AddSourceLocation(C->getBeginLoc());
7772   Record.AddSourceLocation(C->getEndLoc());
7773 }
7774 
7775 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
7776   Record.push_back(uint64_t(C->getCaptureRegion()));
7777   Record.AddStmt(C->getPreInitStmt());
7778 }
7779 
7780 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
7781   VisitOMPClauseWithPreInit(C);
7782   Record.AddStmt(C->getPostUpdateExpr());
7783 }
7784 
7785 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
7786   VisitOMPClauseWithPreInit(C);
7787   Record.push_back(uint64_t(C->getNameModifier()));
7788   Record.AddSourceLocation(C->getNameModifierLoc());
7789   Record.AddSourceLocation(C->getColonLoc());
7790   Record.AddStmt(C->getCondition());
7791   Record.AddSourceLocation(C->getLParenLoc());
7792 }
7793 
7794 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
7795   VisitOMPClauseWithPreInit(C);
7796   Record.AddStmt(C->getCondition());
7797   Record.AddSourceLocation(C->getLParenLoc());
7798 }
7799 
7800 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
7801   VisitOMPClauseWithPreInit(C);
7802   Record.writeEnum(C->getModifier());
7803   Record.AddStmt(C->getNumThreads());
7804   Record.AddSourceLocation(C->getModifierLoc());
7805   Record.AddSourceLocation(C->getLParenLoc());
7806 }
7807 
7808 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
7809   Record.AddStmt(C->getSafelen());
7810   Record.AddSourceLocation(C->getLParenLoc());
7811 }
7812 
7813 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
7814   Record.AddStmt(C->getSimdlen());
7815   Record.AddSourceLocation(C->getLParenLoc());
7816 }
7817 
7818 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
7819   Record.push_back(C->getNumSizes());
7820   for (Expr *Size : C->getSizesRefs())
7821     Record.AddStmt(Size);
7822   Record.AddSourceLocation(C->getLParenLoc());
7823 }
7824 
7825 void OMPClauseWriter::VisitOMPPermutationClause(OMPPermutationClause *C) {
7826   Record.push_back(C->getNumLoops());
7827   for (Expr *Size : C->getArgsRefs())
7828     Record.AddStmt(Size);
7829   Record.AddSourceLocation(C->getLParenLoc());
7830 }
7831 
7832 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
7833 
7834 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
7835   Record.AddStmt(C->getFactor());
7836   Record.AddSourceLocation(C->getLParenLoc());
7837 }
7838 
7839 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
7840   Record.AddStmt(C->getAllocator());
7841   Record.AddSourceLocation(C->getLParenLoc());
7842 }
7843 
7844 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
7845   Record.AddStmt(C->getNumForLoops());
7846   Record.AddSourceLocation(C->getLParenLoc());
7847 }
7848 
7849 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
7850   Record.AddStmt(C->getEventHandler());
7851   Record.AddSourceLocation(C->getLParenLoc());
7852 }
7853 
7854 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
7855   Record.push_back(unsigned(C->getDefaultKind()));
7856   Record.AddSourceLocation(C->getLParenLoc());
7857   Record.AddSourceLocation(C->getDefaultKindKwLoc());
7858 }
7859 
7860 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
7861   Record.push_back(unsigned(C->getProcBindKind()));
7862   Record.AddSourceLocation(C->getLParenLoc());
7863   Record.AddSourceLocation(C->getProcBindKindKwLoc());
7864 }
7865 
7866 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
7867   VisitOMPClauseWithPreInit(C);
7868   Record.push_back(C->getScheduleKind());
7869   Record.push_back(C->getFirstScheduleModifier());
7870   Record.push_back(C->getSecondScheduleModifier());
7871   Record.AddStmt(C->getChunkSize());
7872   Record.AddSourceLocation(C->getLParenLoc());
7873   Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
7874   Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
7875   Record.AddSourceLocation(C->getScheduleKindLoc());
7876   Record.AddSourceLocation(C->getCommaLoc());
7877 }
7878 
7879 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
7880   Record.push_back(C->getLoopNumIterations().size());
7881   Record.AddStmt(C->getNumForLoops());
7882   for (Expr *NumIter : C->getLoopNumIterations())
7883     Record.AddStmt(NumIter);
7884   for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
7885     Record.AddStmt(C->getLoopCounter(I));
7886   Record.AddSourceLocation(C->getLParenLoc());
7887 }
7888 
7889 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
7890 
7891 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
7892 
7893 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
7894 
7895 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
7896 
7897 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
7898 
7899 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
7900   Record.push_back(C->isExtended() ? 1 : 0);
7901   if (C->isExtended()) {
7902     Record.AddSourceLocation(C->getLParenLoc());
7903     Record.AddSourceLocation(C->getArgumentLoc());
7904     Record.writeEnum(C->getDependencyKind());
7905   }
7906 }
7907 
7908 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
7909 
7910 void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
7911 
7912 // Save the parameter of fail clause.
7913 void OMPClauseWriter::VisitOMPFailClause(OMPFailClause *C) {
7914   Record.AddSourceLocation(C->getLParenLoc());
7915   Record.AddSourceLocation(C->getFailParameterLoc());
7916   Record.writeEnum(C->getFailParameter());
7917 }
7918 
7919 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
7920 
7921 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
7922 
7923 void OMPClauseWriter::VisitOMPAbsentClause(OMPAbsentClause *C) {
7924   Record.push_back(static_cast<uint64_t>(C->getDirectiveKinds().size()));
7925   Record.AddSourceLocation(C->getLParenLoc());
7926   for (auto K : C->getDirectiveKinds()) {
7927     Record.writeEnum(K);
7928   }
7929 }
7930 
7931 void OMPClauseWriter::VisitOMPHoldsClause(OMPHoldsClause *C) {
7932   Record.AddStmt(C->getExpr());
7933   Record.AddSourceLocation(C->getLParenLoc());
7934 }
7935 
7936 void OMPClauseWriter::VisitOMPContainsClause(OMPContainsClause *C) {
7937   Record.push_back(static_cast<uint64_t>(C->getDirectiveKinds().size()));
7938   Record.AddSourceLocation(C->getLParenLoc());
7939   for (auto K : C->getDirectiveKinds()) {
7940     Record.writeEnum(K);
7941   }
7942 }
7943 
7944 void OMPClauseWriter::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
7945 
7946 void OMPClauseWriter::VisitOMPNoOpenMPRoutinesClause(
7947     OMPNoOpenMPRoutinesClause *) {}
7948 
7949 void OMPClauseWriter::VisitOMPNoOpenMPConstructsClause(
7950     OMPNoOpenMPConstructsClause *) {}
7951 
7952 void OMPClauseWriter::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
7953 
7954 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
7955 
7956 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
7957 
7958 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
7959 
7960 void OMPClauseWriter::VisitOMPWeakClause(OMPWeakClause *) {}
7961 
7962 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
7963 
7964 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
7965 
7966 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
7967 
7968 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
7969   Record.push_back(C->varlist_size());
7970   for (Expr *VE : C->varlist())
7971     Record.AddStmt(VE);
7972   Record.writeBool(C->getIsTarget());
7973   Record.writeBool(C->getIsTargetSync());
7974   Record.AddSourceLocation(C->getLParenLoc());
7975   Record.AddSourceLocation(C->getVarLoc());
7976 }
7977 
7978 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
7979   Record.AddStmt(C->getInteropVar());
7980   Record.AddSourceLocation(C->getLParenLoc());
7981   Record.AddSourceLocation(C->getVarLoc());
7982 }
7983 
7984 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
7985   Record.AddStmt(C->getInteropVar());
7986   Record.AddSourceLocation(C->getLParenLoc());
7987   Record.AddSourceLocation(C->getVarLoc());
7988 }
7989 
7990 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
7991   VisitOMPClauseWithPreInit(C);
7992   Record.AddStmt(C->getCondition());
7993   Record.AddSourceLocation(C->getLParenLoc());
7994 }
7995 
7996 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
7997   VisitOMPClauseWithPreInit(C);
7998   Record.AddStmt(C->getCondition());
7999   Record.AddSourceLocation(C->getLParenLoc());
8000 }
8001 
8002 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
8003   VisitOMPClauseWithPreInit(C);
8004   Record.AddStmt(C->getThreadID());
8005   Record.AddSourceLocation(C->getLParenLoc());
8006 }
8007 
8008 void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
8009   Record.AddStmt(C->getAlignment());
8010   Record.AddSourceLocation(C->getLParenLoc());
8011 }
8012 
8013 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
8014   Record.push_back(C->varlist_size());
8015   Record.AddSourceLocation(C->getLParenLoc());
8016   for (auto *VE : C->varlist()) {
8017     Record.AddStmt(VE);
8018   }
8019   for (auto *VE : C->private_copies()) {
8020     Record.AddStmt(VE);
8021   }
8022 }
8023 
8024 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
8025   Record.push_back(C->varlist_size());
8026   VisitOMPClauseWithPreInit(C);
8027   Record.AddSourceLocation(C->getLParenLoc());
8028   for (auto *VE : C->varlist()) {
8029     Record.AddStmt(VE);
8030   }
8031   for (auto *VE : C->private_copies()) {
8032     Record.AddStmt(VE);
8033   }
8034   for (auto *VE : C->inits()) {
8035     Record.AddStmt(VE);
8036   }
8037 }
8038 
8039 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
8040   Record.push_back(C->varlist_size());
8041   VisitOMPClauseWithPostUpdate(C);
8042   Record.AddSourceLocation(C->getLParenLoc());
8043   Record.writeEnum(C->getKind());
8044   Record.AddSourceLocation(C->getKindLoc());
8045   Record.AddSourceLocation(C->getColonLoc());
8046   for (auto *VE : C->varlist())
8047     Record.AddStmt(VE);
8048   for (auto *E : C->private_copies())
8049     Record.AddStmt(E);
8050   for (auto *E : C->source_exprs())
8051     Record.AddStmt(E);
8052   for (auto *E : C->destination_exprs())
8053     Record.AddStmt(E);
8054   for (auto *E : C->assignment_ops())
8055     Record.AddStmt(E);
8056 }
8057 
8058 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
8059   Record.push_back(C->varlist_size());
8060   Record.AddSourceLocation(C->getLParenLoc());
8061   for (auto *VE : C->varlist())
8062     Record.AddStmt(VE);
8063 }
8064 
8065 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
8066   Record.push_back(C->varlist_size());
8067   Record.writeEnum(C->getModifier());
8068   VisitOMPClauseWithPostUpdate(C);
8069   Record.AddSourceLocation(C->getLParenLoc());
8070   Record.AddSourceLocation(C->getModifierLoc());
8071   Record.AddSourceLocation(C->getColonLoc());
8072   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8073   Record.AddDeclarationNameInfo(C->getNameInfo());
8074   for (auto *VE : C->varlist())
8075     Record.AddStmt(VE);
8076   for (auto *VE : C->privates())
8077     Record.AddStmt(VE);
8078   for (auto *E : C->lhs_exprs())
8079     Record.AddStmt(E);
8080   for (auto *E : C->rhs_exprs())
8081     Record.AddStmt(E);
8082   for (auto *E : C->reduction_ops())
8083     Record.AddStmt(E);
8084   if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
8085     for (auto *E : C->copy_ops())
8086       Record.AddStmt(E);
8087     for (auto *E : C->copy_array_temps())
8088       Record.AddStmt(E);
8089     for (auto *E : C->copy_array_elems())
8090       Record.AddStmt(E);
8091   }
8092   auto PrivateFlags = C->private_var_reduction_flags();
8093   Record.push_back(std::distance(PrivateFlags.begin(), PrivateFlags.end()));
8094   for (bool Flag : PrivateFlags)
8095     Record.push_back(Flag);
8096 }
8097 
8098 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
8099   Record.push_back(C->varlist_size());
8100   VisitOMPClauseWithPostUpdate(C);
8101   Record.AddSourceLocation(C->getLParenLoc());
8102   Record.AddSourceLocation(C->getColonLoc());
8103   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8104   Record.AddDeclarationNameInfo(C->getNameInfo());
8105   for (auto *VE : C->varlist())
8106     Record.AddStmt(VE);
8107   for (auto *VE : C->privates())
8108     Record.AddStmt(VE);
8109   for (auto *E : C->lhs_exprs())
8110     Record.AddStmt(E);
8111   for (auto *E : C->rhs_exprs())
8112     Record.AddStmt(E);
8113   for (auto *E : C->reduction_ops())
8114     Record.AddStmt(E);
8115 }
8116 
8117 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
8118   Record.push_back(C->varlist_size());
8119   VisitOMPClauseWithPostUpdate(C);
8120   Record.AddSourceLocation(C->getLParenLoc());
8121   Record.AddSourceLocation(C->getColonLoc());
8122   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
8123   Record.AddDeclarationNameInfo(C->getNameInfo());
8124   for (auto *VE : C->varlist())
8125     Record.AddStmt(VE);
8126   for (auto *VE : C->privates())
8127     Record.AddStmt(VE);
8128   for (auto *E : C->lhs_exprs())
8129     Record.AddStmt(E);
8130   for (auto *E : C->rhs_exprs())
8131     Record.AddStmt(E);
8132   for (auto *E : C->reduction_ops())
8133     Record.AddStmt(E);
8134   for (auto *E : C->taskgroup_descriptors())
8135     Record.AddStmt(E);
8136 }
8137 
8138 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
8139   Record.push_back(C->varlist_size());
8140   VisitOMPClauseWithPostUpdate(C);
8141   Record.AddSourceLocation(C->getLParenLoc());
8142   Record.AddSourceLocation(C->getColonLoc());
8143   Record.push_back(C->getModifier());
8144   Record.AddSourceLocation(C->getModifierLoc());
8145   for (auto *VE : C->varlist()) {
8146     Record.AddStmt(VE);
8147   }
8148   for (auto *VE : C->privates()) {
8149     Record.AddStmt(VE);
8150   }
8151   for (auto *VE : C->inits()) {
8152     Record.AddStmt(VE);
8153   }
8154   for (auto *VE : C->updates()) {
8155     Record.AddStmt(VE);
8156   }
8157   for (auto *VE : C->finals()) {
8158     Record.AddStmt(VE);
8159   }
8160   Record.AddStmt(C->getStep());
8161   Record.AddStmt(C->getCalcStep());
8162   for (auto *VE : C->used_expressions())
8163     Record.AddStmt(VE);
8164 }
8165 
8166 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
8167   Record.push_back(C->varlist_size());
8168   Record.AddSourceLocation(C->getLParenLoc());
8169   Record.AddSourceLocation(C->getColonLoc());
8170   for (auto *VE : C->varlist())
8171     Record.AddStmt(VE);
8172   Record.AddStmt(C->getAlignment());
8173 }
8174 
8175 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
8176   Record.push_back(C->varlist_size());
8177   Record.AddSourceLocation(C->getLParenLoc());
8178   for (auto *VE : C->varlist())
8179     Record.AddStmt(VE);
8180   for (auto *E : C->source_exprs())
8181     Record.AddStmt(E);
8182   for (auto *E : C->destination_exprs())
8183     Record.AddStmt(E);
8184   for (auto *E : C->assignment_ops())
8185     Record.AddStmt(E);
8186 }
8187 
8188 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
8189   Record.push_back(C->varlist_size());
8190   Record.AddSourceLocation(C->getLParenLoc());
8191   for (auto *VE : C->varlist())
8192     Record.AddStmt(VE);
8193   for (auto *E : C->source_exprs())
8194     Record.AddStmt(E);
8195   for (auto *E : C->destination_exprs())
8196     Record.AddStmt(E);
8197   for (auto *E : C->assignment_ops())
8198     Record.AddStmt(E);
8199 }
8200 
8201 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
8202   Record.push_back(C->varlist_size());
8203   Record.AddSourceLocation(C->getLParenLoc());
8204   for (auto *VE : C->varlist())
8205     Record.AddStmt(VE);
8206 }
8207 
8208 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
8209   Record.AddStmt(C->getDepobj());
8210   Record.AddSourceLocation(C->getLParenLoc());
8211 }
8212 
8213 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
8214   Record.push_back(C->varlist_size());
8215   Record.push_back(C->getNumLoops());
8216   Record.AddSourceLocation(C->getLParenLoc());
8217   Record.AddStmt(C->getModifier());
8218   Record.push_back(C->getDependencyKind());
8219   Record.AddSourceLocation(C->getDependencyLoc());
8220   Record.AddSourceLocation(C->getColonLoc());
8221   Record.AddSourceLocation(C->getOmpAllMemoryLoc());
8222   for (auto *VE : C->varlist())
8223     Record.AddStmt(VE);
8224   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
8225     Record.AddStmt(C->getLoopData(I));
8226 }
8227 
8228 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
8229   VisitOMPClauseWithPreInit(C);
8230   Record.writeEnum(C->getModifier());
8231   Record.AddStmt(C->getDevice());
8232   Record.AddSourceLocation(C->getModifierLoc());
8233   Record.AddSourceLocation(C->getLParenLoc());
8234 }
8235 
8236 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
8237   Record.push_back(C->varlist_size());
8238   Record.push_back(C->getUniqueDeclarationsNum());
8239   Record.push_back(C->getTotalComponentListNum());
8240   Record.push_back(C->getTotalComponentsNum());
8241   Record.AddSourceLocation(C->getLParenLoc());
8242   bool HasIteratorModifier = false;
8243   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
8244     Record.push_back(C->getMapTypeModifier(I));
8245     Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
8246     if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
8247       HasIteratorModifier = true;
8248   }
8249   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8250   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8251   Record.push_back(C->getMapType());
8252   Record.AddSourceLocation(C->getMapLoc());
8253   Record.AddSourceLocation(C->getColonLoc());
8254   for (auto *E : C->varlist())
8255     Record.AddStmt(E);
8256   for (auto *E : C->mapperlists())
8257     Record.AddStmt(E);
8258   if (HasIteratorModifier)
8259     Record.AddStmt(C->getIteratorModifier());
8260   for (auto *D : C->all_decls())
8261     Record.AddDeclRef(D);
8262   for (auto N : C->all_num_lists())
8263     Record.push_back(N);
8264   for (auto N : C->all_lists_sizes())
8265     Record.push_back(N);
8266   for (auto &M : C->all_components()) {
8267     Record.AddStmt(M.getAssociatedExpression());
8268     Record.AddDeclRef(M.getAssociatedDeclaration());
8269   }
8270 }
8271 
8272 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
8273   Record.push_back(C->varlist_size());
8274   Record.writeEnum(C->getFirstAllocateModifier());
8275   Record.writeEnum(C->getSecondAllocateModifier());
8276   Record.AddSourceLocation(C->getLParenLoc());
8277   Record.AddSourceLocation(C->getColonLoc());
8278   Record.AddStmt(C->getAllocator());
8279   Record.AddStmt(C->getAlignment());
8280   for (auto *VE : C->varlist())
8281     Record.AddStmt(VE);
8282 }
8283 
8284 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
8285   Record.push_back(C->varlist_size());
8286   VisitOMPClauseWithPreInit(C);
8287   Record.AddSourceLocation(C->getLParenLoc());
8288   for (auto *VE : C->varlist())
8289     Record.AddStmt(VE);
8290 }
8291 
8292 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
8293   Record.push_back(C->varlist_size());
8294   VisitOMPClauseWithPreInit(C);
8295   Record.AddSourceLocation(C->getLParenLoc());
8296   for (auto *VE : C->varlist())
8297     Record.AddStmt(VE);
8298 }
8299 
8300 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
8301   VisitOMPClauseWithPreInit(C);
8302   Record.AddStmt(C->getPriority());
8303   Record.AddSourceLocation(C->getLParenLoc());
8304 }
8305 
8306 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
8307   VisitOMPClauseWithPreInit(C);
8308   Record.writeEnum(C->getModifier());
8309   Record.AddStmt(C->getGrainsize());
8310   Record.AddSourceLocation(C->getModifierLoc());
8311   Record.AddSourceLocation(C->getLParenLoc());
8312 }
8313 
8314 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
8315   VisitOMPClauseWithPreInit(C);
8316   Record.writeEnum(C->getModifier());
8317   Record.AddStmt(C->getNumTasks());
8318   Record.AddSourceLocation(C->getModifierLoc());
8319   Record.AddSourceLocation(C->getLParenLoc());
8320 }
8321 
8322 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
8323   Record.AddStmt(C->getHint());
8324   Record.AddSourceLocation(C->getLParenLoc());
8325 }
8326 
8327 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
8328   VisitOMPClauseWithPreInit(C);
8329   Record.push_back(C->getDistScheduleKind());
8330   Record.AddStmt(C->getChunkSize());
8331   Record.AddSourceLocation(C->getLParenLoc());
8332   Record.AddSourceLocation(C->getDistScheduleKindLoc());
8333   Record.AddSourceLocation(C->getCommaLoc());
8334 }
8335 
8336 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
8337   Record.push_back(C->getDefaultmapKind());
8338   Record.push_back(C->getDefaultmapModifier());
8339   Record.AddSourceLocation(C->getLParenLoc());
8340   Record.AddSourceLocation(C->getDefaultmapModifierLoc());
8341   Record.AddSourceLocation(C->getDefaultmapKindLoc());
8342 }
8343 
8344 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
8345   Record.push_back(C->varlist_size());
8346   Record.push_back(C->getUniqueDeclarationsNum());
8347   Record.push_back(C->getTotalComponentListNum());
8348   Record.push_back(C->getTotalComponentsNum());
8349   Record.AddSourceLocation(C->getLParenLoc());
8350   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8351     Record.push_back(C->getMotionModifier(I));
8352     Record.AddSourceLocation(C->getMotionModifierLoc(I));
8353   }
8354   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8355   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8356   Record.AddSourceLocation(C->getColonLoc());
8357   for (auto *E : C->varlist())
8358     Record.AddStmt(E);
8359   for (auto *E : C->mapperlists())
8360     Record.AddStmt(E);
8361   for (auto *D : C->all_decls())
8362     Record.AddDeclRef(D);
8363   for (auto N : C->all_num_lists())
8364     Record.push_back(N);
8365   for (auto N : C->all_lists_sizes())
8366     Record.push_back(N);
8367   for (auto &M : C->all_components()) {
8368     Record.AddStmt(M.getAssociatedExpression());
8369     Record.writeBool(M.isNonContiguous());
8370     Record.AddDeclRef(M.getAssociatedDeclaration());
8371   }
8372 }
8373 
8374 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
8375   Record.push_back(C->varlist_size());
8376   Record.push_back(C->getUniqueDeclarationsNum());
8377   Record.push_back(C->getTotalComponentListNum());
8378   Record.push_back(C->getTotalComponentsNum());
8379   Record.AddSourceLocation(C->getLParenLoc());
8380   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8381     Record.push_back(C->getMotionModifier(I));
8382     Record.AddSourceLocation(C->getMotionModifierLoc(I));
8383   }
8384   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
8385   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
8386   Record.AddSourceLocation(C->getColonLoc());
8387   for (auto *E : C->varlist())
8388     Record.AddStmt(E);
8389   for (auto *E : C->mapperlists())
8390     Record.AddStmt(E);
8391   for (auto *D : C->all_decls())
8392     Record.AddDeclRef(D);
8393   for (auto N : C->all_num_lists())
8394     Record.push_back(N);
8395   for (auto N : C->all_lists_sizes())
8396     Record.push_back(N);
8397   for (auto &M : C->all_components()) {
8398     Record.AddStmt(M.getAssociatedExpression());
8399     Record.writeBool(M.isNonContiguous());
8400     Record.AddDeclRef(M.getAssociatedDeclaration());
8401   }
8402 }
8403 
8404 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
8405   Record.push_back(C->varlist_size());
8406   Record.push_back(C->getUniqueDeclarationsNum());
8407   Record.push_back(C->getTotalComponentListNum());
8408   Record.push_back(C->getTotalComponentsNum());
8409   Record.AddSourceLocation(C->getLParenLoc());
8410   for (auto *E : C->varlist())
8411     Record.AddStmt(E);
8412   for (auto *VE : C->private_copies())
8413     Record.AddStmt(VE);
8414   for (auto *VE : C->inits())
8415     Record.AddStmt(VE);
8416   for (auto *D : C->all_decls())
8417     Record.AddDeclRef(D);
8418   for (auto N : C->all_num_lists())
8419     Record.push_back(N);
8420   for (auto N : C->all_lists_sizes())
8421     Record.push_back(N);
8422   for (auto &M : C->all_components()) {
8423     Record.AddStmt(M.getAssociatedExpression());
8424     Record.AddDeclRef(M.getAssociatedDeclaration());
8425   }
8426 }
8427 
8428 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
8429   Record.push_back(C->varlist_size());
8430   Record.push_back(C->getUniqueDeclarationsNum());
8431   Record.push_back(C->getTotalComponentListNum());
8432   Record.push_back(C->getTotalComponentsNum());
8433   Record.AddSourceLocation(C->getLParenLoc());
8434   for (auto *E : C->varlist())
8435     Record.AddStmt(E);
8436   for (auto *D : C->all_decls())
8437     Record.AddDeclRef(D);
8438   for (auto N : C->all_num_lists())
8439     Record.push_back(N);
8440   for (auto N : C->all_lists_sizes())
8441     Record.push_back(N);
8442   for (auto &M : C->all_components()) {
8443     Record.AddStmt(M.getAssociatedExpression());
8444     Record.AddDeclRef(M.getAssociatedDeclaration());
8445   }
8446 }
8447 
8448 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8449   Record.push_back(C->varlist_size());
8450   Record.push_back(C->getUniqueDeclarationsNum());
8451   Record.push_back(C->getTotalComponentListNum());
8452   Record.push_back(C->getTotalComponentsNum());
8453   Record.AddSourceLocation(C->getLParenLoc());
8454   for (auto *E : C->varlist())
8455     Record.AddStmt(E);
8456   for (auto *D : C->all_decls())
8457     Record.AddDeclRef(D);
8458   for (auto N : C->all_num_lists())
8459     Record.push_back(N);
8460   for (auto N : C->all_lists_sizes())
8461     Record.push_back(N);
8462   for (auto &M : C->all_components()) {
8463     Record.AddStmt(M.getAssociatedExpression());
8464     Record.AddDeclRef(M.getAssociatedDeclaration());
8465   }
8466 }
8467 
8468 void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
8469   Record.push_back(C->varlist_size());
8470   Record.push_back(C->getUniqueDeclarationsNum());
8471   Record.push_back(C->getTotalComponentListNum());
8472   Record.push_back(C->getTotalComponentsNum());
8473   Record.AddSourceLocation(C->getLParenLoc());
8474   for (auto *E : C->varlist())
8475     Record.AddStmt(E);
8476   for (auto *D : C->all_decls())
8477     Record.AddDeclRef(D);
8478   for (auto N : C->all_num_lists())
8479     Record.push_back(N);
8480   for (auto N : C->all_lists_sizes())
8481     Record.push_back(N);
8482   for (auto &M : C->all_components()) {
8483     Record.AddStmt(M.getAssociatedExpression());
8484     Record.AddDeclRef(M.getAssociatedDeclaration());
8485   }
8486 }
8487 
8488 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
8489 
8490 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
8491     OMPUnifiedSharedMemoryClause *) {}
8492 
8493 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
8494 
8495 void
8496 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
8497 }
8498 
8499 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
8500     OMPAtomicDefaultMemOrderClause *C) {
8501   Record.push_back(C->getAtomicDefaultMemOrderKind());
8502   Record.AddSourceLocation(C->getLParenLoc());
8503   Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
8504 }
8505 
8506 void OMPClauseWriter::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
8507 
8508 void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
8509   Record.push_back(C->getAtKind());
8510   Record.AddSourceLocation(C->getLParenLoc());
8511   Record.AddSourceLocation(C->getAtKindKwLoc());
8512 }
8513 
8514 void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
8515   Record.push_back(C->getSeverityKind());
8516   Record.AddSourceLocation(C->getLParenLoc());
8517   Record.AddSourceLocation(C->getSeverityKindKwLoc());
8518 }
8519 
8520 void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
8521   Record.AddStmt(C->getMessageString());
8522   Record.AddSourceLocation(C->getLParenLoc());
8523 }
8524 
8525 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
8526   Record.push_back(C->varlist_size());
8527   Record.AddSourceLocation(C->getLParenLoc());
8528   for (auto *VE : C->varlist())
8529     Record.AddStmt(VE);
8530   for (auto *E : C->private_refs())
8531     Record.AddStmt(E);
8532 }
8533 
8534 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
8535   Record.push_back(C->varlist_size());
8536   Record.AddSourceLocation(C->getLParenLoc());
8537   for (auto *VE : C->varlist())
8538     Record.AddStmt(VE);
8539 }
8540 
8541 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
8542   Record.push_back(C->varlist_size());
8543   Record.AddSourceLocation(C->getLParenLoc());
8544   for (auto *VE : C->varlist())
8545     Record.AddStmt(VE);
8546 }
8547 
8548 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
8549   Record.writeEnum(C->getKind());
8550   Record.writeEnum(C->getModifier());
8551   Record.AddSourceLocation(C->getLParenLoc());
8552   Record.AddSourceLocation(C->getKindKwLoc());
8553   Record.AddSourceLocation(C->getModifierKwLoc());
8554 }
8555 
8556 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
8557   Record.push_back(C->getNumberOfAllocators());
8558   Record.AddSourceLocation(C->getLParenLoc());
8559   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
8560     OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
8561     Record.AddStmt(Data.Allocator);
8562     Record.AddStmt(Data.AllocatorTraits);
8563     Record.AddSourceLocation(Data.LParenLoc);
8564     Record.AddSourceLocation(Data.RParenLoc);
8565   }
8566 }
8567 
8568 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
8569   Record.push_back(C->varlist_size());
8570   Record.AddSourceLocation(C->getLParenLoc());
8571   Record.AddStmt(C->getModifier());
8572   Record.AddSourceLocation(C->getColonLoc());
8573   for (Expr *E : C->varlist())
8574     Record.AddStmt(E);
8575 }
8576 
8577 void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
8578   Record.writeEnum(C->getBindKind());
8579   Record.AddSourceLocation(C->getLParenLoc());
8580   Record.AddSourceLocation(C->getBindKindLoc());
8581 }
8582 
8583 void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
8584   VisitOMPClauseWithPreInit(C);
8585   Record.AddStmt(C->getSize());
8586   Record.AddSourceLocation(C->getLParenLoc());
8587 }
8588 
8589 void OMPClauseWriter::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
8590   Record.push_back(C->varlist_size());
8591   Record.push_back(C->getNumLoops());
8592   Record.AddSourceLocation(C->getLParenLoc());
8593   Record.push_back(C->getDependenceType());
8594   Record.AddSourceLocation(C->getDependenceLoc());
8595   Record.AddSourceLocation(C->getColonLoc());
8596   for (auto *VE : C->varlist())
8597     Record.AddStmt(VE);
8598   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
8599     Record.AddStmt(C->getLoopData(I));
8600 }
8601 
8602 void OMPClauseWriter::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
8603   Record.AddAttributes(C->getAttrs());
8604   Record.AddSourceLocation(C->getBeginLoc());
8605   Record.AddSourceLocation(C->getLParenLoc());
8606   Record.AddSourceLocation(C->getEndLoc());
8607 }
8608 
8609 void OMPClauseWriter::VisitOMPXBareClause(OMPXBareClause *C) {}
8610 
8611 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
8612   writeUInt32(TI->Sets.size());
8613   for (const auto &Set : TI->Sets) {
8614     writeEnum(Set.Kind);
8615     writeUInt32(Set.Selectors.size());
8616     for (const auto &Selector : Set.Selectors) {
8617       writeEnum(Selector.Kind);
8618       writeBool(Selector.ScoreOrCondition);
8619       if (Selector.ScoreOrCondition)
8620         writeExprRef(Selector.ScoreOrCondition);
8621       writeUInt32(Selector.Properties.size());
8622       for (const auto &Property : Selector.Properties)
8623         writeEnum(Property.Kind);
8624     }
8625   }
8626 }
8627 
8628 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
8629   if (!Data)
8630     return;
8631   writeUInt32(Data->getNumClauses());
8632   writeUInt32(Data->getNumChildren());
8633   writeBool(Data->hasAssociatedStmt());
8634   for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
8635     writeOMPClause(Data->getClauses()[I]);
8636   if (Data->hasAssociatedStmt())
8637     AddStmt(Data->getAssociatedStmt());
8638   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
8639     AddStmt(Data->getChildren()[I]);
8640 }
8641 
8642 void ASTRecordWriter::writeOpenACCVarList(const OpenACCClauseWithVarList *C) {
8643   writeUInt32(C->getVarList().size());
8644   for (Expr *E : C->getVarList())
8645     AddStmt(E);
8646 }
8647 
8648 void ASTRecordWriter::writeOpenACCIntExprList(ArrayRef<Expr *> Exprs) {
8649   writeUInt32(Exprs.size());
8650   for (Expr *E : Exprs)
8651     AddStmt(E);
8652 }
8653 
8654 void ASTRecordWriter::writeOpenACCClause(const OpenACCClause *C) {
8655   writeEnum(C->getClauseKind());
8656   writeSourceLocation(C->getBeginLoc());
8657   writeSourceLocation(C->getEndLoc());
8658 
8659   switch (C->getClauseKind()) {
8660   case OpenACCClauseKind::Default: {
8661     const auto *DC = cast<OpenACCDefaultClause>(C);
8662     writeSourceLocation(DC->getLParenLoc());
8663     writeEnum(DC->getDefaultClauseKind());
8664     return;
8665   }
8666   case OpenACCClauseKind::If: {
8667     const auto *IC = cast<OpenACCIfClause>(C);
8668     writeSourceLocation(IC->getLParenLoc());
8669     AddStmt(const_cast<Expr*>(IC->getConditionExpr()));
8670     return;
8671   }
8672   case OpenACCClauseKind::Self: {
8673     const auto *SC = cast<OpenACCSelfClause>(C);
8674     writeSourceLocation(SC->getLParenLoc());
8675     writeBool(SC->isConditionExprClause());
8676     if (SC->isConditionExprClause()) {
8677       writeBool(SC->hasConditionExpr());
8678       if (SC->hasConditionExpr())
8679         AddStmt(const_cast<Expr *>(SC->getConditionExpr()));
8680     } else {
8681       writeUInt32(SC->getVarList().size());
8682       for (Expr *E : SC->getVarList())
8683         AddStmt(E);
8684     }
8685     return;
8686   }
8687   case OpenACCClauseKind::NumGangs: {
8688     const auto *NGC = cast<OpenACCNumGangsClause>(C);
8689     writeSourceLocation(NGC->getLParenLoc());
8690     writeUInt32(NGC->getIntExprs().size());
8691     for (Expr *E : NGC->getIntExprs())
8692       AddStmt(E);
8693     return;
8694   }
8695   case OpenACCClauseKind::DeviceNum: {
8696     const auto *DNC = cast<OpenACCDeviceNumClause>(C);
8697     writeSourceLocation(DNC->getLParenLoc());
8698     AddStmt(const_cast<Expr*>(DNC->getIntExpr()));
8699     return;
8700   }
8701   case OpenACCClauseKind::DefaultAsync: {
8702     const auto *DAC = cast<OpenACCDefaultAsyncClause>(C);
8703     writeSourceLocation(DAC->getLParenLoc());
8704     AddStmt(const_cast<Expr *>(DAC->getIntExpr()));
8705     return;
8706   }
8707   case OpenACCClauseKind::NumWorkers: {
8708     const auto *NWC = cast<OpenACCNumWorkersClause>(C);
8709     writeSourceLocation(NWC->getLParenLoc());
8710     AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
8711     return;
8712   }
8713   case OpenACCClauseKind::VectorLength: {
8714     const auto *NWC = cast<OpenACCVectorLengthClause>(C);
8715     writeSourceLocation(NWC->getLParenLoc());
8716     AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
8717     return;
8718   }
8719   case OpenACCClauseKind::Private: {
8720     const auto *PC = cast<OpenACCPrivateClause>(C);
8721     writeSourceLocation(PC->getLParenLoc());
8722     writeOpenACCVarList(PC);
8723     return;
8724   }
8725   case OpenACCClauseKind::Host: {
8726     const auto *HC = cast<OpenACCHostClause>(C);
8727     writeSourceLocation(HC->getLParenLoc());
8728     writeOpenACCVarList(HC);
8729     return;
8730   }
8731   case OpenACCClauseKind::Device: {
8732     const auto *DC = cast<OpenACCDeviceClause>(C);
8733     writeSourceLocation(DC->getLParenLoc());
8734     writeOpenACCVarList(DC);
8735     return;
8736   }
8737   case OpenACCClauseKind::FirstPrivate: {
8738     const auto *FPC = cast<OpenACCFirstPrivateClause>(C);
8739     writeSourceLocation(FPC->getLParenLoc());
8740     writeOpenACCVarList(FPC);
8741     return;
8742   }
8743   case OpenACCClauseKind::Attach: {
8744     const auto *AC = cast<OpenACCAttachClause>(C);
8745     writeSourceLocation(AC->getLParenLoc());
8746     writeOpenACCVarList(AC);
8747     return;
8748   }
8749   case OpenACCClauseKind::Detach: {
8750     const auto *DC = cast<OpenACCDetachClause>(C);
8751     writeSourceLocation(DC->getLParenLoc());
8752     writeOpenACCVarList(DC);
8753     return;
8754   }
8755   case OpenACCClauseKind::Delete: {
8756     const auto *DC = cast<OpenACCDeleteClause>(C);
8757     writeSourceLocation(DC->getLParenLoc());
8758     writeOpenACCVarList(DC);
8759     return;
8760   }
8761   case OpenACCClauseKind::UseDevice: {
8762     const auto *UDC = cast<OpenACCUseDeviceClause>(C);
8763     writeSourceLocation(UDC->getLParenLoc());
8764     writeOpenACCVarList(UDC);
8765     return;
8766   }
8767   case OpenACCClauseKind::DevicePtr: {
8768     const auto *DPC = cast<OpenACCDevicePtrClause>(C);
8769     writeSourceLocation(DPC->getLParenLoc());
8770     writeOpenACCVarList(DPC);
8771     return;
8772   }
8773   case OpenACCClauseKind::NoCreate: {
8774     const auto *NCC = cast<OpenACCNoCreateClause>(C);
8775     writeSourceLocation(NCC->getLParenLoc());
8776     writeOpenACCVarList(NCC);
8777     return;
8778   }
8779   case OpenACCClauseKind::Present: {
8780     const auto *PC = cast<OpenACCPresentClause>(C);
8781     writeSourceLocation(PC->getLParenLoc());
8782     writeOpenACCVarList(PC);
8783     return;
8784   }
8785   case OpenACCClauseKind::Copy:
8786   case OpenACCClauseKind::PCopy:
8787   case OpenACCClauseKind::PresentOrCopy: {
8788     const auto *CC = cast<OpenACCCopyClause>(C);
8789     writeSourceLocation(CC->getLParenLoc());
8790     writeEnum(CC->getModifierList());
8791     writeOpenACCVarList(CC);
8792     return;
8793   }
8794   case OpenACCClauseKind::CopyIn:
8795   case OpenACCClauseKind::PCopyIn:
8796   case OpenACCClauseKind::PresentOrCopyIn: {
8797     const auto *CIC = cast<OpenACCCopyInClause>(C);
8798     writeSourceLocation(CIC->getLParenLoc());
8799     writeEnum(CIC->getModifierList());
8800     writeOpenACCVarList(CIC);
8801     return;
8802   }
8803   case OpenACCClauseKind::CopyOut:
8804   case OpenACCClauseKind::PCopyOut:
8805   case OpenACCClauseKind::PresentOrCopyOut: {
8806     const auto *COC = cast<OpenACCCopyOutClause>(C);
8807     writeSourceLocation(COC->getLParenLoc());
8808     writeEnum(COC->getModifierList());
8809     writeOpenACCVarList(COC);
8810     return;
8811   }
8812   case OpenACCClauseKind::Create:
8813   case OpenACCClauseKind::PCreate:
8814   case OpenACCClauseKind::PresentOrCreate: {
8815     const auto *CC = cast<OpenACCCreateClause>(C);
8816     writeSourceLocation(CC->getLParenLoc());
8817     writeEnum(CC->getModifierList());
8818     writeOpenACCVarList(CC);
8819     return;
8820   }
8821   case OpenACCClauseKind::Async: {
8822     const auto *AC = cast<OpenACCAsyncClause>(C);
8823     writeSourceLocation(AC->getLParenLoc());
8824     writeBool(AC->hasIntExpr());
8825     if (AC->hasIntExpr())
8826       AddStmt(const_cast<Expr*>(AC->getIntExpr()));
8827     return;
8828   }
8829   case OpenACCClauseKind::Wait: {
8830     const auto *WC = cast<OpenACCWaitClause>(C);
8831     writeSourceLocation(WC->getLParenLoc());
8832     writeBool(WC->getDevNumExpr());
8833     if (Expr *DNE = WC->getDevNumExpr())
8834       AddStmt(DNE);
8835     writeSourceLocation(WC->getQueuesLoc());
8836 
8837     writeOpenACCIntExprList(WC->getQueueIdExprs());
8838     return;
8839   }
8840   case OpenACCClauseKind::DeviceType:
8841   case OpenACCClauseKind::DType: {
8842     const auto *DTC = cast<OpenACCDeviceTypeClause>(C);
8843     writeSourceLocation(DTC->getLParenLoc());
8844     writeUInt32(DTC->getArchitectures().size());
8845     for (const DeviceTypeArgument &Arg : DTC->getArchitectures()) {
8846       writeBool(Arg.getIdentifierInfo());
8847       if (Arg.getIdentifierInfo())
8848         AddIdentifierRef(Arg.getIdentifierInfo());
8849       writeSourceLocation(Arg.getLoc());
8850     }
8851     return;
8852   }
8853   case OpenACCClauseKind::Reduction: {
8854     const auto *RC = cast<OpenACCReductionClause>(C);
8855     writeSourceLocation(RC->getLParenLoc());
8856     writeEnum(RC->getReductionOp());
8857     writeOpenACCVarList(RC);
8858     return;
8859   }
8860   case OpenACCClauseKind::Seq:
8861   case OpenACCClauseKind::Independent:
8862   case OpenACCClauseKind::NoHost:
8863   case OpenACCClauseKind::Auto:
8864   case OpenACCClauseKind::Finalize:
8865   case OpenACCClauseKind::IfPresent:
8866     // Nothing to do here, there is no additional information beyond the
8867     // begin/end loc and clause kind.
8868     return;
8869   case OpenACCClauseKind::Collapse: {
8870     const auto *CC = cast<OpenACCCollapseClause>(C);
8871     writeSourceLocation(CC->getLParenLoc());
8872     writeBool(CC->hasForce());
8873     AddStmt(const_cast<Expr *>(CC->getLoopCount()));
8874     return;
8875   }
8876   case OpenACCClauseKind::Tile: {
8877     const auto *TC = cast<OpenACCTileClause>(C);
8878     writeSourceLocation(TC->getLParenLoc());
8879     writeUInt32(TC->getSizeExprs().size());
8880     for (Expr *E : TC->getSizeExprs())
8881       AddStmt(E);
8882     return;
8883   }
8884   case OpenACCClauseKind::Gang: {
8885     const auto *GC = cast<OpenACCGangClause>(C);
8886     writeSourceLocation(GC->getLParenLoc());
8887     writeUInt32(GC->getNumExprs());
8888     for (unsigned I = 0; I < GC->getNumExprs(); ++I) {
8889       writeEnum(GC->getExpr(I).first);
8890       AddStmt(const_cast<Expr *>(GC->getExpr(I).second));
8891     }
8892     return;
8893   }
8894   case OpenACCClauseKind::Worker: {
8895     const auto *WC = cast<OpenACCWorkerClause>(C);
8896     writeSourceLocation(WC->getLParenLoc());
8897     writeBool(WC->hasIntExpr());
8898     if (WC->hasIntExpr())
8899       AddStmt(const_cast<Expr *>(WC->getIntExpr()));
8900     return;
8901   }
8902   case OpenACCClauseKind::Vector: {
8903     const auto *VC = cast<OpenACCVectorClause>(C);
8904     writeSourceLocation(VC->getLParenLoc());
8905     writeBool(VC->hasIntExpr());
8906     if (VC->hasIntExpr())
8907       AddStmt(const_cast<Expr *>(VC->getIntExpr()));
8908     return;
8909   }
8910   case OpenACCClauseKind::Link: {
8911     const auto *LC = cast<OpenACCLinkClause>(C);
8912     writeSourceLocation(LC->getLParenLoc());
8913     writeOpenACCVarList(LC);
8914     return;
8915   }
8916   case OpenACCClauseKind::DeviceResident: {
8917     const auto *DRC = cast<OpenACCDeviceResidentClause>(C);
8918     writeSourceLocation(DRC->getLParenLoc());
8919     writeOpenACCVarList(DRC);
8920     return;
8921   }
8922 
8923   case OpenACCClauseKind::Bind: {
8924     const auto *BC = cast<OpenACCBindClause>(C);
8925     writeSourceLocation(BC->getLParenLoc());
8926     writeBool(BC->isStringArgument());
8927     if (BC->isStringArgument())
8928       AddStmt(const_cast<StringLiteral *>(BC->getStringArgument()));
8929     else
8930       AddIdentifierRef(BC->getIdentifierArgument());
8931 
8932     return;
8933   }
8934   case OpenACCClauseKind::Invalid:
8935   case OpenACCClauseKind::Shortloop:
8936     llvm_unreachable("Clause serialization not yet implemented");
8937   }
8938   llvm_unreachable("Invalid Clause Kind");
8939 }
8940 
8941 void ASTRecordWriter::writeOpenACCClauseList(
8942     ArrayRef<const OpenACCClause *> Clauses) {
8943   for (const OpenACCClause *Clause : Clauses)
8944     writeOpenACCClause(Clause);
8945 }
8946 void ASTRecordWriter::AddOpenACCRoutineDeclAttr(
8947     const OpenACCRoutineDeclAttr *A) {
8948   // We have to write the size so that the reader can do a resize. Unlike the
8949   // Decl version of this, we can't count on trailing storage to get this right.
8950   writeUInt32(A->Clauses.size());
8951   writeOpenACCClauseList(A->Clauses);
8952 }
8953