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