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