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