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