[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / Serialization / ASTWriter.cpp
blob5ac3030a7a6760205f051c8dab2a1d14d9545c35
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.
11 //===----------------------------------------------------------------------===//
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "MultiOnDiskHashTable.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTUnresolvedSet.h"
18 #include "clang/AST/AbstractTypeWriter.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclContextInternals.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/RawCommentList.h"
34 #include "clang/AST/TemplateName.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLocVisitor.h"
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/DiagnosticOptions.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/FileSystemOptions.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/ObjCRuntime.h"
47 #include "clang/Basic/OpenCLOptions.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/SourceManagerInternals.h"
51 #include "clang/Basic/Specifiers.h"
52 #include "clang/Basic/TargetInfo.h"
53 #include "clang/Basic/TargetOptions.h"
54 #include "clang/Basic/Version.h"
55 #include "clang/Lex/HeaderSearch.h"
56 #include "clang/Lex/HeaderSearchOptions.h"
57 #include "clang/Lex/MacroInfo.h"
58 #include "clang/Lex/ModuleMap.h"
59 #include "clang/Lex/PreprocessingRecord.h"
60 #include "clang/Lex/Preprocessor.h"
61 #include "clang/Lex/PreprocessorOptions.h"
62 #include "clang/Lex/Token.h"
63 #include "clang/Sema/IdentifierResolver.h"
64 #include "clang/Sema/ObjCMethodList.h"
65 #include "clang/Sema/Sema.h"
66 #include "clang/Sema/Weak.h"
67 #include "clang/Serialization/ASTBitCodes.h"
68 #include "clang/Serialization/ASTReader.h"
69 #include "clang/Serialization/ASTRecordWriter.h"
70 #include "clang/Serialization/InMemoryModuleCache.h"
71 #include "clang/Serialization/ModuleFile.h"
72 #include "clang/Serialization/ModuleFileExtension.h"
73 #include "clang/Serialization/SerializationDiagnostic.h"
74 #include "llvm/ADT/APFloat.h"
75 #include "llvm/ADT/APInt.h"
76 #include "llvm/ADT/APSInt.h"
77 #include "llvm/ADT/ArrayRef.h"
78 #include "llvm/ADT/DenseMap.h"
79 #include "llvm/ADT/Hashing.h"
80 #include "llvm/ADT/PointerIntPair.h"
81 #include "llvm/ADT/STLExtras.h"
82 #include "llvm/ADT/ScopeExit.h"
83 #include "llvm/ADT/SmallPtrSet.h"
84 #include "llvm/ADT/SmallString.h"
85 #include "llvm/ADT/SmallVector.h"
86 #include "llvm/ADT/StringMap.h"
87 #include "llvm/ADT/StringRef.h"
88 #include "llvm/Bitstream/BitCodes.h"
89 #include "llvm/Bitstream/BitstreamWriter.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/Compression.h"
92 #include "llvm/Support/DJB.h"
93 #include "llvm/Support/Endian.h"
94 #include "llvm/Support/EndianStream.h"
95 #include "llvm/Support/Error.h"
96 #include "llvm/Support/ErrorHandling.h"
97 #include "llvm/Support/LEB128.h"
98 #include "llvm/Support/MemoryBuffer.h"
99 #include "llvm/Support/OnDiskHashTable.h"
100 #include "llvm/Support/Path.h"
101 #include "llvm/Support/SHA1.h"
102 #include "llvm/Support/TimeProfiler.h"
103 #include "llvm/Support/VersionTuple.h"
104 #include "llvm/Support/raw_ostream.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <cstring>
110 #include <ctime>
111 #include <limits>
112 #include <memory>
113 #include <optional>
114 #include <queue>
115 #include <tuple>
116 #include <utility>
117 #include <vector>
119 using namespace clang;
120 using namespace clang::serialization;
122 template <typename T, typename Allocator>
123 static StringRef bytes(const std::vector<T, Allocator> &v) {
124 if (v.empty()) return StringRef();
125 return StringRef(reinterpret_cast<const char*>(&v[0]),
126 sizeof(T) * v.size());
129 template <typename T>
130 static StringRef bytes(const SmallVectorImpl<T> &v) {
131 return StringRef(reinterpret_cast<const char*>(v.data()),
132 sizeof(T) * v.size());
135 static std::string bytes(const std::vector<bool> &V) {
136 std::string Str;
137 Str.reserve(V.size() / 8);
138 for (unsigned I = 0, E = V.size(); I < E;) {
139 char Byte = 0;
140 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
141 Byte |= V[I] << Bit;
142 Str += Byte;
144 return Str;
147 //===----------------------------------------------------------------------===//
148 // Type serialization
149 //===----------------------------------------------------------------------===//
151 static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
152 switch (id) {
153 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
154 case Type::CLASS_ID: return TYPE_##CODE_ID;
155 #include "clang/Serialization/TypeBitCodes.def"
156 case Type::Builtin:
157 llvm_unreachable("shouldn't be serializing a builtin type this way");
159 llvm_unreachable("bad type kind");
162 namespace {
164 std::set<const FileEntry *> GetAffectingModuleMaps(const Preprocessor &PP,
165 Module *RootModule) {
166 std::set<const FileEntry *> ModuleMaps{};
167 std::set<const Module *> ProcessedModules;
168 SmallVector<const Module *> ModulesToProcess{RootModule};
170 const HeaderSearch &HS = PP.getHeaderSearchInfo();
172 SmallVector<const FileEntry *, 16> FilesByUID;
173 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
175 if (FilesByUID.size() > HS.header_file_size())
176 FilesByUID.resize(HS.header_file_size());
178 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
179 const FileEntry *File = FilesByUID[UID];
180 if (!File)
181 continue;
183 const HeaderFileInfo *HFI =
184 HS.getExistingFileInfo(File, /*WantExternal*/ false);
185 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
186 continue;
188 for (const auto &KH : HS.findResolvedModulesForHeader(File)) {
189 if (!KH.getModule())
190 continue;
191 ModulesToProcess.push_back(KH.getModule());
195 const ModuleMap &MM = HS.getModuleMap();
196 SourceManager &SourceMgr = PP.getSourceManager();
198 auto ForIncludeChain = [&](FileEntryRef F,
199 llvm::function_ref<void(FileEntryRef)> CB) {
200 CB(F);
201 FileID FID = SourceMgr.translateFile(F);
202 SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
203 while (Loc.isValid()) {
204 FID = SourceMgr.getFileID(Loc);
205 CB(*SourceMgr.getFileEntryRefForID(FID));
206 Loc = SourceMgr.getIncludeLoc(FID);
210 auto ProcessModuleOnce = [&](const Module *M) {
211 for (const Module *Mod = M; Mod; Mod = Mod->Parent)
212 if (ProcessedModules.insert(Mod).second)
213 if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
214 ForIncludeChain(*ModuleMapFile, [&](FileEntryRef F) {
215 ModuleMaps.insert(F);
219 for (const Module *CurrentModule : ModulesToProcess) {
220 ProcessModuleOnce(CurrentModule);
221 for (const Module *ImportedModule : CurrentModule->Imports)
222 ProcessModuleOnce(ImportedModule);
223 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
224 ProcessModuleOnce(UndeclaredModule);
227 return ModuleMaps;
230 class ASTTypeWriter {
231 ASTWriter &Writer;
232 ASTWriter::RecordData Record;
233 ASTRecordWriter BasicWriter;
235 public:
236 ASTTypeWriter(ASTWriter &Writer)
237 : Writer(Writer), BasicWriter(Writer, Record) {}
239 uint64_t write(QualType T) {
240 if (T.hasLocalNonFastQualifiers()) {
241 Qualifiers Qs = T.getLocalQualifiers();
242 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
243 BasicWriter.writeQualifiers(Qs);
244 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
247 const Type *typePtr = T.getTypePtr();
248 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
249 atw.write(typePtr);
250 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
251 /*abbrev*/ 0);
255 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
256 using LocSeq = SourceLocationSequence;
258 ASTRecordWriter &Record;
259 LocSeq *Seq;
261 void addSourceLocation(SourceLocation Loc) {
262 Record.AddSourceLocation(Loc, Seq);
264 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
266 public:
267 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
268 : Record(Record), Seq(Seq) {}
270 #define ABSTRACT_TYPELOC(CLASS, PARENT)
271 #define TYPELOC(CLASS, PARENT) \
272 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
273 #include "clang/AST/TypeLocNodes.def"
275 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
276 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
279 } // namespace
281 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
282 // nothing to do
285 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
286 addSourceLocation(TL.getBuiltinLoc());
287 if (TL.needsExtraLocalData()) {
288 Record.push_back(TL.getWrittenTypeSpec());
289 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
290 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
291 Record.push_back(TL.hasModeAttr());
295 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
296 addSourceLocation(TL.getNameLoc());
299 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
300 addSourceLocation(TL.getStarLoc());
303 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
304 // nothing to do
307 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
308 // nothing to do
311 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
312 addSourceLocation(TL.getCaretLoc());
315 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
316 addSourceLocation(TL.getAmpLoc());
319 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
320 addSourceLocation(TL.getAmpAmpLoc());
323 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
324 addSourceLocation(TL.getStarLoc());
325 Record.AddTypeSourceInfo(TL.getClassTInfo());
328 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
329 addSourceLocation(TL.getLBracketLoc());
330 addSourceLocation(TL.getRBracketLoc());
331 Record.push_back(TL.getSizeExpr() ? 1 : 0);
332 if (TL.getSizeExpr())
333 Record.AddStmt(TL.getSizeExpr());
336 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
337 VisitArrayTypeLoc(TL);
340 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
341 VisitArrayTypeLoc(TL);
344 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
345 VisitArrayTypeLoc(TL);
348 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
349 DependentSizedArrayTypeLoc TL) {
350 VisitArrayTypeLoc(TL);
353 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
354 DependentAddressSpaceTypeLoc TL) {
355 addSourceLocation(TL.getAttrNameLoc());
356 SourceRange range = TL.getAttrOperandParensRange();
357 addSourceLocation(range.getBegin());
358 addSourceLocation(range.getEnd());
359 Record.AddStmt(TL.getAttrExprOperand());
362 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
363 DependentSizedExtVectorTypeLoc TL) {
364 addSourceLocation(TL.getNameLoc());
367 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
368 addSourceLocation(TL.getNameLoc());
371 void TypeLocWriter::VisitDependentVectorTypeLoc(
372 DependentVectorTypeLoc TL) {
373 addSourceLocation(TL.getNameLoc());
376 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
377 addSourceLocation(TL.getNameLoc());
380 void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
381 addSourceLocation(TL.getAttrNameLoc());
382 SourceRange range = TL.getAttrOperandParensRange();
383 addSourceLocation(range.getBegin());
384 addSourceLocation(range.getEnd());
385 Record.AddStmt(TL.getAttrRowOperand());
386 Record.AddStmt(TL.getAttrColumnOperand());
389 void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
390 DependentSizedMatrixTypeLoc TL) {
391 addSourceLocation(TL.getAttrNameLoc());
392 SourceRange range = TL.getAttrOperandParensRange();
393 addSourceLocation(range.getBegin());
394 addSourceLocation(range.getEnd());
395 Record.AddStmt(TL.getAttrRowOperand());
396 Record.AddStmt(TL.getAttrColumnOperand());
399 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
400 addSourceLocation(TL.getLocalRangeBegin());
401 addSourceLocation(TL.getLParenLoc());
402 addSourceLocation(TL.getRParenLoc());
403 addSourceRange(TL.getExceptionSpecRange());
404 addSourceLocation(TL.getLocalRangeEnd());
405 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
406 Record.AddDeclRef(TL.getParam(i));
409 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
410 VisitFunctionTypeLoc(TL);
413 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
414 VisitFunctionTypeLoc(TL);
417 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
418 addSourceLocation(TL.getNameLoc());
421 void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
422 addSourceLocation(TL.getNameLoc());
425 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
426 addSourceLocation(TL.getNameLoc());
429 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
430 if (TL.getNumProtocols()) {
431 addSourceLocation(TL.getProtocolLAngleLoc());
432 addSourceLocation(TL.getProtocolRAngleLoc());
434 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
435 addSourceLocation(TL.getProtocolLoc(i));
438 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
439 addSourceLocation(TL.getTypeofLoc());
440 addSourceLocation(TL.getLParenLoc());
441 addSourceLocation(TL.getRParenLoc());
444 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
445 addSourceLocation(TL.getTypeofLoc());
446 addSourceLocation(TL.getLParenLoc());
447 addSourceLocation(TL.getRParenLoc());
448 Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
451 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
452 addSourceLocation(TL.getDecltypeLoc());
453 addSourceLocation(TL.getRParenLoc());
456 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
457 addSourceLocation(TL.getKWLoc());
458 addSourceLocation(TL.getLParenLoc());
459 addSourceLocation(TL.getRParenLoc());
460 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
463 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
464 addSourceLocation(TL.getNameLoc());
465 Record.push_back(TL.isConstrained());
466 if (TL.isConstrained()) {
467 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
468 addSourceLocation(TL.getTemplateKWLoc());
469 addSourceLocation(TL.getConceptNameLoc());
470 Record.AddDeclRef(TL.getFoundDecl());
471 addSourceLocation(TL.getLAngleLoc());
472 addSourceLocation(TL.getRAngleLoc());
473 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
474 Record.AddTemplateArgumentLocInfo(
475 TL.getTypePtr()->getTypeConstraintArguments()[I].getKind(),
476 TL.getArgLocInfo(I));
478 Record.push_back(TL.isDecltypeAuto());
479 if (TL.isDecltypeAuto())
480 addSourceLocation(TL.getRParenLoc());
483 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
484 DeducedTemplateSpecializationTypeLoc TL) {
485 addSourceLocation(TL.getTemplateNameLoc());
488 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
489 addSourceLocation(TL.getNameLoc());
492 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
493 addSourceLocation(TL.getNameLoc());
496 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
497 Record.AddAttr(TL.getAttr());
500 void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
501 // Nothing to do.
504 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
505 addSourceLocation(TL.getNameLoc());
508 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
509 SubstTemplateTypeParmTypeLoc TL) {
510 addSourceLocation(TL.getNameLoc());
513 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
514 SubstTemplateTypeParmPackTypeLoc TL) {
515 addSourceLocation(TL.getNameLoc());
518 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
519 TemplateSpecializationTypeLoc TL) {
520 addSourceLocation(TL.getTemplateKeywordLoc());
521 addSourceLocation(TL.getTemplateNameLoc());
522 addSourceLocation(TL.getLAngleLoc());
523 addSourceLocation(TL.getRAngleLoc());
524 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
525 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
526 TL.getArgLoc(i).getLocInfo());
529 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
530 addSourceLocation(TL.getLParenLoc());
531 addSourceLocation(TL.getRParenLoc());
534 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
535 addSourceLocation(TL.getExpansionLoc());
538 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
539 addSourceLocation(TL.getElaboratedKeywordLoc());
540 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
543 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
544 addSourceLocation(TL.getNameLoc());
547 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
548 addSourceLocation(TL.getElaboratedKeywordLoc());
549 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
550 addSourceLocation(TL.getNameLoc());
553 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
554 DependentTemplateSpecializationTypeLoc TL) {
555 addSourceLocation(TL.getElaboratedKeywordLoc());
556 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
557 addSourceLocation(TL.getTemplateKeywordLoc());
558 addSourceLocation(TL.getTemplateNameLoc());
559 addSourceLocation(TL.getLAngleLoc());
560 addSourceLocation(TL.getRAngleLoc());
561 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
562 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
563 TL.getArgLoc(I).getLocInfo());
566 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
567 addSourceLocation(TL.getEllipsisLoc());
570 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
571 addSourceLocation(TL.getNameLoc());
572 addSourceLocation(TL.getNameEndLoc());
575 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
576 Record.push_back(TL.hasBaseTypeAsWritten());
577 addSourceLocation(TL.getTypeArgsLAngleLoc());
578 addSourceLocation(TL.getTypeArgsRAngleLoc());
579 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
580 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
581 addSourceLocation(TL.getProtocolLAngleLoc());
582 addSourceLocation(TL.getProtocolRAngleLoc());
583 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
584 addSourceLocation(TL.getProtocolLoc(i));
587 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
588 addSourceLocation(TL.getStarLoc());
591 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
592 addSourceLocation(TL.getKWLoc());
593 addSourceLocation(TL.getLParenLoc());
594 addSourceLocation(TL.getRParenLoc());
597 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
598 addSourceLocation(TL.getKWLoc());
601 void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
602 addSourceLocation(TL.getNameLoc());
604 void TypeLocWriter::VisitDependentBitIntTypeLoc(
605 clang::DependentBitIntTypeLoc TL) {
606 addSourceLocation(TL.getNameLoc());
609 void ASTWriter::WriteTypeAbbrevs() {
610 using namespace llvm;
612 std::shared_ptr<BitCodeAbbrev> Abv;
614 // Abbreviation for TYPE_EXT_QUAL
615 Abv = std::make_shared<BitCodeAbbrev>();
616 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
617 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
618 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
619 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
622 //===----------------------------------------------------------------------===//
623 // ASTWriter Implementation
624 //===----------------------------------------------------------------------===//
626 static void EmitBlockID(unsigned ID, const char *Name,
627 llvm::BitstreamWriter &Stream,
628 ASTWriter::RecordDataImpl &Record) {
629 Record.clear();
630 Record.push_back(ID);
631 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
633 // Emit the block name if present.
634 if (!Name || Name[0] == 0)
635 return;
636 Record.clear();
637 while (*Name)
638 Record.push_back(*Name++);
639 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
642 static void EmitRecordID(unsigned ID, const char *Name,
643 llvm::BitstreamWriter &Stream,
644 ASTWriter::RecordDataImpl &Record) {
645 Record.clear();
646 Record.push_back(ID);
647 while (*Name)
648 Record.push_back(*Name++);
649 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
652 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
653 ASTWriter::RecordDataImpl &Record) {
654 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
655 RECORD(STMT_STOP);
656 RECORD(STMT_NULL_PTR);
657 RECORD(STMT_REF_PTR);
658 RECORD(STMT_NULL);
659 RECORD(STMT_COMPOUND);
660 RECORD(STMT_CASE);
661 RECORD(STMT_DEFAULT);
662 RECORD(STMT_LABEL);
663 RECORD(STMT_ATTRIBUTED);
664 RECORD(STMT_IF);
665 RECORD(STMT_SWITCH);
666 RECORD(STMT_WHILE);
667 RECORD(STMT_DO);
668 RECORD(STMT_FOR);
669 RECORD(STMT_GOTO);
670 RECORD(STMT_INDIRECT_GOTO);
671 RECORD(STMT_CONTINUE);
672 RECORD(STMT_BREAK);
673 RECORD(STMT_RETURN);
674 RECORD(STMT_DECL);
675 RECORD(STMT_GCCASM);
676 RECORD(STMT_MSASM);
677 RECORD(EXPR_PREDEFINED);
678 RECORD(EXPR_DECL_REF);
679 RECORD(EXPR_INTEGER_LITERAL);
680 RECORD(EXPR_FIXEDPOINT_LITERAL);
681 RECORD(EXPR_FLOATING_LITERAL);
682 RECORD(EXPR_IMAGINARY_LITERAL);
683 RECORD(EXPR_STRING_LITERAL);
684 RECORD(EXPR_CHARACTER_LITERAL);
685 RECORD(EXPR_PAREN);
686 RECORD(EXPR_PAREN_LIST);
687 RECORD(EXPR_UNARY_OPERATOR);
688 RECORD(EXPR_SIZEOF_ALIGN_OF);
689 RECORD(EXPR_ARRAY_SUBSCRIPT);
690 RECORD(EXPR_CALL);
691 RECORD(EXPR_MEMBER);
692 RECORD(EXPR_BINARY_OPERATOR);
693 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
694 RECORD(EXPR_CONDITIONAL_OPERATOR);
695 RECORD(EXPR_IMPLICIT_CAST);
696 RECORD(EXPR_CSTYLE_CAST);
697 RECORD(EXPR_COMPOUND_LITERAL);
698 RECORD(EXPR_EXT_VECTOR_ELEMENT);
699 RECORD(EXPR_INIT_LIST);
700 RECORD(EXPR_DESIGNATED_INIT);
701 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
702 RECORD(EXPR_IMPLICIT_VALUE_INIT);
703 RECORD(EXPR_NO_INIT);
704 RECORD(EXPR_VA_ARG);
705 RECORD(EXPR_ADDR_LABEL);
706 RECORD(EXPR_STMT);
707 RECORD(EXPR_CHOOSE);
708 RECORD(EXPR_GNU_NULL);
709 RECORD(EXPR_SHUFFLE_VECTOR);
710 RECORD(EXPR_BLOCK);
711 RECORD(EXPR_GENERIC_SELECTION);
712 RECORD(EXPR_OBJC_STRING_LITERAL);
713 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
714 RECORD(EXPR_OBJC_ARRAY_LITERAL);
715 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
716 RECORD(EXPR_OBJC_ENCODE);
717 RECORD(EXPR_OBJC_SELECTOR_EXPR);
718 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
719 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
720 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
721 RECORD(EXPR_OBJC_KVC_REF_EXPR);
722 RECORD(EXPR_OBJC_MESSAGE_EXPR);
723 RECORD(STMT_OBJC_FOR_COLLECTION);
724 RECORD(STMT_OBJC_CATCH);
725 RECORD(STMT_OBJC_FINALLY);
726 RECORD(STMT_OBJC_AT_TRY);
727 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
728 RECORD(STMT_OBJC_AT_THROW);
729 RECORD(EXPR_OBJC_BOOL_LITERAL);
730 RECORD(STMT_CXX_CATCH);
731 RECORD(STMT_CXX_TRY);
732 RECORD(STMT_CXX_FOR_RANGE);
733 RECORD(EXPR_CXX_OPERATOR_CALL);
734 RECORD(EXPR_CXX_MEMBER_CALL);
735 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
736 RECORD(EXPR_CXX_CONSTRUCT);
737 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
738 RECORD(EXPR_CXX_STATIC_CAST);
739 RECORD(EXPR_CXX_DYNAMIC_CAST);
740 RECORD(EXPR_CXX_REINTERPRET_CAST);
741 RECORD(EXPR_CXX_CONST_CAST);
742 RECORD(EXPR_CXX_ADDRSPACE_CAST);
743 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
744 RECORD(EXPR_USER_DEFINED_LITERAL);
745 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
746 RECORD(EXPR_CXX_BOOL_LITERAL);
747 RECORD(EXPR_CXX_PAREN_LIST_INIT);
748 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
749 RECORD(EXPR_CXX_TYPEID_EXPR);
750 RECORD(EXPR_CXX_TYPEID_TYPE);
751 RECORD(EXPR_CXX_THIS);
752 RECORD(EXPR_CXX_THROW);
753 RECORD(EXPR_CXX_DEFAULT_ARG);
754 RECORD(EXPR_CXX_DEFAULT_INIT);
755 RECORD(EXPR_CXX_BIND_TEMPORARY);
756 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
757 RECORD(EXPR_CXX_NEW);
758 RECORD(EXPR_CXX_DELETE);
759 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
760 RECORD(EXPR_EXPR_WITH_CLEANUPS);
761 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
762 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
763 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
764 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
765 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
766 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
767 RECORD(EXPR_CXX_NOEXCEPT);
768 RECORD(EXPR_OPAQUE_VALUE);
769 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
770 RECORD(EXPR_TYPE_TRAIT);
771 RECORD(EXPR_ARRAY_TYPE_TRAIT);
772 RECORD(EXPR_PACK_EXPANSION);
773 RECORD(EXPR_SIZEOF_PACK);
774 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
775 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
776 RECORD(EXPR_FUNCTION_PARM_PACK);
777 RECORD(EXPR_MATERIALIZE_TEMPORARY);
778 RECORD(EXPR_CUDA_KERNEL_CALL);
779 RECORD(EXPR_CXX_UUIDOF_EXPR);
780 RECORD(EXPR_CXX_UUIDOF_TYPE);
781 RECORD(EXPR_LAMBDA);
782 #undef RECORD
785 void ASTWriter::WriteBlockInfoBlock() {
786 RecordData Record;
787 Stream.EnterBlockInfoBlock();
789 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
790 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
792 // Control Block.
793 BLOCK(CONTROL_BLOCK);
794 RECORD(METADATA);
795 RECORD(MODULE_NAME);
796 RECORD(MODULE_DIRECTORY);
797 RECORD(MODULE_MAP_FILE);
798 RECORD(IMPORTS);
799 RECORD(ORIGINAL_FILE);
800 RECORD(ORIGINAL_FILE_ID);
801 RECORD(INPUT_FILE_OFFSETS);
803 BLOCK(OPTIONS_BLOCK);
804 RECORD(LANGUAGE_OPTIONS);
805 RECORD(TARGET_OPTIONS);
806 RECORD(FILE_SYSTEM_OPTIONS);
807 RECORD(HEADER_SEARCH_OPTIONS);
808 RECORD(PREPROCESSOR_OPTIONS);
810 BLOCK(INPUT_FILES_BLOCK);
811 RECORD(INPUT_FILE);
812 RECORD(INPUT_FILE_HASH);
814 // AST Top-Level Block.
815 BLOCK(AST_BLOCK);
816 RECORD(TYPE_OFFSET);
817 RECORD(DECL_OFFSET);
818 RECORD(IDENTIFIER_OFFSET);
819 RECORD(IDENTIFIER_TABLE);
820 RECORD(EAGERLY_DESERIALIZED_DECLS);
821 RECORD(MODULAR_CODEGEN_DECLS);
822 RECORD(SPECIAL_TYPES);
823 RECORD(STATISTICS);
824 RECORD(TENTATIVE_DEFINITIONS);
825 RECORD(SELECTOR_OFFSETS);
826 RECORD(METHOD_POOL);
827 RECORD(PP_COUNTER_VALUE);
828 RECORD(SOURCE_LOCATION_OFFSETS);
829 RECORD(SOURCE_LOCATION_PRELOADS);
830 RECORD(EXT_VECTOR_DECLS);
831 RECORD(UNUSED_FILESCOPED_DECLS);
832 RECORD(PPD_ENTITIES_OFFSETS);
833 RECORD(VTABLE_USES);
834 RECORD(PPD_SKIPPED_RANGES);
835 RECORD(REFERENCED_SELECTOR_POOL);
836 RECORD(TU_UPDATE_LEXICAL);
837 RECORD(SEMA_DECL_REFS);
838 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
839 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
840 RECORD(UPDATE_VISIBLE);
841 RECORD(DECL_UPDATE_OFFSETS);
842 RECORD(DECL_UPDATES);
843 RECORD(CUDA_SPECIAL_DECL_REFS);
844 RECORD(HEADER_SEARCH_TABLE);
845 RECORD(FP_PRAGMA_OPTIONS);
846 RECORD(OPENCL_EXTENSIONS);
847 RECORD(OPENCL_EXTENSION_TYPES);
848 RECORD(OPENCL_EXTENSION_DECLS);
849 RECORD(DELEGATING_CTORS);
850 RECORD(KNOWN_NAMESPACES);
851 RECORD(MODULE_OFFSET_MAP);
852 RECORD(SOURCE_MANAGER_LINE_TABLE);
853 RECORD(OBJC_CATEGORIES_MAP);
854 RECORD(FILE_SORTED_DECLS);
855 RECORD(IMPORTED_MODULES);
856 RECORD(OBJC_CATEGORIES);
857 RECORD(MACRO_OFFSET);
858 RECORD(INTERESTING_IDENTIFIERS);
859 RECORD(UNDEFINED_BUT_USED);
860 RECORD(LATE_PARSED_TEMPLATE);
861 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
862 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
863 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
864 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
865 RECORD(DELETE_EXPRS_TO_ANALYZE);
866 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
867 RECORD(PP_CONDITIONAL_STACK);
868 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
869 RECORD(PP_INCLUDED_FILES);
870 RECORD(PP_ASSUME_NONNULL_LOC);
872 // SourceManager Block.
873 BLOCK(SOURCE_MANAGER_BLOCK);
874 RECORD(SM_SLOC_FILE_ENTRY);
875 RECORD(SM_SLOC_BUFFER_ENTRY);
876 RECORD(SM_SLOC_BUFFER_BLOB);
877 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
878 RECORD(SM_SLOC_EXPANSION_ENTRY);
880 // Preprocessor Block.
881 BLOCK(PREPROCESSOR_BLOCK);
882 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
883 RECORD(PP_MACRO_FUNCTION_LIKE);
884 RECORD(PP_MACRO_OBJECT_LIKE);
885 RECORD(PP_MODULE_MACRO);
886 RECORD(PP_TOKEN);
888 // Submodule Block.
889 BLOCK(SUBMODULE_BLOCK);
890 RECORD(SUBMODULE_METADATA);
891 RECORD(SUBMODULE_DEFINITION);
892 RECORD(SUBMODULE_UMBRELLA_HEADER);
893 RECORD(SUBMODULE_HEADER);
894 RECORD(SUBMODULE_TOPHEADER);
895 RECORD(SUBMODULE_UMBRELLA_DIR);
896 RECORD(SUBMODULE_IMPORTS);
897 RECORD(SUBMODULE_AFFECTING_MODULES);
898 RECORD(SUBMODULE_EXPORTS);
899 RECORD(SUBMODULE_REQUIRES);
900 RECORD(SUBMODULE_EXCLUDED_HEADER);
901 RECORD(SUBMODULE_LINK_LIBRARY);
902 RECORD(SUBMODULE_CONFIG_MACRO);
903 RECORD(SUBMODULE_CONFLICT);
904 RECORD(SUBMODULE_PRIVATE_HEADER);
905 RECORD(SUBMODULE_TEXTUAL_HEADER);
906 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
907 RECORD(SUBMODULE_INITIALIZERS);
908 RECORD(SUBMODULE_EXPORT_AS);
910 // Comments Block.
911 BLOCK(COMMENTS_BLOCK);
912 RECORD(COMMENTS_RAW_COMMENT);
914 // Decls and Types block.
915 BLOCK(DECLTYPES_BLOCK);
916 RECORD(TYPE_EXT_QUAL);
917 RECORD(TYPE_COMPLEX);
918 RECORD(TYPE_POINTER);
919 RECORD(TYPE_BLOCK_POINTER);
920 RECORD(TYPE_LVALUE_REFERENCE);
921 RECORD(TYPE_RVALUE_REFERENCE);
922 RECORD(TYPE_MEMBER_POINTER);
923 RECORD(TYPE_CONSTANT_ARRAY);
924 RECORD(TYPE_INCOMPLETE_ARRAY);
925 RECORD(TYPE_VARIABLE_ARRAY);
926 RECORD(TYPE_VECTOR);
927 RECORD(TYPE_EXT_VECTOR);
928 RECORD(TYPE_FUNCTION_NO_PROTO);
929 RECORD(TYPE_FUNCTION_PROTO);
930 RECORD(TYPE_TYPEDEF);
931 RECORD(TYPE_TYPEOF_EXPR);
932 RECORD(TYPE_TYPEOF);
933 RECORD(TYPE_RECORD);
934 RECORD(TYPE_ENUM);
935 RECORD(TYPE_OBJC_INTERFACE);
936 RECORD(TYPE_OBJC_OBJECT_POINTER);
937 RECORD(TYPE_DECLTYPE);
938 RECORD(TYPE_ELABORATED);
939 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
940 RECORD(TYPE_UNRESOLVED_USING);
941 RECORD(TYPE_INJECTED_CLASS_NAME);
942 RECORD(TYPE_OBJC_OBJECT);
943 RECORD(TYPE_TEMPLATE_TYPE_PARM);
944 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
945 RECORD(TYPE_DEPENDENT_NAME);
946 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
947 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
948 RECORD(TYPE_PAREN);
949 RECORD(TYPE_MACRO_QUALIFIED);
950 RECORD(TYPE_PACK_EXPANSION);
951 RECORD(TYPE_ATTRIBUTED);
952 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
953 RECORD(TYPE_AUTO);
954 RECORD(TYPE_UNARY_TRANSFORM);
955 RECORD(TYPE_ATOMIC);
956 RECORD(TYPE_DECAYED);
957 RECORD(TYPE_ADJUSTED);
958 RECORD(TYPE_OBJC_TYPE_PARAM);
959 RECORD(LOCAL_REDECLARATIONS);
960 RECORD(DECL_TYPEDEF);
961 RECORD(DECL_TYPEALIAS);
962 RECORD(DECL_ENUM);
963 RECORD(DECL_RECORD);
964 RECORD(DECL_ENUM_CONSTANT);
965 RECORD(DECL_FUNCTION);
966 RECORD(DECL_OBJC_METHOD);
967 RECORD(DECL_OBJC_INTERFACE);
968 RECORD(DECL_OBJC_PROTOCOL);
969 RECORD(DECL_OBJC_IVAR);
970 RECORD(DECL_OBJC_AT_DEFS_FIELD);
971 RECORD(DECL_OBJC_CATEGORY);
972 RECORD(DECL_OBJC_CATEGORY_IMPL);
973 RECORD(DECL_OBJC_IMPLEMENTATION);
974 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
975 RECORD(DECL_OBJC_PROPERTY);
976 RECORD(DECL_OBJC_PROPERTY_IMPL);
977 RECORD(DECL_FIELD);
978 RECORD(DECL_MS_PROPERTY);
979 RECORD(DECL_VAR);
980 RECORD(DECL_IMPLICIT_PARAM);
981 RECORD(DECL_PARM_VAR);
982 RECORD(DECL_FILE_SCOPE_ASM);
983 RECORD(DECL_BLOCK);
984 RECORD(DECL_CONTEXT_LEXICAL);
985 RECORD(DECL_CONTEXT_VISIBLE);
986 RECORD(DECL_NAMESPACE);
987 RECORD(DECL_NAMESPACE_ALIAS);
988 RECORD(DECL_USING);
989 RECORD(DECL_USING_SHADOW);
990 RECORD(DECL_USING_DIRECTIVE);
991 RECORD(DECL_UNRESOLVED_USING_VALUE);
992 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
993 RECORD(DECL_LINKAGE_SPEC);
994 RECORD(DECL_CXX_RECORD);
995 RECORD(DECL_CXX_METHOD);
996 RECORD(DECL_CXX_CONSTRUCTOR);
997 RECORD(DECL_CXX_DESTRUCTOR);
998 RECORD(DECL_CXX_CONVERSION);
999 RECORD(DECL_ACCESS_SPEC);
1000 RECORD(DECL_FRIEND);
1001 RECORD(DECL_FRIEND_TEMPLATE);
1002 RECORD(DECL_CLASS_TEMPLATE);
1003 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1004 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1005 RECORD(DECL_VAR_TEMPLATE);
1006 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1007 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1008 RECORD(DECL_FUNCTION_TEMPLATE);
1009 RECORD(DECL_TEMPLATE_TYPE_PARM);
1010 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1011 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1012 RECORD(DECL_CONCEPT);
1013 RECORD(DECL_REQUIRES_EXPR_BODY);
1014 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1015 RECORD(DECL_STATIC_ASSERT);
1016 RECORD(DECL_CXX_BASE_SPECIFIERS);
1017 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1018 RECORD(DECL_INDIRECTFIELD);
1019 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1020 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1021 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1022 RECORD(DECL_IMPORT);
1023 RECORD(DECL_OMP_THREADPRIVATE);
1024 RECORD(DECL_EMPTY);
1025 RECORD(DECL_OBJC_TYPE_PARAM);
1026 RECORD(DECL_OMP_CAPTUREDEXPR);
1027 RECORD(DECL_PRAGMA_COMMENT);
1028 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1029 RECORD(DECL_OMP_DECLARE_REDUCTION);
1030 RECORD(DECL_OMP_ALLOCATE);
1031 RECORD(DECL_HLSL_BUFFER);
1033 // Statements and Exprs can occur in the Decls and Types block.
1034 AddStmtsExprs(Stream, Record);
1036 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1037 RECORD(PPD_MACRO_EXPANSION);
1038 RECORD(PPD_MACRO_DEFINITION);
1039 RECORD(PPD_INCLUSION_DIRECTIVE);
1041 // Decls and Types block.
1042 BLOCK(EXTENSION_BLOCK);
1043 RECORD(EXTENSION_METADATA);
1045 BLOCK(UNHASHED_CONTROL_BLOCK);
1046 RECORD(SIGNATURE);
1047 RECORD(AST_BLOCK_HASH);
1048 RECORD(DIAGNOSTIC_OPTIONS);
1049 RECORD(HEADER_SEARCH_PATHS);
1050 RECORD(DIAG_PRAGMA_MAPPINGS);
1052 #undef RECORD
1053 #undef BLOCK
1054 Stream.ExitBlock();
1057 /// Prepares a path for being written to an AST file by converting it
1058 /// to an absolute path and removing nested './'s.
1060 /// \return \c true if the path was changed.
1061 static bool cleanPathForOutput(FileManager &FileMgr,
1062 SmallVectorImpl<char> &Path) {
1063 bool Changed = FileMgr.makeAbsolutePath(Path);
1064 return Changed | llvm::sys::path::remove_dots(Path);
1067 /// Adjusts the given filename to only write out the portion of the
1068 /// filename that is not part of the system root directory.
1070 /// \param Filename the file name to adjust.
1072 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1073 /// the returned filename will be adjusted by this root directory.
1075 /// \returns either the original filename (if it needs no adjustment) or the
1076 /// adjusted filename (which points into the @p Filename parameter).
1077 static const char *
1078 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1079 assert(Filename && "No file name to adjust?");
1081 if (BaseDir.empty())
1082 return Filename;
1084 // Verify that the filename and the system root have the same prefix.
1085 unsigned Pos = 0;
1086 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1087 if (Filename[Pos] != BaseDir[Pos])
1088 return Filename; // Prefixes don't match.
1090 // We hit the end of the filename before we hit the end of the system root.
1091 if (!Filename[Pos])
1092 return Filename;
1094 // If there's not a path separator at the end of the base directory nor
1095 // immediately after it, then this isn't within the base directory.
1096 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1097 if (!llvm::sys::path::is_separator(BaseDir.back()))
1098 return Filename;
1099 } else {
1100 // If the file name has a '/' at the current position, skip over the '/'.
1101 // We distinguish relative paths from absolute paths by the
1102 // absence of '/' at the beginning of relative paths.
1104 // FIXME: This is wrong. We distinguish them by asking if the path is
1105 // absolute, which isn't the same thing. And there might be multiple '/'s
1106 // in a row. Use a better mechanism to indicate whether we have emitted an
1107 // absolute or relative path.
1108 ++Pos;
1111 return Filename + Pos;
1114 std::pair<ASTFileSignature, ASTFileSignature>
1115 ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
1116 llvm::SHA1 Hasher;
1117 Hasher.update(ASTBlockBytes);
1118 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1120 // Add the remaining bytes (i.e. bytes before the unhashed control block that
1121 // are not part of the AST block).
1122 Hasher.update(
1123 AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1124 Hasher.update(
1125 AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1126 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1128 return std::make_pair(ASTBlockHash, Signature);
1131 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1132 ASTContext &Context) {
1133 using namespace llvm;
1135 // Flush first to prepare the PCM hash (signature).
1136 Stream.FlushToWord();
1137 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1139 // Enter the block and prepare to write records.
1140 RecordData Record;
1141 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1143 // For implicit modules, write the hash of the PCM as its signature.
1144 ASTFileSignature Signature;
1145 if (WritingModule &&
1146 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1147 ASTFileSignature ASTBlockHash;
1148 auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1149 auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1150 std::tie(ASTBlockHash, Signature) = createSignature(
1151 StringRef(Buffer.begin(), StartOfUnhashedControl),
1152 StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1154 Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1155 Stream.EmitRecord(AST_BLOCK_HASH, Record);
1156 Record.clear();
1157 Record.append(Signature.begin(), Signature.end());
1158 Stream.EmitRecord(SIGNATURE, Record);
1159 Record.clear();
1162 // Diagnostic options.
1163 const auto &Diags = Context.getDiagnostics();
1164 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1165 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1166 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1167 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1168 #include "clang/Basic/DiagnosticOptions.def"
1169 Record.push_back(DiagOpts.Warnings.size());
1170 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1171 AddString(DiagOpts.Warnings[I], Record);
1172 Record.push_back(DiagOpts.Remarks.size());
1173 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1174 AddString(DiagOpts.Remarks[I], Record);
1175 // Note: we don't serialize the log or serialization file names, because they
1176 // are generally transient files and will almost always be overridden.
1177 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1178 Record.clear();
1180 // Header search paths.
1181 Record.clear();
1182 const HeaderSearchOptions &HSOpts =
1183 PP.getHeaderSearchInfo().getHeaderSearchOpts();
1185 // Include entries.
1186 Record.push_back(HSOpts.UserEntries.size());
1187 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1188 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1189 AddString(Entry.Path, Record);
1190 Record.push_back(static_cast<unsigned>(Entry.Group));
1191 Record.push_back(Entry.IsFramework);
1192 Record.push_back(Entry.IgnoreSysRoot);
1195 // System header prefixes.
1196 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1197 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1198 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1199 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1202 // VFS overlay files.
1203 Record.push_back(HSOpts.VFSOverlayFiles.size());
1204 for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1205 AddString(VFSOverlayFile, Record);
1207 Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
1209 // Write out the diagnostic/pragma mappings.
1210 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1212 // Header search entry usage.
1213 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1214 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1215 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1218 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1220 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1221 HSEntryUsage.size()};
1222 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1225 // Leave the options block.
1226 Stream.ExitBlock();
1227 return Signature;
1230 /// Write the control block.
1231 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1232 StringRef isysroot) {
1233 using namespace llvm;
1235 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1236 RecordData Record;
1238 // Metadata
1239 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1240 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1241 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1242 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1243 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1244 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1245 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1246 // Standard C++ module
1247 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1248 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1249 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1250 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1251 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1252 assert((!WritingModule || isysroot.empty()) &&
1253 "writing module as a relocatable PCH?");
1255 RecordData::value_type Record[] = {METADATA,
1256 VERSION_MAJOR,
1257 VERSION_MINOR,
1258 CLANG_VERSION_MAJOR,
1259 CLANG_VERSION_MINOR,
1260 !isysroot.empty(),
1261 isWritingStdCXXNamedModules(),
1262 IncludeTimestamps,
1263 ASTHasCompilerErrors};
1264 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1265 getClangFullRepositoryVersion());
1268 if (WritingModule) {
1269 // Module name
1270 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1271 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1273 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1274 RecordData::value_type Record[] = {MODULE_NAME};
1275 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1278 if (WritingModule && WritingModule->Directory) {
1279 SmallString<128> BaseDir;
1280 if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1281 // Use the current working directory as the base path for all inputs.
1282 auto CWD =
1283 Context.getSourceManager().getFileManager().getOptionalDirectoryRef(
1284 ".");
1285 BaseDir.assign(CWD->getName());
1286 } else {
1287 BaseDir.assign(WritingModule->Directory->getName());
1289 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1291 // If the home of the module is the current working directory, then we
1292 // want to pick up the cwd of the build process loading the module, not
1293 // our cwd, when we load this module.
1294 if (!PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd &&
1295 (!PP.getHeaderSearchInfo()
1296 .getHeaderSearchOpts()
1297 .ModuleMapFileHomeIsCwd ||
1298 WritingModule->Directory->getName() != StringRef("."))) {
1299 // Module directory.
1300 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1301 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1303 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1305 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1306 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1309 // Write out all other paths relative to the base directory if possible.
1310 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1311 } else if (!isysroot.empty()) {
1312 // Write out paths relative to the sysroot if possible.
1313 BaseDirectory = std::string(isysroot);
1316 // Module map file
1317 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1318 Record.clear();
1320 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1321 AddPath(WritingModule->PresumedModuleMapFile.empty()
1322 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1323 : StringRef(WritingModule->PresumedModuleMapFile),
1324 Record);
1326 // Additional module map files.
1327 if (auto *AdditionalModMaps =
1328 Map.getAdditionalModuleMapFiles(WritingModule)) {
1329 Record.push_back(AdditionalModMaps->size());
1330 SmallVector<const FileEntry *, 1> ModMaps(AdditionalModMaps->begin(),
1331 AdditionalModMaps->end());
1332 llvm::sort(ModMaps, [](const FileEntry *A, const FileEntry *B) {
1333 return A->getName() < B->getName();
1335 for (const FileEntry *F : ModMaps)
1336 AddPath(F->getName(), Record);
1337 } else {
1338 Record.push_back(0);
1341 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1344 // Imports
1345 if (Chain) {
1346 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1347 Record.clear();
1349 for (ModuleFile &M : Mgr) {
1350 // Skip modules that weren't directly imported.
1351 if (!M.isDirectlyImported())
1352 continue;
1354 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1355 Record.push_back(M.StandardCXXModule);
1356 AddSourceLocation(M.ImportLoc, Record);
1358 // If we have calculated signature, there is no need to store
1359 // the size or timestamp.
1360 Record.push_back(M.Signature ? 0 : M.File->getSize());
1361 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1363 llvm::append_range(Record, M.Signature);
1365 AddString(M.ModuleName, Record);
1366 AddPath(M.FileName, Record);
1368 Stream.EmitRecord(IMPORTS, Record);
1371 // Write the options block.
1372 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1374 // Language options.
1375 Record.clear();
1376 const LangOptions &LangOpts = Context.getLangOpts();
1377 #define LANGOPT(Name, Bits, Default, Description) \
1378 Record.push_back(LangOpts.Name);
1379 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1380 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1381 #include "clang/Basic/LangOptions.def"
1382 #define SANITIZER(NAME, ID) \
1383 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1384 #include "clang/Basic/Sanitizers.def"
1386 Record.push_back(LangOpts.ModuleFeatures.size());
1387 for (StringRef Feature : LangOpts.ModuleFeatures)
1388 AddString(Feature, Record);
1390 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1391 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1393 AddString(LangOpts.CurrentModule, Record);
1395 // Comment options.
1396 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1397 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1398 AddString(I, Record);
1400 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1402 // OpenMP offloading options.
1403 Record.push_back(LangOpts.OMPTargetTriples.size());
1404 for (auto &T : LangOpts.OMPTargetTriples)
1405 AddString(T.getTriple(), Record);
1407 AddString(LangOpts.OMPHostIRFile, Record);
1409 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1411 // Target options.
1412 Record.clear();
1413 const TargetInfo &Target = Context.getTargetInfo();
1414 const TargetOptions &TargetOpts = Target.getTargetOpts();
1415 AddString(TargetOpts.Triple, Record);
1416 AddString(TargetOpts.CPU, Record);
1417 AddString(TargetOpts.TuneCPU, Record);
1418 AddString(TargetOpts.ABI, Record);
1419 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1420 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1421 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1423 Record.push_back(TargetOpts.Features.size());
1424 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1425 AddString(TargetOpts.Features[I], Record);
1427 Stream.EmitRecord(TARGET_OPTIONS, Record);
1429 // File system options.
1430 Record.clear();
1431 const FileSystemOptions &FSOpts =
1432 Context.getSourceManager().getFileManager().getFileSystemOpts();
1433 AddString(FSOpts.WorkingDir, Record);
1434 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1436 // Header search options.
1437 Record.clear();
1438 const HeaderSearchOptions &HSOpts =
1439 PP.getHeaderSearchInfo().getHeaderSearchOpts();
1441 AddString(HSOpts.Sysroot, Record);
1442 AddString(HSOpts.ResourceDir, Record);
1443 AddString(HSOpts.ModuleCachePath, Record);
1444 AddString(HSOpts.ModuleUserBuildPath, Record);
1445 Record.push_back(HSOpts.DisableModuleHash);
1446 Record.push_back(HSOpts.ImplicitModuleMaps);
1447 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1448 Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1449 Record.push_back(HSOpts.UseBuiltinIncludes);
1450 Record.push_back(HSOpts.UseStandardSystemIncludes);
1451 Record.push_back(HSOpts.UseStandardCXXIncludes);
1452 Record.push_back(HSOpts.UseLibcxx);
1453 // Write out the specific module cache path that contains the module files.
1454 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1455 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1457 // Preprocessor options.
1458 Record.clear();
1459 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1461 // Macro definitions.
1462 Record.push_back(PPOpts.Macros.size());
1463 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1464 AddString(PPOpts.Macros[I].first, Record);
1465 Record.push_back(PPOpts.Macros[I].second);
1468 // Includes
1469 Record.push_back(PPOpts.Includes.size());
1470 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1471 AddString(PPOpts.Includes[I], Record);
1473 // Macro includes
1474 Record.push_back(PPOpts.MacroIncludes.size());
1475 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1476 AddString(PPOpts.MacroIncludes[I], Record);
1478 Record.push_back(PPOpts.UsePredefines);
1479 // Detailed record is important since it is used for the module cache hash.
1480 Record.push_back(PPOpts.DetailedRecord);
1481 AddString(PPOpts.ImplicitPCHInclude, Record);
1482 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1483 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1485 // Leave the options block.
1486 Stream.ExitBlock();
1488 // Original file name and file ID
1489 SourceManager &SM = Context.getSourceManager();
1490 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1491 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1492 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1493 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1494 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1495 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1497 Record.clear();
1498 Record.push_back(ORIGINAL_FILE);
1499 AddFileID(SM.getMainFileID(), Record);
1500 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1503 Record.clear();
1504 AddFileID(SM.getMainFileID(), Record);
1505 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1507 WriteInputFiles(Context.SourceMgr,
1508 PP.getHeaderSearchInfo().getHeaderSearchOpts());
1509 Stream.ExitBlock();
1512 namespace {
1514 /// An input file.
1515 struct InputFileEntry {
1516 FileEntryRef File;
1517 bool IsSystemFile;
1518 bool IsTransient;
1519 bool BufferOverridden;
1520 bool IsTopLevelModuleMap;
1521 uint32_t ContentHash[2];
1523 InputFileEntry(FileEntryRef File) : File(File) {}
1526 } // namespace
1528 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1529 HeaderSearchOptions &HSOpts) {
1530 using namespace llvm;
1532 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1534 // Create input-file abbreviation.
1535 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1536 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1537 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1538 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1539 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1540 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1541 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1542 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1543 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1544 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1546 // Create input file hash abbreviation.
1547 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1548 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1549 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1550 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1551 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1553 // Get all ContentCache objects for files.
1554 std::vector<InputFileEntry> UserFiles;
1555 std::vector<InputFileEntry> SystemFiles;
1556 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1557 // Get this source location entry.
1558 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1559 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1561 // We only care about file entries that were not overridden.
1562 if (!SLoc->isFile())
1563 continue;
1564 const SrcMgr::FileInfo &File = SLoc->getFile();
1565 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1566 if (!Cache->OrigEntry)
1567 continue;
1569 // Do not emit input files that do not affect current module.
1570 if (!IsSLocAffecting[I])
1571 continue;
1573 InputFileEntry Entry(*Cache->OrigEntry);
1574 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1575 Entry.IsTransient = Cache->IsTransient;
1576 Entry.BufferOverridden = Cache->BufferOverridden;
1577 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1578 File.getIncludeLoc().isInvalid();
1580 auto ContentHash = hash_code(-1);
1581 if (PP->getHeaderSearchInfo()
1582 .getHeaderSearchOpts()
1583 .ValidateASTInputFilesContent) {
1584 auto MemBuff = Cache->getBufferIfLoaded();
1585 if (MemBuff)
1586 ContentHash = hash_value(MemBuff->getBuffer());
1587 else
1588 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1589 << Entry.File.getName();
1591 auto CH = llvm::APInt(64, ContentHash);
1592 Entry.ContentHash[0] =
1593 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1594 Entry.ContentHash[1] =
1595 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1597 if (Entry.IsSystemFile)
1598 SystemFiles.push_back(Entry);
1599 else
1600 UserFiles.push_back(Entry);
1603 // User files go at the front, system files at the back.
1604 auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1605 std::move(SystemFiles));
1607 unsigned UserFilesNum = 0;
1608 // Write out all of the input files.
1609 std::vector<uint64_t> InputFileOffsets;
1610 for (const auto &Entry : SortedFiles) {
1611 uint32_t &InputFileID = InputFileIDs[Entry.File];
1612 if (InputFileID != 0)
1613 continue; // already recorded this file.
1615 // Record this entry's offset.
1616 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1618 InputFileID = InputFileOffsets.size();
1620 if (!Entry.IsSystemFile)
1621 ++UserFilesNum;
1623 // Emit size/modification time for this file.
1624 // And whether this file was overridden.
1626 RecordData::value_type Record[] = {
1627 INPUT_FILE,
1628 InputFileOffsets.size(),
1629 (uint64_t)Entry.File.getSize(),
1630 (uint64_t)getTimestampForOutput(Entry.File),
1631 Entry.BufferOverridden,
1632 Entry.IsTransient,
1633 Entry.IsTopLevelModuleMap};
1635 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File.getNameAsRequested());
1638 // Emit content hash for this file.
1640 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1641 Entry.ContentHash[1]};
1642 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1646 Stream.ExitBlock();
1648 // Create input file offsets abbreviation.
1649 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1650 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1651 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1652 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1653 // input files
1654 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1655 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1657 // Write input file offsets.
1658 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1659 InputFileOffsets.size(), UserFilesNum};
1660 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1663 //===----------------------------------------------------------------------===//
1664 // Source Manager Serialization
1665 //===----------------------------------------------------------------------===//
1667 /// Create an abbreviation for the SLocEntry that refers to a
1668 /// file.
1669 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1670 using namespace llvm;
1672 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1673 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1678 // FileEntry fields.
1679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1683 return Stream.EmitAbbrev(std::move(Abbrev));
1686 /// Create an abbreviation for the SLocEntry that refers to a
1687 /// buffer.
1688 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1689 using namespace llvm;
1691 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1692 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1693 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1694 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1698 return Stream.EmitAbbrev(std::move(Abbrev));
1701 /// Create an abbreviation for the SLocEntry that refers to a
1702 /// buffer's blob.
1703 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1704 bool Compressed) {
1705 using namespace llvm;
1707 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1708 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1709 : SM_SLOC_BUFFER_BLOB));
1710 if (Compressed)
1711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1713 return Stream.EmitAbbrev(std::move(Abbrev));
1716 /// Create an abbreviation for the SLocEntry that refers to a macro
1717 /// expansion.
1718 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1719 using namespace llvm;
1721 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1722 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1725 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
1726 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
1727 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1728 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1729 return Stream.EmitAbbrev(std::move(Abbrev));
1732 /// Emit key length and data length as ULEB-encoded data, and return them as a
1733 /// pair.
1734 static std::pair<unsigned, unsigned>
1735 emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1736 llvm::encodeULEB128(KeyLen, Out);
1737 llvm::encodeULEB128(DataLen, Out);
1738 return std::make_pair(KeyLen, DataLen);
1741 namespace {
1743 // Trait used for the on-disk hash table of header search information.
1744 class HeaderFileInfoTrait {
1745 ASTWriter &Writer;
1747 // Keep track of the framework names we've used during serialization.
1748 SmallString<128> FrameworkStringData;
1749 llvm::StringMap<unsigned> FrameworkNameOffset;
1751 public:
1752 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1754 struct key_type {
1755 StringRef Filename;
1756 off_t Size;
1757 time_t ModTime;
1759 using key_type_ref = const key_type &;
1761 using UnresolvedModule =
1762 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1764 struct data_type {
1765 const HeaderFileInfo &HFI;
1766 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1767 UnresolvedModule Unresolved;
1769 using data_type_ref = const data_type &;
1771 using hash_value_type = unsigned;
1772 using offset_type = unsigned;
1774 hash_value_type ComputeHash(key_type_ref key) {
1775 // The hash is based only on size/time of the file, so that the reader can
1776 // match even when symlinking or excess path elements ("foo/../", "../")
1777 // change the form of the name. However, complete path is still the key.
1778 return llvm::hash_combine(key.Size, key.ModTime);
1781 std::pair<unsigned, unsigned>
1782 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1783 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1784 unsigned DataLen = 1 + 4 + 4;
1785 for (auto ModInfo : Data.KnownHeaders)
1786 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1787 DataLen += 4;
1788 if (Data.Unresolved.getPointer())
1789 DataLen += 4;
1790 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1793 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1794 using namespace llvm::support;
1796 endian::Writer LE(Out, little);
1797 LE.write<uint64_t>(key.Size);
1798 KeyLen -= 8;
1799 LE.write<uint64_t>(key.ModTime);
1800 KeyLen -= 8;
1801 Out.write(key.Filename.data(), KeyLen);
1804 void EmitData(raw_ostream &Out, key_type_ref key,
1805 data_type_ref Data, unsigned DataLen) {
1806 using namespace llvm::support;
1808 endian::Writer LE(Out, little);
1809 uint64_t Start = Out.tell(); (void)Start;
1811 unsigned char Flags = (Data.HFI.isImport << 5)
1812 | (Data.HFI.isPragmaOnce << 4)
1813 | (Data.HFI.DirInfo << 1)
1814 | Data.HFI.IndexHeaderMapHeader;
1815 LE.write<uint8_t>(Flags);
1817 if (!Data.HFI.ControllingMacro)
1818 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1819 else
1820 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1822 unsigned Offset = 0;
1823 if (!Data.HFI.Framework.empty()) {
1824 // If this header refers into a framework, save the framework name.
1825 llvm::StringMap<unsigned>::iterator Pos
1826 = FrameworkNameOffset.find(Data.HFI.Framework);
1827 if (Pos == FrameworkNameOffset.end()) {
1828 Offset = FrameworkStringData.size() + 1;
1829 FrameworkStringData.append(Data.HFI.Framework);
1830 FrameworkStringData.push_back(0);
1832 FrameworkNameOffset[Data.HFI.Framework] = Offset;
1833 } else
1834 Offset = Pos->second;
1836 LE.write<uint32_t>(Offset);
1838 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1839 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1840 uint32_t Value = (ModID << 3) | (unsigned)Role;
1841 assert((Value >> 3) == ModID && "overflow in header module info");
1842 LE.write<uint32_t>(Value);
1846 for (auto ModInfo : Data.KnownHeaders)
1847 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1848 if (Data.Unresolved.getPointer())
1849 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1851 assert(Out.tell() - Start == DataLen && "Wrong data length");
1854 const char *strings_begin() const { return FrameworkStringData.begin(); }
1855 const char *strings_end() const { return FrameworkStringData.end(); }
1858 } // namespace
1860 /// Write the header search block for the list of files that
1862 /// \param HS The header search structure to save.
1863 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1864 HeaderFileInfoTrait GeneratorTrait(*this);
1865 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1866 SmallVector<const char *, 4> SavedStrings;
1867 unsigned NumHeaderSearchEntries = 0;
1869 // Find all unresolved headers for the current module. We generally will
1870 // have resolved them before we get here, but not necessarily: we might be
1871 // compiling a preprocessed module, where there is no requirement for the
1872 // original files to exist any more.
1873 const HeaderFileInfo Empty; // So we can take a reference.
1874 if (WritingModule) {
1875 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1876 while (!Worklist.empty()) {
1877 Module *M = Worklist.pop_back_val();
1878 // We don't care about headers in unimportable submodules.
1879 if (M->isUnimportable())
1880 continue;
1882 // Map to disk files where possible, to pick up any missing stat
1883 // information. This also means we don't need to check the unresolved
1884 // headers list when emitting resolved headers in the first loop below.
1885 // FIXME: It'd be preferable to avoid doing this if we were given
1886 // sufficient stat information in the module map.
1887 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/std::nullopt);
1889 // If the file didn't exist, we can still create a module if we were given
1890 // enough information in the module map.
1891 for (const auto &U : M->MissingHeaders) {
1892 // Check that we were given enough information to build a module
1893 // without this file existing on disk.
1894 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1895 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1896 << WritingModule->getFullModuleName() << U.Size.has_value()
1897 << U.FileName;
1898 continue;
1901 // Form the effective relative pathname for the file.
1902 SmallString<128> Filename(M->Directory->getName());
1903 llvm::sys::path::append(Filename, U.FileName);
1904 PreparePathForOutput(Filename);
1906 StringRef FilenameDup = strdup(Filename.c_str());
1907 SavedStrings.push_back(FilenameDup.data());
1909 HeaderFileInfoTrait::key_type Key = {
1910 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0};
1911 HeaderFileInfoTrait::data_type Data = {
1912 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}};
1913 // FIXME: Deal with cases where there are multiple unresolved header
1914 // directives in different submodules for the same header.
1915 Generator.insert(Key, Data, GeneratorTrait);
1916 ++NumHeaderSearchEntries;
1918 auto SubmodulesRange = M->submodules();
1919 Worklist.append(SubmodulesRange.begin(), SubmodulesRange.end());
1923 SmallVector<const FileEntry *, 16> FilesByUID;
1924 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1926 if (FilesByUID.size() > HS.header_file_size())
1927 FilesByUID.resize(HS.header_file_size());
1929 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1930 const FileEntry *File = FilesByUID[UID];
1931 if (!File)
1932 continue;
1934 // Get the file info. This will load info from the external source if
1935 // necessary. Skip emitting this file if we have no information on it
1936 // as a header file (in which case HFI will be null) or if it hasn't
1937 // changed since it was loaded. Also skip it if it's for a modular header
1938 // from a different module; in that case, we rely on the module(s)
1939 // containing the header to provide this information.
1940 const HeaderFileInfo *HFI =
1941 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1942 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1943 continue;
1945 // Massage the file path into an appropriate form.
1946 StringRef Filename = File->getName();
1947 SmallString<128> FilenameTmp(Filename);
1948 if (PreparePathForOutput(FilenameTmp)) {
1949 // If we performed any translation on the file name at all, we need to
1950 // save this string, since the generator will refer to it later.
1951 Filename = StringRef(strdup(FilenameTmp.c_str()));
1952 SavedStrings.push_back(Filename.data());
1955 HeaderFileInfoTrait::key_type Key = {
1956 Filename, File->getSize(), getTimestampForOutput(File)
1958 HeaderFileInfoTrait::data_type Data = {
1959 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
1961 Generator.insert(Key, Data, GeneratorTrait);
1962 ++NumHeaderSearchEntries;
1965 // Create the on-disk hash table in a buffer.
1966 SmallString<4096> TableData;
1967 uint32_t BucketOffset;
1969 using namespace llvm::support;
1971 llvm::raw_svector_ostream Out(TableData);
1972 // Make sure that no bucket is at offset 0
1973 endian::write<uint32_t>(Out, 0, little);
1974 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1977 // Create a blob abbreviation
1978 using namespace llvm;
1980 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1981 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1982 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1983 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1984 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1985 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1986 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1988 // Write the header search table
1989 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1990 NumHeaderSearchEntries, TableData.size()};
1991 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1992 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1994 // Free all of the strings we had to duplicate.
1995 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1996 free(const_cast<char *>(SavedStrings[I]));
1999 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2000 unsigned SLocBufferBlobCompressedAbbrv,
2001 unsigned SLocBufferBlobAbbrv) {
2002 using RecordDataType = ASTWriter::RecordData::value_type;
2004 // Compress the buffer if possible. We expect that almost all PCM
2005 // consumers will not want its contents.
2006 SmallVector<uint8_t, 0> CompressedBuffer;
2007 if (llvm::compression::zstd::isAvailable()) {
2008 llvm::compression::zstd::compress(
2009 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer, 9);
2010 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2011 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2012 llvm::toStringRef(CompressedBuffer));
2013 return;
2015 if (llvm::compression::zlib::isAvailable()) {
2016 llvm::compression::zlib::compress(
2017 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2018 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2019 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2020 llvm::toStringRef(CompressedBuffer));
2021 return;
2024 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2025 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2028 /// Writes the block containing the serialized form of the
2029 /// source manager.
2031 /// TODO: We should probably use an on-disk hash table (stored in a
2032 /// blob), indexed based on the file name, so that we only create
2033 /// entries for files that we actually need. In the common case (no
2034 /// errors), we probably won't have to create file entries for any of
2035 /// the files in the AST.
2036 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2037 const Preprocessor &PP) {
2038 RecordData Record;
2040 // Enter the source manager block.
2041 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2042 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2044 // Abbreviations for the various kinds of source-location entries.
2045 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2046 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2047 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2048 unsigned SLocBufferBlobCompressedAbbrv =
2049 CreateSLocBufferBlobAbbrev(Stream, true);
2050 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2052 // Write out the source location entry table. We skip the first
2053 // entry, which is always the same dummy entry.
2054 std::vector<uint32_t> SLocEntryOffsets;
2055 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2056 RecordData PreloadSLocs;
2057 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2058 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2059 I != N; ++I) {
2060 // Get this source location entry.
2061 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2062 FileID FID = FileID::get(I);
2063 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2065 // Record the offset of this source-location entry.
2066 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2067 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2069 // Figure out which record code to use.
2070 unsigned Code;
2071 if (SLoc->isFile()) {
2072 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2073 if (Cache->OrigEntry) {
2074 Code = SM_SLOC_FILE_ENTRY;
2075 } else
2076 Code = SM_SLOC_BUFFER_ENTRY;
2077 } else
2078 Code = SM_SLOC_EXPANSION_ENTRY;
2079 Record.clear();
2080 Record.push_back(Code);
2082 if (SLoc->isFile()) {
2083 const SrcMgr::FileInfo &File = SLoc->getFile();
2084 const SrcMgr::ContentCache *Content = &File.getContentCache();
2085 // Do not emit files that were not listed as inputs.
2086 if (!IsSLocAffecting[I])
2087 continue;
2088 SLocEntryOffsets.push_back(Offset);
2089 // Starting offset of this entry within this module, so skip the dummy.
2090 Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2091 AddSourceLocation(File.getIncludeLoc(), Record);
2092 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2093 Record.push_back(File.hasLineDirectives());
2095 bool EmitBlob = false;
2096 if (Content->OrigEntry) {
2097 assert(Content->OrigEntry == Content->ContentsEntry &&
2098 "Writing to AST an overridden file is not supported");
2100 // The source location entry is a file. Emit input file ID.
2101 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2102 Record.push_back(InputFileIDs[Content->OrigEntry]);
2104 Record.push_back(getAdjustedNumCreatedFIDs(FID));
2106 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2107 if (FDI != FileDeclIDs.end()) {
2108 Record.push_back(FDI->second->FirstDeclIndex);
2109 Record.push_back(FDI->second->DeclIDs.size());
2110 } else {
2111 Record.push_back(0);
2112 Record.push_back(0);
2115 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2117 if (Content->BufferOverridden || Content->IsTransient)
2118 EmitBlob = true;
2119 } else {
2120 // The source location entry is a buffer. The blob associated
2121 // with this entry contains the contents of the buffer.
2123 // We add one to the size so that we capture the trailing NULL
2124 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2125 // the reader side).
2126 std::optional<llvm::MemoryBufferRef> Buffer =
2127 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2128 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2129 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2130 StringRef(Name.data(), Name.size() + 1));
2131 EmitBlob = true;
2133 if (Name == "<built-in>")
2134 PreloadSLocs.push_back(SLocEntryOffsets.size());
2137 if (EmitBlob) {
2138 // Include the implicit terminating null character in the on-disk buffer
2139 // if we're writing it uncompressed.
2140 std::optional<llvm::MemoryBufferRef> Buffer =
2141 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2142 if (!Buffer)
2143 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2144 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2145 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2146 SLocBufferBlobAbbrv);
2148 } else {
2149 // The source location entry is a macro expansion.
2150 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2151 SLocEntryOffsets.push_back(Offset);
2152 // Starting offset of this entry within this module, so skip the dummy.
2153 Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2);
2154 LocSeq::State Seq;
2155 AddSourceLocation(Expansion.getSpellingLoc(), Record, Seq);
2156 AddSourceLocation(Expansion.getExpansionLocStart(), Record, Seq);
2157 AddSourceLocation(Expansion.isMacroArgExpansion()
2158 ? SourceLocation()
2159 : Expansion.getExpansionLocEnd(),
2160 Record, Seq);
2161 Record.push_back(Expansion.isExpansionTokenRange());
2163 // Compute the token length for this macro expansion.
2164 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2165 if (I + 1 != N)
2166 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2167 Record.push_back(getAdjustedOffset(NextOffset - SLoc->getOffset()) - 1);
2168 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2172 Stream.ExitBlock();
2174 if (SLocEntryOffsets.empty())
2175 return;
2177 // Write the source-location offsets table into the AST block. This
2178 // table is used for lazily loading source-location information.
2179 using namespace llvm;
2181 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2182 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2183 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2184 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2185 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2186 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2187 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2189 RecordData::value_type Record[] = {
2190 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2191 getAdjustedOffset(SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2192 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2193 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2194 bytes(SLocEntryOffsets));
2196 // Write the source location entry preloads array, telling the AST
2197 // reader which source locations entries it should load eagerly.
2198 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2200 // Write the line table. It depends on remapping working, so it must come
2201 // after the source location offsets.
2202 if (SourceMgr.hasLineTable()) {
2203 LineTableInfo &LineTable = SourceMgr.getLineTable();
2205 Record.clear();
2207 // Emit the needed file names.
2208 llvm::DenseMap<int, int> FilenameMap;
2209 FilenameMap[-1] = -1; // For unspecified filenames.
2210 for (const auto &L : LineTable) {
2211 if (L.first.ID < 0)
2212 continue;
2213 for (auto &LE : L.second) {
2214 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2215 FilenameMap.size() - 1)).second)
2216 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2219 Record.push_back(0);
2221 // Emit the line entries
2222 for (const auto &L : LineTable) {
2223 // Only emit entries for local files.
2224 if (L.first.ID < 0)
2225 continue;
2227 AddFileID(L.first, Record);
2229 // Emit the line entries
2230 Record.push_back(L.second.size());
2231 for (const auto &LE : L.second) {
2232 Record.push_back(LE.FileOffset);
2233 Record.push_back(LE.LineNo);
2234 Record.push_back(FilenameMap[LE.FilenameID]);
2235 Record.push_back((unsigned)LE.FileKind);
2236 Record.push_back(LE.IncludeOffset);
2240 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2244 //===----------------------------------------------------------------------===//
2245 // Preprocessor Serialization
2246 //===----------------------------------------------------------------------===//
2248 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2249 const Preprocessor &PP) {
2250 if (MacroInfo *MI = MD->getMacroInfo())
2251 if (MI->isBuiltinMacro())
2252 return true;
2254 if (IsModule) {
2255 SourceLocation Loc = MD->getLocation();
2256 if (Loc.isInvalid())
2257 return true;
2258 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2259 return true;
2262 return false;
2265 void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) {
2266 using namespace llvm::support;
2268 const Preprocessor::IncludedFilesSet &IncludedFiles = PP.getIncludedFiles();
2270 std::vector<uint32_t> IncludedInputFileIDs;
2271 IncludedInputFileIDs.reserve(IncludedFiles.size());
2273 for (const FileEntry *File : IncludedFiles) {
2274 auto InputFileIt = InputFileIDs.find(File);
2275 if (InputFileIt == InputFileIDs.end())
2276 continue;
2277 IncludedInputFileIDs.push_back(InputFileIt->second);
2280 llvm::sort(IncludedInputFileIDs);
2282 endian::Writer LE(Out, little);
2283 LE.write<uint32_t>(IncludedInputFileIDs.size());
2284 for (uint32_t ID : IncludedInputFileIDs)
2285 LE.write<uint32_t>(ID);
2288 /// Writes the block containing the serialized form of the
2289 /// preprocessor.
2290 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2291 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2293 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2294 if (PPRec)
2295 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2297 RecordData Record;
2298 RecordData ModuleMacroRecord;
2300 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2301 if (PP.getCounterValue() != 0) {
2302 RecordData::value_type Record[] = {PP.getCounterValue()};
2303 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2306 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2307 // replayed when the preamble terminates into the main file.
2308 SourceLocation AssumeNonNullLoc =
2309 PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2310 if (AssumeNonNullLoc.isValid()) {
2311 assert(PP.isRecordingPreamble());
2312 AddSourceLocation(AssumeNonNullLoc, Record);
2313 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2314 Record.clear();
2317 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2318 assert(!IsModule);
2319 auto SkipInfo = PP.getPreambleSkipInfo();
2320 if (SkipInfo) {
2321 Record.push_back(true);
2322 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2323 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2324 Record.push_back(SkipInfo->FoundNonSkipPortion);
2325 Record.push_back(SkipInfo->FoundElse);
2326 AddSourceLocation(SkipInfo->ElseLoc, Record);
2327 } else {
2328 Record.push_back(false);
2330 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2331 AddSourceLocation(Cond.IfLoc, Record);
2332 Record.push_back(Cond.WasSkipping);
2333 Record.push_back(Cond.FoundNonSkip);
2334 Record.push_back(Cond.FoundElse);
2336 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2337 Record.clear();
2340 // Enter the preprocessor block.
2341 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2343 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2344 // FIXME: Include a location for the use, and say which one was used.
2345 if (PP.SawDateOrTime())
2346 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2348 // Loop over all the macro directives that are live at the end of the file,
2349 // emitting each to the PP section.
2351 // Construct the list of identifiers with macro directives that need to be
2352 // serialized.
2353 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2354 // It is meaningless to emit macros for named modules. It only wastes times
2355 // and spaces.
2356 if (!isWritingStdCXXNamedModules())
2357 for (auto &Id : PP.getIdentifierTable())
2358 if (Id.second->hadMacroDefinition() &&
2359 (!Id.second->isFromAST() ||
2360 Id.second->hasChangedSinceDeserialization()))
2361 MacroIdentifiers.push_back(Id.second);
2362 // Sort the set of macro definitions that need to be serialized by the
2363 // name of the macro, to provide a stable ordering.
2364 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2366 // Emit the macro directives as a list and associate the offset with the
2367 // identifier they belong to.
2368 for (const IdentifierInfo *Name : MacroIdentifiers) {
2369 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2370 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2371 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2373 // Write out any exported module macros.
2374 bool EmittedModuleMacros = false;
2375 // C+=20 Header Units are compiled module interfaces, but they preserve
2376 // macros that are live (i.e. have a defined value) at the end of the
2377 // compilation. So when writing a header unit, we preserve only the final
2378 // value of each macro (and discard any that are undefined). Header units
2379 // do not have sub-modules (although they might import other header units).
2380 // PCH files, conversely, retain the history of each macro's define/undef
2381 // and of leaf macros in sub modules.
2382 if (IsModule && WritingModule->isHeaderUnit()) {
2383 // This is for the main TU when it is a C++20 header unit.
2384 // We preserve the final state of defined macros, and we do not emit ones
2385 // that are undefined.
2386 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2387 MD->getKind() == MacroDirective::MD_Undefine)
2388 continue;
2389 AddSourceLocation(MD->getLocation(), Record);
2390 Record.push_back(MD->getKind());
2391 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2392 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2393 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2394 Record.push_back(VisMD->isPublic());
2396 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2397 ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2398 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2399 ModuleMacroRecord.clear();
2400 EmittedModuleMacros = true;
2401 } else {
2402 // Emit the macro directives in reverse source order.
2403 for (; MD; MD = MD->getPrevious()) {
2404 // Once we hit an ignored macro, we're done: the rest of the chain
2405 // will all be ignored macros.
2406 if (shouldIgnoreMacro(MD, IsModule, PP))
2407 break;
2408 AddSourceLocation(MD->getLocation(), Record);
2409 Record.push_back(MD->getKind());
2410 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2411 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2412 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2413 Record.push_back(VisMD->isPublic());
2417 // We write out exported module macros for PCH as well.
2418 auto Leafs = PP.getLeafModuleMacros(Name);
2419 SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end());
2420 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2421 while (!Worklist.empty()) {
2422 auto *Macro = Worklist.pop_back_val();
2424 // Emit a record indicating this submodule exports this macro.
2425 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2426 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2427 for (auto *M : Macro->overrides())
2428 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2430 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2431 ModuleMacroRecord.clear();
2433 // Enqueue overridden macros once we've visited all their ancestors.
2434 for (auto *M : Macro->overrides())
2435 if (++Visits[M] == M->getNumOverridingMacros())
2436 Worklist.push_back(M);
2438 EmittedModuleMacros = true;
2441 if (Record.empty() && !EmittedModuleMacros)
2442 continue;
2444 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2445 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2446 Record.clear();
2449 /// Offsets of each of the macros into the bitstream, indexed by
2450 /// the local macro ID
2452 /// For each identifier that is associated with a macro, this map
2453 /// provides the offset into the bitstream where that macro is
2454 /// defined.
2455 std::vector<uint32_t> MacroOffsets;
2457 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2458 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2459 MacroInfo *MI = MacroInfosToEmit[I].MI;
2460 MacroID ID = MacroInfosToEmit[I].ID;
2462 if (ID < FirstMacroID) {
2463 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2464 continue;
2467 // Record the local offset of this macro.
2468 unsigned Index = ID - FirstMacroID;
2469 if (Index >= MacroOffsets.size())
2470 MacroOffsets.resize(Index + 1);
2472 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2473 assert((Offset >> 32) == 0 && "Macro offset too large");
2474 MacroOffsets[Index] = Offset;
2476 AddIdentifierRef(Name, Record);
2477 AddSourceLocation(MI->getDefinitionLoc(), Record);
2478 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2479 Record.push_back(MI->isUsed());
2480 Record.push_back(MI->isUsedForHeaderGuard());
2481 Record.push_back(MI->getNumTokens());
2482 unsigned Code;
2483 if (MI->isObjectLike()) {
2484 Code = PP_MACRO_OBJECT_LIKE;
2485 } else {
2486 Code = PP_MACRO_FUNCTION_LIKE;
2488 Record.push_back(MI->isC99Varargs());
2489 Record.push_back(MI->isGNUVarargs());
2490 Record.push_back(MI->hasCommaPasting());
2491 Record.push_back(MI->getNumParams());
2492 for (const IdentifierInfo *Param : MI->params())
2493 AddIdentifierRef(Param, Record);
2496 // If we have a detailed preprocessing record, record the macro definition
2497 // ID that corresponds to this macro.
2498 if (PPRec)
2499 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2501 Stream.EmitRecord(Code, Record);
2502 Record.clear();
2504 // Emit the tokens array.
2505 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2506 // Note that we know that the preprocessor does not have any annotation
2507 // tokens in it because they are created by the parser, and thus can't
2508 // be in a macro definition.
2509 const Token &Tok = MI->getReplacementToken(TokNo);
2510 AddToken(Tok, Record);
2511 Stream.EmitRecord(PP_TOKEN, Record);
2512 Record.clear();
2514 ++NumMacros;
2517 Stream.ExitBlock();
2519 // Write the offsets table for macro IDs.
2520 using namespace llvm;
2522 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2523 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2529 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2531 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2532 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2533 MacroOffsetsBase - ASTBlockStartOffset};
2534 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2538 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2539 Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES));
2540 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2541 unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2543 SmallString<2048> Buffer;
2544 raw_svector_ostream Out(Buffer);
2545 writeIncludedFiles(Out, PP);
2546 RecordData::value_type Record[] = {PP_INCLUDED_FILES};
2547 Stream.EmitRecordWithBlob(IncludedFilesAbbrev, Record, Buffer.data(),
2548 Buffer.size());
2552 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2553 uint64_t MacroOffsetsBase) {
2554 if (PPRec.local_begin() == PPRec.local_end())
2555 return;
2557 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2559 // Enter the preprocessor block.
2560 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2562 // If the preprocessor has a preprocessing record, emit it.
2563 unsigned NumPreprocessingRecords = 0;
2564 using namespace llvm;
2566 // Set up the abbreviation for
2567 unsigned InclusionAbbrev = 0;
2569 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2570 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2572 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2573 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2576 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2579 unsigned FirstPreprocessorEntityID
2580 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2581 + NUM_PREDEF_PP_ENTITY_IDS;
2582 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2583 RecordData Record;
2584 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2585 EEnd = PPRec.local_end();
2586 E != EEnd;
2587 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2588 Record.clear();
2590 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2591 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2592 PreprocessedEntityOffsets.push_back(
2593 PPEntityOffset(getAdjustedRange((*E)->getSourceRange()), Offset));
2595 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2596 // Record this macro definition's ID.
2597 MacroDefinitions[MD] = NextPreprocessorEntityID;
2599 AddIdentifierRef(MD->getName(), Record);
2600 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2601 continue;
2604 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2605 Record.push_back(ME->isBuiltinMacro());
2606 if (ME->isBuiltinMacro())
2607 AddIdentifierRef(ME->getName(), Record);
2608 else
2609 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2610 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2611 continue;
2614 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2615 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2616 Record.push_back(ID->getFileName().size());
2617 Record.push_back(ID->wasInQuotes());
2618 Record.push_back(static_cast<unsigned>(ID->getKind()));
2619 Record.push_back(ID->importedModule());
2620 SmallString<64> Buffer;
2621 Buffer += ID->getFileName();
2622 // Check that the FileEntry is not null because it was not resolved and
2623 // we create a PCH even with compiler errors.
2624 if (ID->getFile())
2625 Buffer += ID->getFile()->getName();
2626 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2627 continue;
2630 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2632 Stream.ExitBlock();
2634 // Write the offsets table for the preprocessing record.
2635 if (NumPreprocessingRecords > 0) {
2636 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2638 // Write the offsets table for identifier IDs.
2639 using namespace llvm;
2641 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2642 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2643 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2644 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2645 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2647 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2648 FirstPreprocessorEntityID -
2649 NUM_PREDEF_PP_ENTITY_IDS};
2650 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2651 bytes(PreprocessedEntityOffsets));
2654 // Write the skipped region table for the preprocessing record.
2655 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2656 if (SkippedRanges.size() > 0) {
2657 std::vector<PPSkippedRange> SerializedSkippedRanges;
2658 SerializedSkippedRanges.reserve(SkippedRanges.size());
2659 for (auto const& Range : SkippedRanges)
2660 SerializedSkippedRanges.emplace_back(Range);
2662 using namespace llvm;
2663 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2664 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2666 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2668 Record.clear();
2669 Record.push_back(PPD_SKIPPED_RANGES);
2670 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2671 bytes(SerializedSkippedRanges));
2675 unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2676 if (!Mod)
2677 return 0;
2679 auto Known = SubmoduleIDs.find(Mod);
2680 if (Known != SubmoduleIDs.end())
2681 return Known->second;
2683 auto *Top = Mod->getTopLevelModule();
2684 if (Top != WritingModule &&
2685 (getLangOpts().CompilingPCH ||
2686 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2687 return 0;
2689 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2692 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2693 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2694 // FIXME: This can easily happen, if we have a reference to a submodule that
2695 // did not result in us loading a module file for that submodule. For
2696 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2697 // assert((ID || !Mod) &&
2698 // "asked for module ID for non-local, non-imported module");
2699 return ID;
2702 /// Compute the number of modules within the given tree (including the
2703 /// given module).
2704 static unsigned getNumberOfModules(Module *Mod) {
2705 unsigned ChildModules = 0;
2706 for (auto *Submodule : Mod->submodules())
2707 ChildModules += getNumberOfModules(Submodule);
2709 return ChildModules + 1;
2712 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2713 // Enter the submodule description block.
2714 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2716 // Write the abbreviations needed for the submodules block.
2717 using namespace llvm;
2719 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2720 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
2724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2725 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2726 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2727 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2728 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2729 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2730 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2731 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2732 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2733 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2734 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2736 Abbrev = std::make_shared<BitCodeAbbrev>();
2737 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2739 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2741 Abbrev = std::make_shared<BitCodeAbbrev>();
2742 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2743 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2744 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2746 Abbrev = std::make_shared<BitCodeAbbrev>();
2747 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2749 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2751 Abbrev = std::make_shared<BitCodeAbbrev>();
2752 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2754 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2756 Abbrev = std::make_shared<BitCodeAbbrev>();
2757 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2760 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2762 Abbrev = std::make_shared<BitCodeAbbrev>();
2763 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2765 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2767 Abbrev = std::make_shared<BitCodeAbbrev>();
2768 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2769 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2770 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2772 Abbrev = std::make_shared<BitCodeAbbrev>();
2773 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2774 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2775 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2777 Abbrev = std::make_shared<BitCodeAbbrev>();
2778 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2780 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2782 Abbrev = std::make_shared<BitCodeAbbrev>();
2783 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2786 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2788 Abbrev = std::make_shared<BitCodeAbbrev>();
2789 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2790 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2791 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2793 Abbrev = std::make_shared<BitCodeAbbrev>();
2794 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2797 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2799 Abbrev = std::make_shared<BitCodeAbbrev>();
2800 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2801 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2802 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2804 // Write the submodule metadata block.
2805 RecordData::value_type Record[] = {
2806 getNumberOfModules(WritingModule),
2807 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2808 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2810 // Write all of the submodules.
2811 std::queue<Module *> Q;
2812 Q.push(WritingModule);
2813 while (!Q.empty()) {
2814 Module *Mod = Q.front();
2815 Q.pop();
2816 unsigned ID = getSubmoduleID(Mod);
2818 uint64_t ParentID = 0;
2819 if (Mod->Parent) {
2820 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2821 ParentID = SubmoduleIDs[Mod->Parent];
2824 // Emit the definition of the block.
2826 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2828 ParentID,
2829 (RecordData::value_type)Mod->Kind,
2830 Mod->IsFramework,
2831 Mod->IsExplicit,
2832 Mod->IsSystem,
2833 Mod->IsExternC,
2834 Mod->InferSubmodules,
2835 Mod->InferExplicitSubmodules,
2836 Mod->InferExportWildcard,
2837 Mod->ConfigMacrosExhaustive,
2838 Mod->ModuleMapIsPrivate};
2839 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2842 // Emit the requirements.
2843 for (const auto &R : Mod->Requirements) {
2844 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2845 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2848 // Emit the umbrella header, if there is one.
2849 if (std::optional<Module::Header> UmbrellaHeader =
2850 Mod->getUmbrellaHeaderAsWritten()) {
2851 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2852 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2853 UmbrellaHeader->NameAsWritten);
2854 } else if (std::optional<Module::DirectoryName> UmbrellaDir =
2855 Mod->getUmbrellaDirAsWritten()) {
2856 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2857 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2858 UmbrellaDir->NameAsWritten);
2861 // Emit the headers.
2862 struct {
2863 unsigned RecordKind;
2864 unsigned Abbrev;
2865 Module::HeaderKind HeaderKind;
2866 } HeaderLists[] = {
2867 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2868 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2869 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2870 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2871 Module::HK_PrivateTextual},
2872 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2874 for (auto &HL : HeaderLists) {
2875 RecordData::value_type Record[] = {HL.RecordKind};
2876 for (auto &H : Mod->Headers[HL.HeaderKind])
2877 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2880 // Emit the top headers.
2882 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2883 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2884 for (auto *H : TopHeaders) {
2885 SmallString<128> HeaderName(H->getName());
2886 PreparePathForOutput(HeaderName);
2887 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
2891 // Emit the imports.
2892 if (!Mod->Imports.empty()) {
2893 RecordData Record;
2894 for (auto *I : Mod->Imports)
2895 Record.push_back(getSubmoduleID(I));
2896 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2899 // Emit the modules affecting compilation that were not imported.
2900 if (!Mod->AffectingClangModules.empty()) {
2901 RecordData Record;
2902 for (auto *I : Mod->AffectingClangModules)
2903 Record.push_back(getSubmoduleID(I));
2904 Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
2907 // Emit the exports.
2908 if (!Mod->Exports.empty()) {
2909 RecordData Record;
2910 for (const auto &E : Mod->Exports) {
2911 // FIXME: This may fail; we don't require that all exported modules
2912 // are local or imported.
2913 Record.push_back(getSubmoduleID(E.getPointer()));
2914 Record.push_back(E.getInt());
2916 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2919 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2920 // Might be unnecessary as use declarations are only used to build the
2921 // module itself.
2923 // TODO: Consider serializing undeclared uses of modules.
2925 // Emit the link libraries.
2926 for (const auto &LL : Mod->LinkLibraries) {
2927 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2928 LL.IsFramework};
2929 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2932 // Emit the conflicts.
2933 for (const auto &C : Mod->Conflicts) {
2934 // FIXME: This may fail; we don't require that all conflicting modules
2935 // are local or imported.
2936 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2937 getSubmoduleID(C.Other)};
2938 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2941 // Emit the configuration macros.
2942 for (const auto &CM : Mod->ConfigMacros) {
2943 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2944 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2947 // Emit the initializers, if any.
2948 RecordData Inits;
2949 for (Decl *D : Context->getModuleInitializers(Mod))
2950 Inits.push_back(GetDeclRef(D));
2951 if (!Inits.empty())
2952 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2954 // Emit the name of the re-exported module, if any.
2955 if (!Mod->ExportAsModule.empty()) {
2956 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2957 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2960 // Queue up the submodules of this module.
2961 for (auto *M : Mod->submodules())
2962 Q.push(M);
2965 Stream.ExitBlock();
2967 assert((NextSubmoduleID - FirstSubmoduleID ==
2968 getNumberOfModules(WritingModule)) &&
2969 "Wrong # of submodules; found a reference to a non-local, "
2970 "non-imported submodule?");
2973 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2974 bool isModule) {
2975 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2976 DiagStateIDMap;
2977 unsigned CurrID = 0;
2978 RecordData Record;
2980 auto EncodeDiagStateFlags =
2981 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2982 unsigned Result = (unsigned)DS->ExtBehavior;
2983 for (unsigned Val :
2984 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2985 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2986 (unsigned)DS->SuppressSystemWarnings})
2987 Result = (Result << 1) | Val;
2988 return Result;
2991 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2992 Record.push_back(Flags);
2994 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2995 bool IncludeNonPragmaStates) {
2996 // Ensure that the diagnostic state wasn't modified since it was created.
2997 // We will not correctly round-trip this information otherwise.
2998 assert(Flags == EncodeDiagStateFlags(State) &&
2999 "diag state flags vary in single AST file");
3001 unsigned &DiagStateID = DiagStateIDMap[State];
3002 Record.push_back(DiagStateID);
3004 if (DiagStateID == 0) {
3005 DiagStateID = ++CurrID;
3007 // Add a placeholder for the number of mappings.
3008 auto SizeIdx = Record.size();
3009 Record.emplace_back();
3010 for (const auto &I : *State) {
3011 if (I.second.isPragma() || IncludeNonPragmaStates) {
3012 Record.push_back(I.first);
3013 Record.push_back(I.second.serialize());
3016 // Update the placeholder.
3017 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3021 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3023 // Reserve a spot for the number of locations with state transitions.
3024 auto NumLocationsIdx = Record.size();
3025 Record.emplace_back();
3027 // Emit the state transitions.
3028 unsigned NumLocations = 0;
3029 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3030 if (!FileIDAndFile.first.isValid() ||
3031 !FileIDAndFile.second.HasLocalTransitions)
3032 continue;
3033 ++NumLocations;
3035 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3036 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3037 AddSourceLocation(Loc, Record);
3039 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3040 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3041 Record.push_back(getAdjustedOffset(StatePoint.Offset));
3042 AddDiagState(StatePoint.State, false);
3046 // Backpatch the number of locations.
3047 Record[NumLocationsIdx] = NumLocations;
3049 // Emit CurDiagStateLoc. Do it last in order to match source order.
3051 // This also protects against a hypothetical corner case with simulating
3052 // -Werror settings for implicit modules in the ASTReader, where reading
3053 // CurDiagState out of context could change whether warning pragmas are
3054 // treated as errors.
3055 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3056 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3058 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3061 //===----------------------------------------------------------------------===//
3062 // Type Serialization
3063 //===----------------------------------------------------------------------===//
3065 /// Write the representation of a type to the AST stream.
3066 void ASTWriter::WriteType(QualType T) {
3067 TypeIdx &IdxRef = TypeIdxs[T];
3068 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3069 IdxRef = TypeIdx(NextTypeID++);
3070 TypeIdx Idx = IdxRef;
3072 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3074 // Emit the type's representation.
3075 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
3077 // Record the offset for this type.
3078 unsigned Index = Idx.getIndex() - FirstTypeID;
3079 if (TypeOffsets.size() == Index)
3080 TypeOffsets.emplace_back(Offset);
3081 else if (TypeOffsets.size() < Index) {
3082 TypeOffsets.resize(Index + 1);
3083 TypeOffsets[Index].setBitOffset(Offset);
3084 } else {
3085 llvm_unreachable("Types emitted in wrong order");
3089 //===----------------------------------------------------------------------===//
3090 // Declaration Serialization
3091 //===----------------------------------------------------------------------===//
3093 /// Write the block containing all of the declaration IDs
3094 /// lexically declared within the given DeclContext.
3096 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3097 /// bitstream, or 0 if no block was written.
3098 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3099 DeclContext *DC) {
3100 if (DC->decls_empty())
3101 return 0;
3103 uint64_t Offset = Stream.GetCurrentBitNo();
3104 SmallVector<uint32_t, 128> KindDeclPairs;
3105 for (const auto *D : DC->decls()) {
3106 KindDeclPairs.push_back(D->getKind());
3107 KindDeclPairs.push_back(GetDeclRef(D));
3110 ++NumLexicalDeclContexts;
3111 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3112 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3113 bytes(KindDeclPairs));
3114 return Offset;
3117 void ASTWriter::WriteTypeDeclOffsets() {
3118 using namespace llvm;
3120 // Write the type offsets array
3121 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3122 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3123 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3124 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3125 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3126 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3128 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3129 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3130 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3133 // Write the declaration offsets array
3134 Abbrev = std::make_shared<BitCodeAbbrev>();
3135 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3136 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3137 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3138 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3139 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3141 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3142 FirstDeclID - NUM_PREDEF_DECL_IDS};
3143 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3147 void ASTWriter::WriteFileDeclIDsMap() {
3148 using namespace llvm;
3150 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3151 SortedFileDeclIDs.reserve(FileDeclIDs.size());
3152 for (const auto &P : FileDeclIDs)
3153 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3154 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3156 // Join the vectors of DeclIDs from all files.
3157 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3158 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3159 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3160 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3161 llvm::stable_sort(Info.DeclIDs);
3162 for (auto &LocDeclEntry : Info.DeclIDs)
3163 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3166 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3167 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3170 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3171 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3172 FileGroupedDeclIDs.size()};
3173 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3176 void ASTWriter::WriteComments() {
3177 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3178 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3179 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3180 return;
3182 // Don't write comments to BMI to reduce the size of BMI.
3183 // If language services (e.g., clangd) want such abilities,
3184 // we can offer a special option then.
3185 if (isWritingStdCXXNamedModules())
3186 return;
3188 RecordData Record;
3189 for (const auto &FO : Context->Comments.OrderedComments) {
3190 for (const auto &OC : FO.second) {
3191 const RawComment *I = OC.second;
3192 Record.clear();
3193 AddSourceRange(I->getSourceRange(), Record);
3194 Record.push_back(I->getKind());
3195 Record.push_back(I->isTrailingComment());
3196 Record.push_back(I->isAlmostTrailingComment());
3197 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3202 //===----------------------------------------------------------------------===//
3203 // Global Method Pool and Selector Serialization
3204 //===----------------------------------------------------------------------===//
3206 namespace {
3208 // Trait used for the on-disk hash table used in the method pool.
3209 class ASTMethodPoolTrait {
3210 ASTWriter &Writer;
3212 public:
3213 using key_type = Selector;
3214 using key_type_ref = key_type;
3216 struct data_type {
3217 SelectorID ID;
3218 ObjCMethodList Instance, Factory;
3220 using data_type_ref = const data_type &;
3222 using hash_value_type = unsigned;
3223 using offset_type = unsigned;
3225 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3227 static hash_value_type ComputeHash(Selector Sel) {
3228 return serialization::ComputeHash(Sel);
3231 std::pair<unsigned, unsigned>
3232 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3233 data_type_ref Methods) {
3234 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3235 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3236 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3237 Method = Method->getNext())
3238 if (ShouldWriteMethodListNode(Method))
3239 DataLen += 4;
3240 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3241 Method = Method->getNext())
3242 if (ShouldWriteMethodListNode(Method))
3243 DataLen += 4;
3244 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3247 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3248 using namespace llvm::support;
3250 endian::Writer LE(Out, little);
3251 uint64_t Start = Out.tell();
3252 assert((Start >> 32) == 0 && "Selector key offset too large");
3253 Writer.SetSelectorOffset(Sel, Start);
3254 unsigned N = Sel.getNumArgs();
3255 LE.write<uint16_t>(N);
3256 if (N == 0)
3257 N = 1;
3258 for (unsigned I = 0; I != N; ++I)
3259 LE.write<uint32_t>(
3260 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3263 void EmitData(raw_ostream& Out, key_type_ref,
3264 data_type_ref Methods, unsigned DataLen) {
3265 using namespace llvm::support;
3267 endian::Writer LE(Out, little);
3268 uint64_t Start = Out.tell(); (void)Start;
3269 LE.write<uint32_t>(Methods.ID);
3270 unsigned NumInstanceMethods = 0;
3271 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3272 Method = Method->getNext())
3273 if (ShouldWriteMethodListNode(Method))
3274 ++NumInstanceMethods;
3276 unsigned NumFactoryMethods = 0;
3277 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3278 Method = Method->getNext())
3279 if (ShouldWriteMethodListNode(Method))
3280 ++NumFactoryMethods;
3282 unsigned InstanceBits = Methods.Instance.getBits();
3283 assert(InstanceBits < 4);
3284 unsigned InstanceHasMoreThanOneDeclBit =
3285 Methods.Instance.hasMoreThanOneDecl();
3286 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3287 (InstanceHasMoreThanOneDeclBit << 2) |
3288 InstanceBits;
3289 unsigned FactoryBits = Methods.Factory.getBits();
3290 assert(FactoryBits < 4);
3291 unsigned FactoryHasMoreThanOneDeclBit =
3292 Methods.Factory.hasMoreThanOneDecl();
3293 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3294 (FactoryHasMoreThanOneDeclBit << 2) |
3295 FactoryBits;
3296 LE.write<uint16_t>(FullInstanceBits);
3297 LE.write<uint16_t>(FullFactoryBits);
3298 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3299 Method = Method->getNext())
3300 if (ShouldWriteMethodListNode(Method))
3301 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3302 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3303 Method = Method->getNext())
3304 if (ShouldWriteMethodListNode(Method))
3305 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3307 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3310 private:
3311 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3312 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3316 } // namespace
3318 /// Write ObjC data: selectors and the method pool.
3320 /// The method pool contains both instance and factory methods, stored
3321 /// in an on-disk hash table indexed by the selector. The hash table also
3322 /// contains an empty entry for every other selector known to Sema.
3323 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3324 using namespace llvm;
3326 // Do we have to do anything at all?
3327 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3328 return;
3329 unsigned NumTableEntries = 0;
3330 // Create and write out the blob that contains selectors and the method pool.
3332 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3333 ASTMethodPoolTrait Trait(*this);
3335 // Create the on-disk hash table representation. We walk through every
3336 // selector we've seen and look it up in the method pool.
3337 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3338 for (auto &SelectorAndID : SelectorIDs) {
3339 Selector S = SelectorAndID.first;
3340 SelectorID ID = SelectorAndID.second;
3341 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3342 ASTMethodPoolTrait::data_type Data = {
3344 ObjCMethodList(),
3345 ObjCMethodList()
3347 if (F != SemaRef.MethodPool.end()) {
3348 Data.Instance = F->second.first;
3349 Data.Factory = F->second.second;
3351 // Only write this selector if it's not in an existing AST or something
3352 // changed.
3353 if (Chain && ID < FirstSelectorID) {
3354 // Selector already exists. Did it change?
3355 bool changed = false;
3356 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3357 M = M->getNext()) {
3358 if (!M->getMethod()->isFromASTFile()) {
3359 changed = true;
3360 Data.Instance = *M;
3361 break;
3364 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3365 M = M->getNext()) {
3366 if (!M->getMethod()->isFromASTFile()) {
3367 changed = true;
3368 Data.Factory = *M;
3369 break;
3372 if (!changed)
3373 continue;
3374 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3375 // A new method pool entry.
3376 ++NumTableEntries;
3378 Generator.insert(S, Data, Trait);
3381 // Create the on-disk hash table in a buffer.
3382 SmallString<4096> MethodPool;
3383 uint32_t BucketOffset;
3385 using namespace llvm::support;
3387 ASTMethodPoolTrait Trait(*this);
3388 llvm::raw_svector_ostream Out(MethodPool);
3389 // Make sure that no bucket is at offset 0
3390 endian::write<uint32_t>(Out, 0, little);
3391 BucketOffset = Generator.Emit(Out, Trait);
3394 // Create a blob abbreviation
3395 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3396 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3397 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3399 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3400 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3402 // Write the method pool
3404 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3405 NumTableEntries};
3406 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3409 // Create a blob abbreviation for the selector table offsets.
3410 Abbrev = std::make_shared<BitCodeAbbrev>();
3411 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3413 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3415 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3417 // Write the selector offsets table.
3419 RecordData::value_type Record[] = {
3420 SELECTOR_OFFSETS, SelectorOffsets.size(),
3421 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3422 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3423 bytes(SelectorOffsets));
3428 /// Write the selectors referenced in @selector expression into AST file.
3429 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3430 using namespace llvm;
3432 if (SemaRef.ReferencedSelectors.empty())
3433 return;
3435 RecordData Record;
3436 ASTRecordWriter Writer(*this, Record);
3438 // Note: this writes out all references even for a dependent AST. But it is
3439 // very tricky to fix, and given that @selector shouldn't really appear in
3440 // headers, probably not worth it. It's not a correctness issue.
3441 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3442 Selector Sel = SelectorAndLocation.first;
3443 SourceLocation Loc = SelectorAndLocation.second;
3444 Writer.AddSelectorRef(Sel);
3445 Writer.AddSourceLocation(Loc);
3447 Writer.Emit(REFERENCED_SELECTOR_POOL);
3450 //===----------------------------------------------------------------------===//
3451 // Identifier Table Serialization
3452 //===----------------------------------------------------------------------===//
3454 /// Determine the declaration that should be put into the name lookup table to
3455 /// represent the given declaration in this module. This is usually D itself,
3456 /// but if D was imported and merged into a local declaration, we want the most
3457 /// recent local declaration instead. The chosen declaration will be the most
3458 /// recent declaration in any module that imports this one.
3459 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3460 NamedDecl *D) {
3461 if (!LangOpts.Modules || !D->isFromASTFile())
3462 return D;
3464 if (Decl *Redecl = D->getPreviousDecl()) {
3465 // For Redeclarable decls, a prior declaration might be local.
3466 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3467 // If we find a local decl, we're done.
3468 if (!Redecl->isFromASTFile()) {
3469 // Exception: in very rare cases (for injected-class-names), not all
3470 // redeclarations are in the same semantic context. Skip ones in a
3471 // different context. They don't go in this lookup table at all.
3472 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3473 D->getDeclContext()->getRedeclContext()))
3474 continue;
3475 return cast<NamedDecl>(Redecl);
3478 // If we find a decl from a (chained-)PCH stop since we won't find a
3479 // local one.
3480 if (Redecl->getOwningModuleID() == 0)
3481 break;
3483 } else if (Decl *First = D->getCanonicalDecl()) {
3484 // For Mergeable decls, the first decl might be local.
3485 if (!First->isFromASTFile())
3486 return cast<NamedDecl>(First);
3489 // All declarations are imported. Our most recent declaration will also be
3490 // the most recent one in anyone who imports us.
3491 return D;
3494 namespace {
3496 class ASTIdentifierTableTrait {
3497 ASTWriter &Writer;
3498 Preprocessor &PP;
3499 IdentifierResolver &IdResolver;
3500 bool IsModule;
3501 bool NeedDecls;
3502 ASTWriter::RecordData *InterestingIdentifierOffsets;
3504 /// Determines whether this is an "interesting" identifier that needs a
3505 /// full IdentifierInfo structure written into the hash table. Notably, this
3506 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3507 /// to check that.
3508 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3509 if (MacroOffset || II->isPoisoned() ||
3510 (!IsModule && II->getObjCOrBuiltinID()) ||
3511 II->hasRevertedTokenIDToIdentifier() ||
3512 (NeedDecls && II->getFETokenInfo()))
3513 return true;
3515 return false;
3518 public:
3519 using key_type = IdentifierInfo *;
3520 using key_type_ref = key_type;
3522 using data_type = IdentID;
3523 using data_type_ref = data_type;
3525 using hash_value_type = unsigned;
3526 using offset_type = unsigned;
3528 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3529 IdentifierResolver &IdResolver, bool IsModule,
3530 ASTWriter::RecordData *InterestingIdentifierOffsets)
3531 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3532 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3533 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3535 bool needDecls() const { return NeedDecls; }
3537 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3538 return llvm::djbHash(II->getName());
3541 bool isInterestingIdentifier(const IdentifierInfo *II) {
3542 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3543 return isInterestingIdentifier(II, MacroOffset);
3546 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3547 return isInterestingIdentifier(II, 0);
3550 std::pair<unsigned, unsigned>
3551 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3552 // Record the location of the identifier data. This is used when generating
3553 // the mapping from persistent IDs to strings.
3554 Writer.SetIdentifierOffset(II, Out.tell());
3556 // Emit the offset of the key/data length information to the interesting
3557 // identifiers table if necessary.
3558 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3559 InterestingIdentifierOffsets->push_back(Out.tell());
3561 unsigned KeyLen = II->getLength() + 1;
3562 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3563 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3564 if (isInterestingIdentifier(II, MacroOffset)) {
3565 DataLen += 2; // 2 bytes for builtin ID
3566 DataLen += 2; // 2 bytes for flags
3567 if (MacroOffset)
3568 DataLen += 4; // MacroDirectives offset.
3570 if (NeedDecls)
3571 DataLen += std::distance(IdResolver.begin(II), IdResolver.end()) * 4;
3573 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3576 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3577 unsigned KeyLen) {
3578 Out.write(II->getNameStart(), KeyLen);
3581 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3582 IdentID ID, unsigned) {
3583 using namespace llvm::support;
3585 endian::Writer LE(Out, little);
3587 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3588 if (!isInterestingIdentifier(II, MacroOffset)) {
3589 LE.write<uint32_t>(ID << 1);
3590 return;
3593 LE.write<uint32_t>((ID << 1) | 0x01);
3594 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3595 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3596 LE.write<uint16_t>(Bits);
3597 Bits = 0;
3598 bool HadMacroDefinition = MacroOffset != 0;
3599 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3600 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3601 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3602 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3603 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3604 LE.write<uint16_t>(Bits);
3606 if (HadMacroDefinition)
3607 LE.write<uint32_t>(MacroOffset);
3609 if (NeedDecls) {
3610 // Emit the declaration IDs in reverse order, because the
3611 // IdentifierResolver provides the declarations as they would be
3612 // visible (e.g., the function "stat" would come before the struct
3613 // "stat"), but the ASTReader adds declarations to the end of the list
3614 // (so we need to see the struct "stat" before the function "stat").
3615 // Only emit declarations that aren't from a chained PCH, though.
3616 SmallVector<NamedDecl *, 16> Decls(IdResolver.decls(II));
3617 for (NamedDecl *D : llvm::reverse(Decls))
3618 LE.write<uint32_t>(
3619 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D)));
3624 } // namespace
3626 /// Write the identifier table into the AST file.
3628 /// The identifier table consists of a blob containing string data
3629 /// (the actual identifiers themselves) and a separate "offsets" index
3630 /// that maps identifier IDs to locations within the blob.
3631 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3632 IdentifierResolver &IdResolver,
3633 bool IsModule) {
3634 using namespace llvm;
3636 RecordData InterestingIdents;
3638 // Create and write out the blob that contains the identifier
3639 // strings.
3641 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3642 ASTIdentifierTableTrait Trait(
3643 *this, PP, IdResolver, IsModule,
3644 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3646 // Look for any identifiers that were named while processing the
3647 // headers, but are otherwise not needed. We add these to the hash
3648 // table to enable checking of the predefines buffer in the case
3649 // where the user adds new macro definitions when building the AST
3650 // file.
3651 SmallVector<const IdentifierInfo *, 128> IIs;
3652 for (const auto &ID : PP.getIdentifierTable())
3653 if (Trait.isInterestingNonMacroIdentifier(ID.second))
3654 IIs.push_back(ID.second);
3655 // Sort the identifiers lexicographically before getting the references so
3656 // that their order is stable.
3657 llvm::sort(IIs, llvm::deref<std::less<>>());
3658 for (const IdentifierInfo *II : IIs)
3659 getIdentifierRef(II);
3661 // Create the on-disk hash table representation. We only store offsets
3662 // for identifiers that appear here for the first time.
3663 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3664 for (auto IdentIDPair : IdentifierIDs) {
3665 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3666 IdentID ID = IdentIDPair.second;
3667 assert(II && "NULL identifier in identifier table");
3668 // Write out identifiers if either the ID is local or the identifier has
3669 // changed since it was loaded.
3670 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3671 || II->hasChangedSinceDeserialization() ||
3672 (Trait.needDecls() &&
3673 II->hasFETokenInfoChangedSinceDeserialization()))
3674 Generator.insert(II, ID, Trait);
3677 // Create the on-disk hash table in a buffer.
3678 SmallString<4096> IdentifierTable;
3679 uint32_t BucketOffset;
3681 using namespace llvm::support;
3683 llvm::raw_svector_ostream Out(IdentifierTable);
3684 // Make sure that no bucket is at offset 0
3685 endian::write<uint32_t>(Out, 0, little);
3686 BucketOffset = Generator.Emit(Out, Trait);
3689 // Create a blob abbreviation
3690 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3691 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3692 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3693 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3694 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3696 // Write the identifier table
3697 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3698 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3701 // Write the offsets table for identifier IDs.
3702 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3703 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3707 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3709 #ifndef NDEBUG
3710 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3711 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3712 #endif
3714 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3715 IdentifierOffsets.size(),
3716 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3717 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3718 bytes(IdentifierOffsets));
3720 // In C++, write the list of interesting identifiers (those that are
3721 // defined as macros, poisoned, or similar unusual things).
3722 if (!InterestingIdents.empty())
3723 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3726 //===----------------------------------------------------------------------===//
3727 // DeclContext's Name Lookup Table Serialization
3728 //===----------------------------------------------------------------------===//
3730 namespace {
3732 // Trait used for the on-disk hash table used in the method pool.
3733 class ASTDeclContextNameLookupTrait {
3734 ASTWriter &Writer;
3735 llvm::SmallVector<DeclID, 64> DeclIDs;
3737 public:
3738 using key_type = DeclarationNameKey;
3739 using key_type_ref = key_type;
3741 /// A start and end index into DeclIDs, representing a sequence of decls.
3742 using data_type = std::pair<unsigned, unsigned>;
3743 using data_type_ref = const data_type &;
3745 using hash_value_type = unsigned;
3746 using offset_type = unsigned;
3748 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3750 template<typename Coll>
3751 data_type getData(const Coll &Decls) {
3752 unsigned Start = DeclIDs.size();
3753 for (NamedDecl *D : Decls) {
3754 DeclIDs.push_back(
3755 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3757 return std::make_pair(Start, DeclIDs.size());
3760 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3761 unsigned Start = DeclIDs.size();
3762 llvm::append_range(DeclIDs, FromReader);
3763 return std::make_pair(Start, DeclIDs.size());
3766 static bool EqualKey(key_type_ref a, key_type_ref b) {
3767 return a == b;
3770 hash_value_type ComputeHash(DeclarationNameKey Name) {
3771 return Name.getHash();
3774 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3775 assert(Writer.hasChain() &&
3776 "have reference to loaded module file but no chain?");
3778 using namespace llvm::support;
3780 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3783 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3784 DeclarationNameKey Name,
3785 data_type_ref Lookup) {
3786 unsigned KeyLen = 1;
3787 switch (Name.getKind()) {
3788 case DeclarationName::Identifier:
3789 case DeclarationName::ObjCZeroArgSelector:
3790 case DeclarationName::ObjCOneArgSelector:
3791 case DeclarationName::ObjCMultiArgSelector:
3792 case DeclarationName::CXXLiteralOperatorName:
3793 case DeclarationName::CXXDeductionGuideName:
3794 KeyLen += 4;
3795 break;
3796 case DeclarationName::CXXOperatorName:
3797 KeyLen += 1;
3798 break;
3799 case DeclarationName::CXXConstructorName:
3800 case DeclarationName::CXXDestructorName:
3801 case DeclarationName::CXXConversionFunctionName:
3802 case DeclarationName::CXXUsingDirective:
3803 break;
3806 // 4 bytes for each DeclID.
3807 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3809 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3812 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3813 using namespace llvm::support;
3815 endian::Writer LE(Out, little);
3816 LE.write<uint8_t>(Name.getKind());
3817 switch (Name.getKind()) {
3818 case DeclarationName::Identifier:
3819 case DeclarationName::CXXLiteralOperatorName:
3820 case DeclarationName::CXXDeductionGuideName:
3821 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3822 return;
3823 case DeclarationName::ObjCZeroArgSelector:
3824 case DeclarationName::ObjCOneArgSelector:
3825 case DeclarationName::ObjCMultiArgSelector:
3826 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3827 return;
3828 case DeclarationName::CXXOperatorName:
3829 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3830 "Invalid operator?");
3831 LE.write<uint8_t>(Name.getOperatorKind());
3832 return;
3833 case DeclarationName::CXXConstructorName:
3834 case DeclarationName::CXXDestructorName:
3835 case DeclarationName::CXXConversionFunctionName:
3836 case DeclarationName::CXXUsingDirective:
3837 return;
3840 llvm_unreachable("Invalid name kind?");
3843 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3844 unsigned DataLen) {
3845 using namespace llvm::support;
3847 endian::Writer LE(Out, little);
3848 uint64_t Start = Out.tell(); (void)Start;
3849 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3850 LE.write<uint32_t>(DeclIDs[I]);
3851 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3855 } // namespace
3857 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3858 DeclContext *DC) {
3859 return Result.hasExternalDecls() &&
3860 DC->hasNeedToReconcileExternalVisibleStorage();
3863 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3864 DeclContext *DC) {
3865 for (auto *D : Result.getLookupResult())
3866 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3867 return false;
3869 return true;
3872 void
3873 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3874 llvm::SmallVectorImpl<char> &LookupTable) {
3875 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3876 !ConstDC->hasLazyExternalLexicalLookups() &&
3877 "must call buildLookups first");
3879 // FIXME: We need to build the lookups table, which is logically const.
3880 auto *DC = const_cast<DeclContext*>(ConstDC);
3881 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3883 // Create the on-disk hash table representation.
3884 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3885 ASTDeclContextNameLookupTrait> Generator;
3886 ASTDeclContextNameLookupTrait Trait(*this);
3888 // The first step is to collect the declaration names which we need to
3889 // serialize into the name lookup table, and to collect them in a stable
3890 // order.
3891 SmallVector<DeclarationName, 16> Names;
3893 // We also build up small sets of the constructor and conversion function
3894 // names which are visible.
3895 llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3897 for (auto &Lookup : *DC->buildLookup()) {
3898 auto &Name = Lookup.first;
3899 auto &Result = Lookup.second;
3901 // If there are no local declarations in our lookup result, we
3902 // don't need to write an entry for the name at all. If we can't
3903 // write out a lookup set without performing more deserialization,
3904 // just skip this entry.
3905 if (isLookupResultExternal(Result, DC) &&
3906 isLookupResultEntirelyExternal(Result, DC))
3907 continue;
3909 // We also skip empty results. If any of the results could be external and
3910 // the currently available results are empty, then all of the results are
3911 // external and we skip it above. So the only way we get here with an empty
3912 // results is when no results could have been external *and* we have
3913 // external results.
3915 // FIXME: While we might want to start emitting on-disk entries for negative
3916 // lookups into a decl context as an optimization, today we *have* to skip
3917 // them because there are names with empty lookup results in decl contexts
3918 // which we can't emit in any stable ordering: we lookup constructors and
3919 // conversion functions in the enclosing namespace scope creating empty
3920 // results for them. This in almost certainly a bug in Clang's name lookup,
3921 // but that is likely to be hard or impossible to fix and so we tolerate it
3922 // here by omitting lookups with empty results.
3923 if (Lookup.second.getLookupResult().empty())
3924 continue;
3926 switch (Lookup.first.getNameKind()) {
3927 default:
3928 Names.push_back(Lookup.first);
3929 break;
3931 case DeclarationName::CXXConstructorName:
3932 assert(isa<CXXRecordDecl>(DC) &&
3933 "Cannot have a constructor name outside of a class!");
3934 ConstructorNameSet.insert(Name);
3935 break;
3937 case DeclarationName::CXXConversionFunctionName:
3938 assert(isa<CXXRecordDecl>(DC) &&
3939 "Cannot have a conversion function name outside of a class!");
3940 ConversionNameSet.insert(Name);
3941 break;
3945 // Sort the names into a stable order.
3946 llvm::sort(Names);
3948 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3949 // We need to establish an ordering of constructor and conversion function
3950 // names, and they don't have an intrinsic ordering.
3952 // First we try the easy case by forming the current context's constructor
3953 // name and adding that name first. This is a very useful optimization to
3954 // avoid walking the lexical declarations in many cases, and it also
3955 // handles the only case where a constructor name can come from some other
3956 // lexical context -- when that name is an implicit constructor merged from
3957 // another declaration in the redecl chain. Any non-implicit constructor or
3958 // conversion function which doesn't occur in all the lexical contexts
3959 // would be an ODR violation.
3960 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3961 Context->getCanonicalType(Context->getRecordType(D)));
3962 if (ConstructorNameSet.erase(ImplicitCtorName))
3963 Names.push_back(ImplicitCtorName);
3965 // If we still have constructors or conversion functions, we walk all the
3966 // names in the decl and add the constructors and conversion functions
3967 // which are visible in the order they lexically occur within the context.
3968 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3969 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3970 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3971 auto Name = ChildND->getDeclName();
3972 switch (Name.getNameKind()) {
3973 default:
3974 continue;
3976 case DeclarationName::CXXConstructorName:
3977 if (ConstructorNameSet.erase(Name))
3978 Names.push_back(Name);
3979 break;
3981 case DeclarationName::CXXConversionFunctionName:
3982 if (ConversionNameSet.erase(Name))
3983 Names.push_back(Name);
3984 break;
3987 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3988 break;
3991 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3992 "constructors by walking all the "
3993 "lexical members of the context.");
3994 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3995 "conversion functions by walking all "
3996 "the lexical members of the context.");
3999 // Next we need to do a lookup with each name into this decl context to fully
4000 // populate any results from external sources. We don't actually use the
4001 // results of these lookups because we only want to use the results after all
4002 // results have been loaded and the pointers into them will be stable.
4003 for (auto &Name : Names)
4004 DC->lookup(Name);
4006 // Now we need to insert the results for each name into the hash table. For
4007 // constructor names and conversion function names, we actually need to merge
4008 // all of the results for them into one list of results each and insert
4009 // those.
4010 SmallVector<NamedDecl *, 8> ConstructorDecls;
4011 SmallVector<NamedDecl *, 8> ConversionDecls;
4013 // Now loop over the names, either inserting them or appending for the two
4014 // special cases.
4015 for (auto &Name : Names) {
4016 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4018 switch (Name.getNameKind()) {
4019 default:
4020 Generator.insert(Name, Trait.getData(Result), Trait);
4021 break;
4023 case DeclarationName::CXXConstructorName:
4024 ConstructorDecls.append(Result.begin(), Result.end());
4025 break;
4027 case DeclarationName::CXXConversionFunctionName:
4028 ConversionDecls.append(Result.begin(), Result.end());
4029 break;
4033 // Handle our two special cases if we ended up having any. We arbitrarily use
4034 // the first declaration's name here because the name itself isn't part of
4035 // the key, only the kind of name is used.
4036 if (!ConstructorDecls.empty())
4037 Generator.insert(ConstructorDecls.front()->getDeclName(),
4038 Trait.getData(ConstructorDecls), Trait);
4039 if (!ConversionDecls.empty())
4040 Generator.insert(ConversionDecls.front()->getDeclName(),
4041 Trait.getData(ConversionDecls), Trait);
4043 // Create the on-disk hash table. Also emit the existing imported and
4044 // merged table if there is one.
4045 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4046 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4049 /// Write the block containing all of the declaration IDs
4050 /// visible from the given DeclContext.
4052 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4053 /// bitstream, or 0 if no block was written.
4054 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4055 DeclContext *DC) {
4056 // If we imported a key declaration of this namespace, write the visible
4057 // lookup results as an update record for it rather than including them
4058 // on this declaration. We will only look at key declarations on reload.
4059 if (isa<NamespaceDecl>(DC) && Chain &&
4060 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4061 // Only do this once, for the first local declaration of the namespace.
4062 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4063 Prev = Prev->getPreviousDecl())
4064 if (!Prev->isFromASTFile())
4065 return 0;
4067 // Note that we need to emit an update record for the primary context.
4068 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4070 // Make sure all visible decls are written. They will be recorded later. We
4071 // do this using a side data structure so we can sort the names into
4072 // a deterministic order.
4073 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4074 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4075 LookupResults;
4076 if (Map) {
4077 LookupResults.reserve(Map->size());
4078 for (auto &Entry : *Map)
4079 LookupResults.push_back(
4080 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4083 llvm::sort(LookupResults, llvm::less_first());
4084 for (auto &NameAndResult : LookupResults) {
4085 DeclarationName Name = NameAndResult.first;
4086 DeclContext::lookup_result Result = NameAndResult.second;
4087 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4088 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4089 // We have to work around a name lookup bug here where negative lookup
4090 // results for these names get cached in namespace lookup tables (these
4091 // names should never be looked up in a namespace).
4092 assert(Result.empty() && "Cannot have a constructor or conversion "
4093 "function name in a namespace!");
4094 continue;
4097 for (NamedDecl *ND : Result)
4098 if (!ND->isFromASTFile())
4099 GetDeclRef(ND);
4102 return 0;
4105 if (DC->getPrimaryContext() != DC)
4106 return 0;
4108 // Skip contexts which don't support name lookup.
4109 if (!DC->isLookupContext())
4110 return 0;
4112 // If not in C++, we perform name lookup for the translation unit via the
4113 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4114 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4115 return 0;
4117 // Serialize the contents of the mapping used for lookup. Note that,
4118 // although we have two very different code paths, the serialized
4119 // representation is the same for both cases: a declaration name,
4120 // followed by a size, followed by references to the visible
4121 // declarations that have that name.
4122 uint64_t Offset = Stream.GetCurrentBitNo();
4123 StoredDeclsMap *Map = DC->buildLookup();
4124 if (!Map || Map->empty())
4125 return 0;
4127 // Create the on-disk hash table in a buffer.
4128 SmallString<4096> LookupTable;
4129 GenerateNameLookupTable(DC, LookupTable);
4131 // Write the lookup table
4132 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4133 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4134 LookupTable);
4135 ++NumVisibleDeclContexts;
4136 return Offset;
4139 /// Write an UPDATE_VISIBLE block for the given context.
4141 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4142 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4143 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4144 /// enumeration members (in C++11).
4145 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4146 StoredDeclsMap *Map = DC->getLookupPtr();
4147 if (!Map || Map->empty())
4148 return;
4150 // Create the on-disk hash table in a buffer.
4151 SmallString<4096> LookupTable;
4152 GenerateNameLookupTable(DC, LookupTable);
4154 // If we're updating a namespace, select a key declaration as the key for the
4155 // update record; those are the only ones that will be checked on reload.
4156 if (isa<NamespaceDecl>(DC))
4157 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4159 // Write the lookup table
4160 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4161 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4164 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4165 void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4166 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4167 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4170 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4171 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4172 if (!SemaRef.Context.getLangOpts().OpenCL)
4173 return;
4175 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4176 RecordData Record;
4177 for (const auto &I:Opts.OptMap) {
4178 AddString(I.getKey(), Record);
4179 auto V = I.getValue();
4180 Record.push_back(V.Supported ? 1 : 0);
4181 Record.push_back(V.Enabled ? 1 : 0);
4182 Record.push_back(V.WithPragma ? 1 : 0);
4183 Record.push_back(V.Avail);
4184 Record.push_back(V.Core);
4185 Record.push_back(V.Opt);
4187 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4189 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4190 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4191 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4192 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4196 void ASTWriter::WriteObjCCategories() {
4197 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4198 RecordData Categories;
4200 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4201 unsigned Size = 0;
4202 unsigned StartIndex = Categories.size();
4204 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4206 // Allocate space for the size.
4207 Categories.push_back(0);
4209 // Add the categories.
4210 for (ObjCInterfaceDecl::known_categories_iterator
4211 Cat = Class->known_categories_begin(),
4212 CatEnd = Class->known_categories_end();
4213 Cat != CatEnd; ++Cat, ++Size) {
4214 assert(getDeclID(*Cat) != 0 && "Bogus category");
4215 AddDeclRef(*Cat, Categories);
4218 // Update the size.
4219 Categories[StartIndex] = Size;
4221 // Record this interface -> category map.
4222 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4223 CategoriesMap.push_back(CatInfo);
4226 // Sort the categories map by the definition ID, since the reader will be
4227 // performing binary searches on this information.
4228 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4230 // Emit the categories map.
4231 using namespace llvm;
4233 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4234 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4235 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4236 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4237 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4239 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4240 Stream.EmitRecordWithBlob(AbbrevID, Record,
4241 reinterpret_cast<char *>(CategoriesMap.data()),
4242 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4244 // Emit the category lists.
4245 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4248 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4249 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4251 if (LPTMap.empty())
4252 return;
4254 RecordData Record;
4255 for (auto &LPTMapEntry : LPTMap) {
4256 const FunctionDecl *FD = LPTMapEntry.first;
4257 LateParsedTemplate &LPT = *LPTMapEntry.second;
4258 AddDeclRef(FD, Record);
4259 AddDeclRef(LPT.D, Record);
4260 Record.push_back(LPT.Toks.size());
4262 for (const auto &Tok : LPT.Toks) {
4263 AddToken(Tok, Record);
4266 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4269 /// Write the state of 'pragma clang optimize' at the end of the module.
4270 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4271 RecordData Record;
4272 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4273 AddSourceLocation(PragmaLoc, Record);
4274 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4277 /// Write the state of 'pragma ms_struct' at the end of the module.
4278 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4279 RecordData Record;
4280 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4281 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4284 /// Write the state of 'pragma pointers_to_members' at the end of the
4285 //module.
4286 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4287 RecordData Record;
4288 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4289 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4290 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4293 /// Write the state of 'pragma align/pack' at the end of the module.
4294 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4295 // Don't serialize pragma align/pack state for modules, since it should only
4296 // take effect on a per-submodule basis.
4297 if (WritingModule)
4298 return;
4300 RecordData Record;
4301 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4302 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4303 Record.push_back(SemaRef.AlignPackStack.Stack.size());
4304 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4305 AddAlignPackInfo(StackEntry.Value, Record);
4306 AddSourceLocation(StackEntry.PragmaLocation, Record);
4307 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4308 AddString(StackEntry.StackSlotLabel, Record);
4310 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4313 /// Write the state of 'pragma float_control' at the end of the module.
4314 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4315 // Don't serialize pragma float_control state for modules,
4316 // since it should only take effect on a per-submodule basis.
4317 if (WritingModule)
4318 return;
4320 RecordData Record;
4321 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4322 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4323 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4324 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4325 Record.push_back(StackEntry.Value.getAsOpaqueInt());
4326 AddSourceLocation(StackEntry.PragmaLocation, Record);
4327 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4328 AddString(StackEntry.StackSlotLabel, Record);
4330 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4333 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4334 ModuleFileExtensionWriter &Writer) {
4335 // Enter the extension block.
4336 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4338 // Emit the metadata record abbreviation.
4339 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4340 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4341 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4342 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4343 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4344 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4345 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4346 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4348 // Emit the metadata record.
4349 RecordData Record;
4350 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4351 Record.push_back(EXTENSION_METADATA);
4352 Record.push_back(Metadata.MajorVersion);
4353 Record.push_back(Metadata.MinorVersion);
4354 Record.push_back(Metadata.BlockName.size());
4355 Record.push_back(Metadata.UserInfo.size());
4356 SmallString<64> Buffer;
4357 Buffer += Metadata.BlockName;
4358 Buffer += Metadata.UserInfo;
4359 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4361 // Emit the contents of the extension block.
4362 Writer.writeExtensionContents(SemaRef, Stream);
4364 // Exit the extension block.
4365 Stream.ExitBlock();
4368 //===----------------------------------------------------------------------===//
4369 // General Serialization Routines
4370 //===----------------------------------------------------------------------===//
4372 void ASTRecordWriter::AddAttr(const Attr *A) {
4373 auto &Record = *this;
4374 // FIXME: Clang can't handle the serialization/deserialization of
4375 // preferred_name properly now. See
4376 // https://github.com/llvm/llvm-project/issues/56490 for example.
4377 if (!A || (isa<PreferredNameAttr>(A) &&
4378 Writer->isWritingStdCXXNamedModules()))
4379 return Record.push_back(0);
4381 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4383 Record.AddIdentifierRef(A->getAttrName());
4384 Record.AddIdentifierRef(A->getScopeName());
4385 Record.AddSourceRange(A->getRange());
4386 Record.AddSourceLocation(A->getScopeLoc());
4387 Record.push_back(A->getParsedKind());
4388 Record.push_back(A->getSyntax());
4389 Record.push_back(A->getAttributeSpellingListIndexRaw());
4390 Record.push_back(A->isRegularKeywordAttribute());
4392 #include "clang/Serialization/AttrPCHWrite.inc"
4395 /// Emit the list of attributes to the specified record.
4396 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4397 push_back(Attrs.size());
4398 for (const auto *A : Attrs)
4399 AddAttr(A);
4402 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4403 AddSourceLocation(Tok.getLocation(), Record);
4404 // FIXME: Should translate token kind to a stable encoding.
4405 Record.push_back(Tok.getKind());
4406 // FIXME: Should translate token flags to a stable encoding.
4407 Record.push_back(Tok.getFlags());
4409 if (Tok.isAnnotation()) {
4410 AddSourceLocation(Tok.getAnnotationEndLoc(), Record);
4411 switch (Tok.getKind()) {
4412 case tok::annot_pragma_loop_hint: {
4413 auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
4414 AddToken(Info->PragmaName, Record);
4415 AddToken(Info->Option, Record);
4416 Record.push_back(Info->Toks.size());
4417 for (const auto &T : Info->Toks)
4418 AddToken(T, Record);
4419 break;
4421 case tok::annot_pragma_pack: {
4422 auto *Info =
4423 static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
4424 Record.push_back(static_cast<unsigned>(Info->Action));
4425 AddString(Info->SlotLabel, Record);
4426 AddToken(Info->Alignment, Record);
4427 break;
4429 // Some annotation tokens do not use the PtrData field.
4430 case tok::annot_pragma_openmp:
4431 case tok::annot_pragma_openmp_end:
4432 case tok::annot_pragma_unused:
4433 break;
4434 default:
4435 llvm_unreachable("missing serialization code for annotation token");
4437 } else {
4438 Record.push_back(Tok.getLength());
4439 // FIXME: When reading literal tokens, reconstruct the literal pointer if it
4440 // is needed.
4441 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4445 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4446 Record.push_back(Str.size());
4447 Record.insert(Record.end(), Str.begin(), Str.end());
4450 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4451 assert(Context && "should have context when outputting path");
4453 // Leave special file names as they are.
4454 StringRef PathStr(Path.data(), Path.size());
4455 if (PathStr == "<built-in>" || PathStr == "<command line>")
4456 return false;
4458 bool Changed =
4459 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4461 // Remove a prefix to make the path relative, if relevant.
4462 const char *PathBegin = Path.data();
4463 const char *PathPtr =
4464 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4465 if (PathPtr != PathBegin) {
4466 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4467 Changed = true;
4470 return Changed;
4473 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4474 SmallString<128> FilePath(Path);
4475 PreparePathForOutput(FilePath);
4476 AddString(FilePath, Record);
4479 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4480 StringRef Path) {
4481 SmallString<128> FilePath(Path);
4482 PreparePathForOutput(FilePath);
4483 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4486 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4487 RecordDataImpl &Record) {
4488 Record.push_back(Version.getMajor());
4489 if (std::optional<unsigned> Minor = Version.getMinor())
4490 Record.push_back(*Minor + 1);
4491 else
4492 Record.push_back(0);
4493 if (std::optional<unsigned> Subminor = Version.getSubminor())
4494 Record.push_back(*Subminor + 1);
4495 else
4496 Record.push_back(0);
4499 /// Note that the identifier II occurs at the given offset
4500 /// within the identifier table.
4501 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4502 IdentID ID = IdentifierIDs[II];
4503 // Only store offsets new to this AST file. Other identifier names are looked
4504 // up earlier in the chain and thus don't need an offset.
4505 if (ID >= FirstIdentID)
4506 IdentifierOffsets[ID - FirstIdentID] = Offset;
4509 /// Note that the selector Sel occurs at the given offset
4510 /// within the method pool/selector table.
4511 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4512 unsigned ID = SelectorIDs[Sel];
4513 assert(ID && "Unknown selector");
4514 // Don't record offsets for selectors that are also available in a different
4515 // file.
4516 if (ID < FirstSelectorID)
4517 return;
4518 SelectorOffsets[ID - FirstSelectorID] = Offset;
4521 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4522 SmallVectorImpl<char> &Buffer,
4523 InMemoryModuleCache &ModuleCache,
4524 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4525 bool IncludeTimestamps)
4526 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4527 IncludeTimestamps(IncludeTimestamps) {
4528 for (const auto &Ext : Extensions) {
4529 if (auto Writer = Ext->createExtensionWriter(*this))
4530 ModuleFileExtensionWriters.push_back(std::move(Writer));
4534 ASTWriter::~ASTWriter() = default;
4536 const LangOptions &ASTWriter::getLangOpts() const {
4537 assert(WritingAST && "can't determine lang opts when not writing AST");
4538 return Context->getLangOpts();
4541 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4542 return IncludeTimestamps ? E->getModificationTime() : 0;
4545 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, StringRef OutputFile,
4546 Module *WritingModule, StringRef isysroot,
4547 bool hasErrors,
4548 bool ShouldCacheASTInMemory) {
4549 llvm::TimeTraceScope scope("WriteAST", OutputFile);
4550 WritingAST = true;
4552 ASTHasCompilerErrors = hasErrors;
4554 // Emit the file header.
4555 Stream.Emit((unsigned)'C', 8);
4556 Stream.Emit((unsigned)'P', 8);
4557 Stream.Emit((unsigned)'C', 8);
4558 Stream.Emit((unsigned)'H', 8);
4560 WriteBlockInfoBlock();
4562 Context = &SemaRef.Context;
4563 PP = &SemaRef.PP;
4564 this->WritingModule = WritingModule;
4565 ASTFileSignature Signature = WriteASTCore(SemaRef, isysroot, WritingModule);
4566 Context = nullptr;
4567 PP = nullptr;
4568 this->WritingModule = nullptr;
4569 this->BaseDirectory.clear();
4571 WritingAST = false;
4572 if (ShouldCacheASTInMemory) {
4573 // Construct MemoryBuffer and update buffer manager.
4574 ModuleCache.addBuiltPCM(OutputFile,
4575 llvm::MemoryBuffer::getMemBufferCopy(
4576 StringRef(Buffer.begin(), Buffer.size())));
4578 return Signature;
4581 template<typename Vector>
4582 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4583 ASTWriter::RecordData &Record) {
4584 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4585 I != E; ++I) {
4586 Writer.AddDeclRef(*I, Record);
4590 void ASTWriter::collectNonAffectingInputFiles() {
4591 SourceManager &SrcMgr = PP->getSourceManager();
4592 unsigned N = SrcMgr.local_sloc_entry_size();
4594 IsSLocAffecting.resize(N, true);
4596 if (!WritingModule)
4597 return;
4599 auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
4601 unsigned FileIDAdjustment = 0;
4602 unsigned OffsetAdjustment = 0;
4604 NonAffectingFileIDAdjustments.reserve(N);
4605 NonAffectingOffsetAdjustments.reserve(N);
4607 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4608 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4610 for (unsigned I = 1; I != N; ++I) {
4611 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(I);
4612 FileID FID = FileID::get(I);
4613 assert(&SrcMgr.getSLocEntry(FID) == SLoc);
4615 if (!SLoc->isFile())
4616 continue;
4617 const SrcMgr::FileInfo &File = SLoc->getFile();
4618 const SrcMgr::ContentCache *Cache = &File.getContentCache();
4619 if (!Cache->OrigEntry)
4620 continue;
4622 if (!isModuleMap(File.getFileCharacteristic()) ||
4623 AffectingModuleMaps.empty() ||
4624 AffectingModuleMaps.find(Cache->OrigEntry) != AffectingModuleMaps.end())
4625 continue;
4627 IsSLocAffecting[I] = false;
4629 FileIDAdjustment += 1;
4630 // Even empty files take up one element in the offset table.
4631 OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
4633 // If the previous file was non-affecting as well, just extend its entry
4634 // with our information.
4635 if (!NonAffectingFileIDs.empty() &&
4636 NonAffectingFileIDs.back().ID == FID.ID - 1) {
4637 NonAffectingFileIDs.back() = FID;
4638 NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
4639 NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
4640 NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
4641 continue;
4644 NonAffectingFileIDs.push_back(FID);
4645 NonAffectingRanges.emplace_back(SrcMgr.getLocForStartOfFile(FID),
4646 SrcMgr.getLocForEndOfFile(FID));
4647 NonAffectingFileIDAdjustments.push_back(FileIDAdjustment);
4648 NonAffectingOffsetAdjustments.push_back(OffsetAdjustment);
4652 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4653 Module *WritingModule) {
4654 using namespace llvm;
4656 bool isModule = WritingModule != nullptr;
4658 // Make sure that the AST reader knows to finalize itself.
4659 if (Chain)
4660 Chain->finalizeForWriting();
4662 ASTContext &Context = SemaRef.Context;
4663 Preprocessor &PP = SemaRef.PP;
4665 collectNonAffectingInputFiles();
4667 // Set up predefined declaration IDs.
4668 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4669 if (D) {
4670 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4671 DeclIDs[D] = ID;
4674 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4675 PREDEF_DECL_TRANSLATION_UNIT_ID);
4676 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4677 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4678 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4679 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4680 PREDEF_DECL_OBJC_PROTOCOL_ID);
4681 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4682 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4683 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4684 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4685 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4686 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4687 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4688 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4689 RegisterPredefDecl(Context.MSGuidTagDecl,
4690 PREDEF_DECL_BUILTIN_MS_GUID_ID);
4691 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4692 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4693 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4694 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4695 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4696 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4697 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4698 RegisterPredefDecl(Context.TypePackElementDecl,
4699 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4701 // Build a record containing all of the tentative definitions in this file, in
4702 // TentativeDefinitions order. Generally, this record will be empty for
4703 // headers.
4704 RecordData TentativeDefinitions;
4705 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4707 // Build a record containing all of the file scoped decls in this file.
4708 RecordData UnusedFileScopedDecls;
4709 if (!isModule)
4710 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4711 UnusedFileScopedDecls);
4713 // Build a record containing all of the delegating constructors we still need
4714 // to resolve.
4715 RecordData DelegatingCtorDecls;
4716 if (!isModule)
4717 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4719 // Write the set of weak, undeclared identifiers. We always write the
4720 // entire table, since later PCH files in a PCH chain are only interested in
4721 // the results at the end of the chain.
4722 RecordData WeakUndeclaredIdentifiers;
4723 for (const auto &WeakUndeclaredIdentifierList :
4724 SemaRef.WeakUndeclaredIdentifiers) {
4725 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
4726 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
4727 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4728 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4729 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4733 // Build a record containing all of the ext_vector declarations.
4734 RecordData ExtVectorDecls;
4735 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4737 // Build a record containing all of the VTable uses information.
4738 RecordData VTableUses;
4739 if (!SemaRef.VTableUses.empty()) {
4740 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4741 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4742 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4743 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4747 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4748 RecordData UnusedLocalTypedefNameCandidates;
4749 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4750 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4752 // Build a record containing all of pending implicit instantiations.
4753 RecordData PendingInstantiations;
4754 for (const auto &I : SemaRef.PendingInstantiations) {
4755 AddDeclRef(I.first, PendingInstantiations);
4756 AddSourceLocation(I.second, PendingInstantiations);
4758 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4759 "There are local ones at end of translation unit!");
4761 // Build a record containing some declaration references.
4762 RecordData SemaDeclRefs;
4763 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4764 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4765 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4766 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4769 RecordData CUDASpecialDeclRefs;
4770 if (Context.getcudaConfigureCallDecl()) {
4771 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4774 // Build a record containing all of the known namespaces.
4775 RecordData KnownNamespaces;
4776 for (const auto &I : SemaRef.KnownNamespaces) {
4777 if (!I.second)
4778 AddDeclRef(I.first, KnownNamespaces);
4781 // Build a record of all used, undefined objects that require definitions.
4782 RecordData UndefinedButUsed;
4784 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4785 SemaRef.getUndefinedButUsed(Undefined);
4786 for (const auto &I : Undefined) {
4787 AddDeclRef(I.first, UndefinedButUsed);
4788 AddSourceLocation(I.second, UndefinedButUsed);
4791 // Build a record containing all delete-expressions that we would like to
4792 // analyze later in AST.
4793 RecordData DeleteExprsToAnalyze;
4795 if (!isModule) {
4796 for (const auto &DeleteExprsInfo :
4797 SemaRef.getMismatchingDeleteExpressions()) {
4798 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4799 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4800 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4801 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4802 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4807 // Write the control block
4808 WriteControlBlock(PP, Context, isysroot);
4810 // Write the remaining AST contents.
4811 Stream.FlushToWord();
4812 ASTBlockRange.first = Stream.GetCurrentBitNo();
4813 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4814 ASTBlockStartOffset = Stream.GetCurrentBitNo();
4816 // This is so that older clang versions, before the introduction
4817 // of the control block, can read and reject the newer PCH format.
4819 RecordData Record = {VERSION_MAJOR};
4820 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4823 // Create a lexical update block containing all of the declarations in the
4824 // translation unit that do not come from other AST files.
4825 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4826 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4827 for (const auto *D : TU->noload_decls()) {
4828 if (!D->isFromASTFile()) {
4829 NewGlobalKindDeclPairs.push_back(D->getKind());
4830 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4834 auto Abv = std::make_shared<BitCodeAbbrev>();
4835 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4836 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4837 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4839 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4840 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4841 bytes(NewGlobalKindDeclPairs));
4844 // And a visible updates block for the translation unit.
4845 Abv = std::make_shared<BitCodeAbbrev>();
4846 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4847 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4848 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4849 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4850 WriteDeclContextVisibleUpdate(TU);
4852 // If we have any extern "C" names, write out a visible update for them.
4853 if (Context.ExternCContext)
4854 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4856 // If the translation unit has an anonymous namespace, and we don't already
4857 // have an update block for it, write it as an update block.
4858 // FIXME: Why do we not do this if there's already an update block?
4859 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4860 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4861 if (Record.empty())
4862 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4865 // Add update records for all mangling numbers and static local numbers.
4866 // These aren't really update records, but this is a convenient way of
4867 // tagging this rare extra data onto the declarations.
4868 for (const auto &Number : Context.MangleNumbers)
4869 if (!Number.first->isFromASTFile())
4870 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4871 Number.second));
4872 for (const auto &Number : Context.StaticLocalNumbers)
4873 if (!Number.first->isFromASTFile())
4874 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4875 Number.second));
4877 // Make sure visible decls, added to DeclContexts previously loaded from
4878 // an AST file, are registered for serialization. Likewise for template
4879 // specializations added to imported templates.
4880 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4881 GetDeclRef(I);
4884 // Make sure all decls associated with an identifier are registered for
4885 // serialization, if we're storing decls with identifiers.
4886 if (!WritingModule || !getLangOpts().CPlusPlus) {
4887 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4888 for (const auto &ID : PP.getIdentifierTable()) {
4889 const IdentifierInfo *II = ID.second;
4890 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4891 IIs.push_back(II);
4893 // Sort the identifiers to visit based on their name.
4894 llvm::sort(IIs, llvm::deref<std::less<>>());
4895 for (const IdentifierInfo *II : IIs)
4896 for (const Decl *D : SemaRef.IdResolver.decls(II))
4897 GetDeclRef(D);
4900 // For method pool in the module, if it contains an entry for a selector,
4901 // the entry should be complete, containing everything introduced by that
4902 // module and all modules it imports. It's possible that the entry is out of
4903 // date, so we need to pull in the new content here.
4905 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4906 // safe, we copy all selectors out.
4907 llvm::SmallVector<Selector, 256> AllSelectors;
4908 for (auto &SelectorAndID : SelectorIDs)
4909 AllSelectors.push_back(SelectorAndID.first);
4910 for (auto &Selector : AllSelectors)
4911 SemaRef.updateOutOfDateSelector(Selector);
4913 // Form the record of special types.
4914 RecordData SpecialTypes;
4915 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4916 AddTypeRef(Context.getFILEType(), SpecialTypes);
4917 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4918 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4919 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4920 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4921 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4922 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4924 if (Chain) {
4925 // Write the mapping information describing our module dependencies and how
4926 // each of those modules were mapped into our own offset/ID space, so that
4927 // the reader can build the appropriate mapping to its own offset/ID space.
4928 // The map consists solely of a blob with the following format:
4929 // *(module-kind:i8
4930 // module-name-len:i16 module-name:len*i8
4931 // source-location-offset:i32
4932 // identifier-id:i32
4933 // preprocessed-entity-id:i32
4934 // macro-definition-id:i32
4935 // submodule-id:i32
4936 // selector-id:i32
4937 // declaration-id:i32
4938 // c++-base-specifiers-id:i32
4939 // type-id:i32)
4941 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4942 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4943 // module name. Otherwise, it is the module file name.
4944 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4945 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4946 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4947 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4948 SmallString<2048> Buffer;
4950 llvm::raw_svector_ostream Out(Buffer);
4951 for (ModuleFile &M : Chain->ModuleMgr) {
4952 using namespace llvm::support;
4954 endian::Writer LE(Out, little);
4955 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4956 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
4957 LE.write<uint16_t>(Name.size());
4958 Out.write(Name.data(), Name.size());
4960 // Note: if a base ID was uint max, it would not be possible to load
4961 // another module after it or have more than one entity inside it.
4962 uint32_t None = std::numeric_limits<uint32_t>::max();
4964 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
4965 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4966 if (ShouldWrite)
4967 LE.write<uint32_t>(BaseID);
4968 else
4969 LE.write<uint32_t>(None);
4972 // These values should be unique within a chain, since they will be read
4973 // as keys into ContinuousRangeMaps.
4974 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4975 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4976 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4977 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4978 M.NumPreprocessedEntities);
4979 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4980 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4981 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4982 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4985 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4986 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4987 Buffer.data(), Buffer.size());
4990 // Build a record containing all of the DeclsToCheckForDeferredDiags.
4991 SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
4992 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4993 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
4995 RecordData DeclUpdatesOffsetsRecord;
4997 // Keep writing types, declarations, and declaration update records
4998 // until we've emitted all of them.
4999 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5000 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
5001 WriteTypeAbbrevs();
5002 WriteDeclAbbrevs();
5003 do {
5004 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5005 while (!DeclTypesToEmit.empty()) {
5006 DeclOrType DOT = DeclTypesToEmit.front();
5007 DeclTypesToEmit.pop();
5008 if (DOT.isType())
5009 WriteType(DOT.getType());
5010 else
5011 WriteDecl(Context, DOT.getDecl());
5013 } while (!DeclUpdates.empty());
5014 Stream.ExitBlock();
5016 DoneWritingDeclsAndTypes = true;
5018 // These things can only be done once we've written out decls and types.
5019 WriteTypeDeclOffsets();
5020 if (!DeclUpdatesOffsetsRecord.empty())
5021 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5022 WriteFileDeclIDsMap();
5023 WriteSourceManagerBlock(Context.getSourceManager(), PP);
5024 WriteComments();
5025 WritePreprocessor(PP, isModule);
5026 WriteHeaderSearch(PP.getHeaderSearchInfo());
5027 WriteSelectors(SemaRef);
5028 WriteReferencedSelectorsPool(SemaRef);
5029 WriteLateParsedTemplates(SemaRef);
5030 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5031 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
5032 WriteOpenCLExtensions(SemaRef);
5033 WriteCUDAPragmas(SemaRef);
5035 // If we're emitting a module, write out the submodule information.
5036 if (WritingModule)
5037 WriteSubmodules(WritingModule);
5039 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5041 // Write the record containing external, unnamed definitions.
5042 if (!EagerlyDeserializedDecls.empty())
5043 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5045 if (!ModularCodegenDecls.empty())
5046 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5048 // Write the record containing tentative definitions.
5049 if (!TentativeDefinitions.empty())
5050 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5052 // Write the record containing unused file scoped decls.
5053 if (!UnusedFileScopedDecls.empty())
5054 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5056 // Write the record containing weak undeclared identifiers.
5057 if (!WeakUndeclaredIdentifiers.empty())
5058 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5059 WeakUndeclaredIdentifiers);
5061 // Write the record containing ext_vector type names.
5062 if (!ExtVectorDecls.empty())
5063 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5065 // Write the record containing VTable uses information.
5066 if (!VTableUses.empty())
5067 Stream.EmitRecord(VTABLE_USES, VTableUses);
5069 // Write the record containing potentially unused local typedefs.
5070 if (!UnusedLocalTypedefNameCandidates.empty())
5071 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5072 UnusedLocalTypedefNameCandidates);
5074 // Write the record containing pending implicit instantiations.
5075 if (!PendingInstantiations.empty())
5076 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5078 // Write the record containing declaration references of Sema.
5079 if (!SemaDeclRefs.empty())
5080 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5082 // Write the record containing decls to be checked for deferred diags.
5083 if (!DeclsToCheckForDeferredDiags.empty())
5084 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
5085 DeclsToCheckForDeferredDiags);
5087 // Write the record containing CUDA-specific declaration references.
5088 if (!CUDASpecialDeclRefs.empty())
5089 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5091 // Write the delegating constructors.
5092 if (!DelegatingCtorDecls.empty())
5093 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5095 // Write the known namespaces.
5096 if (!KnownNamespaces.empty())
5097 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5099 // Write the undefined internal functions and variables, and inline functions.
5100 if (!UndefinedButUsed.empty())
5101 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5103 if (!DeleteExprsToAnalyze.empty())
5104 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5106 // Write the visible updates to DeclContexts.
5107 for (auto *DC : UpdatedDeclContexts)
5108 WriteDeclContextVisibleUpdate(DC);
5110 if (!WritingModule) {
5111 // Write the submodules that were imported, if any.
5112 struct ModuleInfo {
5113 uint64_t ID;
5114 Module *M;
5115 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5117 llvm::SmallVector<ModuleInfo, 64> Imports;
5118 for (const auto *I : Context.local_imports()) {
5119 assert(SubmoduleIDs.contains(I->getImportedModule()));
5120 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5121 I->getImportedModule()));
5124 if (!Imports.empty()) {
5125 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5126 return A.ID < B.ID;
5128 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5129 return A.ID == B.ID;
5132 // Sort and deduplicate module IDs.
5133 llvm::sort(Imports, Cmp);
5134 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5135 Imports.end());
5137 RecordData ImportedModules;
5138 for (const auto &Import : Imports) {
5139 ImportedModules.push_back(Import.ID);
5140 // FIXME: If the module has macros imported then later has declarations
5141 // imported, this location won't be the right one as a location for the
5142 // declaration imports.
5143 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5146 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5150 WriteObjCCategories();
5151 if(!WritingModule) {
5152 WriteOptimizePragmaOptions(SemaRef);
5153 WriteMSStructPragmaOptions(SemaRef);
5154 WriteMSPointersToMembersPragmaOptions(SemaRef);
5156 WritePackPragmaOptions(SemaRef);
5157 WriteFloatControlPragmaOptions(SemaRef);
5159 // Some simple statistics
5160 RecordData::value_type Record[] = {
5161 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5162 Stream.EmitRecord(STATISTICS, Record);
5163 Stream.ExitBlock();
5164 Stream.FlushToWord();
5165 ASTBlockRange.second = Stream.GetCurrentBitNo();
5167 // Write the module file extension blocks.
5168 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5169 WriteModuleFileExtension(SemaRef, *ExtWriter);
5171 return writeUnhashedControlBlock(PP, Context);
5174 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5175 if (DeclUpdates.empty())
5176 return;
5178 DeclUpdateMap LocalUpdates;
5179 LocalUpdates.swap(DeclUpdates);
5181 for (auto &DeclUpdate : LocalUpdates) {
5182 const Decl *D = DeclUpdate.first;
5184 bool HasUpdatedBody = false;
5185 bool HasAddedVarDefinition = false;
5186 RecordData RecordData;
5187 ASTRecordWriter Record(*this, RecordData);
5188 for (auto &Update : DeclUpdate.second) {
5189 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5191 // An updated body is emitted last, so that the reader doesn't need
5192 // to skip over the lazy body to reach statements for other records.
5193 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5194 HasUpdatedBody = true;
5195 else if (Kind == UPD_CXX_ADDED_VAR_DEFINITION)
5196 HasAddedVarDefinition = true;
5197 else
5198 Record.push_back(Kind);
5200 switch (Kind) {
5201 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5202 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5203 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5204 assert(Update.getDecl() && "no decl to add?");
5205 Record.push_back(GetDeclRef(Update.getDecl()));
5206 break;
5208 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5209 case UPD_CXX_ADDED_VAR_DEFINITION:
5210 break;
5212 case UPD_CXX_POINT_OF_INSTANTIATION:
5213 // FIXME: Do we need to also save the template specialization kind here?
5214 Record.AddSourceLocation(Update.getLoc());
5215 break;
5217 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5218 Record.AddStmt(const_cast<Expr *>(
5219 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5220 break;
5222 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5223 Record.AddStmt(
5224 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5225 break;
5227 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5228 auto *RD = cast<CXXRecordDecl>(D);
5229 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5230 Record.push_back(RD->isParamDestroyedInCallee());
5231 Record.push_back(RD->getArgPassingRestrictions());
5232 Record.AddCXXDefinitionData(RD);
5233 Record.AddOffset(WriteDeclContextLexicalBlock(
5234 *Context, const_cast<CXXRecordDecl *>(RD)));
5236 // This state is sometimes updated by template instantiation, when we
5237 // switch from the specialization referring to the template declaration
5238 // to it referring to the template definition.
5239 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5240 Record.push_back(MSInfo->getTemplateSpecializationKind());
5241 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5242 } else {
5243 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5244 Record.push_back(Spec->getTemplateSpecializationKind());
5245 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5247 // The instantiation might have been resolved to a partial
5248 // specialization. If so, record which one.
5249 auto From = Spec->getInstantiatedFrom();
5250 if (auto PartialSpec =
5251 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5252 Record.push_back(true);
5253 Record.AddDeclRef(PartialSpec);
5254 Record.AddTemplateArgumentList(
5255 &Spec->getTemplateInstantiationArgs());
5256 } else {
5257 Record.push_back(false);
5260 Record.push_back(RD->getTagKind());
5261 Record.AddSourceLocation(RD->getLocation());
5262 Record.AddSourceLocation(RD->getBeginLoc());
5263 Record.AddSourceRange(RD->getBraceRange());
5265 // Instantiation may change attributes; write them all out afresh.
5266 Record.push_back(D->hasAttrs());
5267 if (D->hasAttrs())
5268 Record.AddAttributes(D->getAttrs());
5270 // FIXME: Ensure we don't get here for explicit instantiations.
5271 break;
5274 case UPD_CXX_RESOLVED_DTOR_DELETE:
5275 Record.AddDeclRef(Update.getDecl());
5276 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5277 break;
5279 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5280 auto prototype =
5281 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5282 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5283 break;
5286 case UPD_CXX_DEDUCED_RETURN_TYPE:
5287 Record.push_back(GetOrCreateTypeID(Update.getType()));
5288 break;
5290 case UPD_DECL_MARKED_USED:
5291 break;
5293 case UPD_MANGLING_NUMBER:
5294 case UPD_STATIC_LOCAL_NUMBER:
5295 Record.push_back(Update.getNumber());
5296 break;
5298 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5299 Record.AddSourceRange(
5300 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5301 break;
5303 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5304 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5305 Record.push_back(A->getAllocatorType());
5306 Record.AddStmt(A->getAllocator());
5307 Record.AddStmt(A->getAlignment());
5308 Record.AddSourceRange(A->getRange());
5309 break;
5312 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5313 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5314 Record.AddSourceRange(
5315 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5316 break;
5318 case UPD_DECL_EXPORTED:
5319 Record.push_back(getSubmoduleID(Update.getModule()));
5320 break;
5322 case UPD_ADDED_ATTR_TO_RECORD:
5323 Record.AddAttributes(llvm::ArrayRef(Update.getAttr()));
5324 break;
5328 // Add a trailing update record, if any. These must go last because we
5329 // lazily load their attached statement.
5330 if (HasUpdatedBody) {
5331 const auto *Def = cast<FunctionDecl>(D);
5332 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5333 Record.push_back(Def->isInlined());
5334 Record.AddSourceLocation(Def->getInnerLocStart());
5335 Record.AddFunctionDefinition(Def);
5336 } else if (HasAddedVarDefinition) {
5337 const auto *VD = cast<VarDecl>(D);
5338 Record.push_back(UPD_CXX_ADDED_VAR_DEFINITION);
5339 Record.push_back(VD->isInline());
5340 Record.push_back(VD->isInlineSpecified());
5341 Record.AddVarDeclInit(VD);
5344 OffsetsRecord.push_back(GetDeclRef(D));
5345 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5349 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
5350 RecordDataImpl &Record) {
5351 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5352 Record.push_back(Raw);
5355 FileID ASTWriter::getAdjustedFileID(FileID FID) const {
5356 if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
5357 NonAffectingFileIDs.empty())
5358 return FID;
5359 auto It = llvm::lower_bound(NonAffectingFileIDs, FID);
5360 unsigned Idx = std::distance(NonAffectingFileIDs.begin(), It);
5361 unsigned Offset = NonAffectingFileIDAdjustments[Idx];
5362 return FileID::get(FID.getOpaqueValue() - Offset);
5365 unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
5366 unsigned NumCreatedFIDs = PP->getSourceManager()
5367 .getLocalSLocEntry(FID.ID)
5368 .getFile()
5369 .NumCreatedFIDs;
5371 unsigned AdjustedNumCreatedFIDs = 0;
5372 for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
5373 if (IsSLocAffecting[I])
5374 ++AdjustedNumCreatedFIDs;
5375 return AdjustedNumCreatedFIDs;
5378 SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
5379 if (Loc.isInvalid())
5380 return Loc;
5381 return Loc.getLocWithOffset(-getAdjustment(Loc.getOffset()));
5384 SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
5385 return SourceRange(getAdjustedLocation(Range.getBegin()),
5386 getAdjustedLocation(Range.getEnd()));
5389 SourceLocation::UIntTy
5390 ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
5391 return Offset - getAdjustment(Offset);
5394 SourceLocation::UIntTy
5395 ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
5396 if (NonAffectingRanges.empty())
5397 return 0;
5399 if (PP->getSourceManager().isLoadedOffset(Offset))
5400 return 0;
5402 if (Offset > NonAffectingRanges.back().getEnd().getOffset())
5403 return NonAffectingOffsetAdjustments.back();
5405 if (Offset < NonAffectingRanges.front().getBegin().getOffset())
5406 return 0;
5408 auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
5409 return Range.getEnd().getOffset() < Offset;
5412 auto It = llvm::lower_bound(NonAffectingRanges, Offset, Contains);
5413 unsigned Idx = std::distance(NonAffectingRanges.begin(), It);
5414 return NonAffectingOffsetAdjustments[Idx];
5417 void ASTWriter::AddFileID(FileID FID, RecordDataImpl &Record) {
5418 Record.push_back(getAdjustedFileID(FID).getOpaqueValue());
5421 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record,
5422 SourceLocationSequence *Seq) {
5423 Loc = getAdjustedLocation(Loc);
5424 Record.push_back(SourceLocationEncoding::encode(Loc, Seq));
5427 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record,
5428 SourceLocationSequence *Seq) {
5429 AddSourceLocation(Range.getBegin(), Record, Seq);
5430 AddSourceLocation(Range.getEnd(), Record, Seq);
5433 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5434 AddAPInt(Value.bitcastToAPInt());
5437 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5438 Record.push_back(getIdentifierRef(II));
5441 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5442 if (!II)
5443 return 0;
5445 IdentID &ID = IdentifierIDs[II];
5446 if (ID == 0)
5447 ID = NextIdentID++;
5448 return ID;
5451 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5452 // Don't emit builtin macros like __LINE__ to the AST file unless they
5453 // have been redefined by the header (in which case they are not
5454 // isBuiltinMacro).
5455 if (!MI || MI->isBuiltinMacro())
5456 return 0;
5458 MacroID &ID = MacroIDs[MI];
5459 if (ID == 0) {
5460 ID = NextMacroID++;
5461 MacroInfoToEmitData Info = { Name, MI, ID };
5462 MacroInfosToEmit.push_back(Info);
5464 return ID;
5467 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5468 if (!MI || MI->isBuiltinMacro())
5469 return 0;
5471 assert(MacroIDs.contains(MI) && "Macro not emitted!");
5472 return MacroIDs[MI];
5475 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5476 return IdentMacroDirectivesOffsetMap.lookup(Name);
5479 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5480 Record->push_back(Writer->getSelectorRef(SelRef));
5483 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5484 if (Sel.getAsOpaquePtr() == nullptr) {
5485 return 0;
5488 SelectorID SID = SelectorIDs[Sel];
5489 if (SID == 0 && Chain) {
5490 // This might trigger a ReadSelector callback, which will set the ID for
5491 // this selector.
5492 Chain->LoadSelector(Sel);
5493 SID = SelectorIDs[Sel];
5495 if (SID == 0) {
5496 SID = NextSelectorID++;
5497 SelectorIDs[Sel] = SID;
5499 return SID;
5502 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5503 AddDeclRef(Temp->getDestructor());
5506 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5507 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5508 switch (Kind) {
5509 case TemplateArgument::Expression:
5510 AddStmt(Arg.getAsExpr());
5511 break;
5512 case TemplateArgument::Type:
5513 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5514 break;
5515 case TemplateArgument::Template:
5516 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5517 AddSourceLocation(Arg.getTemplateNameLoc());
5518 break;
5519 case TemplateArgument::TemplateExpansion:
5520 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5521 AddSourceLocation(Arg.getTemplateNameLoc());
5522 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5523 break;
5524 case TemplateArgument::Null:
5525 case TemplateArgument::Integral:
5526 case TemplateArgument::Declaration:
5527 case TemplateArgument::NullPtr:
5528 case TemplateArgument::Pack:
5529 // FIXME: Is this right?
5530 break;
5534 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5535 AddTemplateArgument(Arg.getArgument());
5537 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5538 bool InfoHasSameExpr
5539 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5540 Record->push_back(InfoHasSameExpr);
5541 if (InfoHasSameExpr)
5542 return; // Avoid storing the same expr twice.
5544 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5547 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5548 if (!TInfo) {
5549 AddTypeRef(QualType());
5550 return;
5553 AddTypeRef(TInfo->getType());
5554 AddTypeLoc(TInfo->getTypeLoc());
5557 void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) {
5558 LocSeq::State Seq(OuterSeq);
5559 TypeLocWriter TLW(*this, Seq);
5560 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5561 TLW.Visit(TL);
5564 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5565 Record.push_back(GetOrCreateTypeID(T));
5568 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5569 assert(Context);
5570 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5571 if (T.isNull())
5572 return TypeIdx();
5573 assert(!T.getLocalFastQualifiers());
5575 TypeIdx &Idx = TypeIdxs[T];
5576 if (Idx.getIndex() == 0) {
5577 if (DoneWritingDeclsAndTypes) {
5578 assert(0 && "New type seen after serializing all the types to emit!");
5579 return TypeIdx();
5582 // We haven't seen this type before. Assign it a new ID and put it
5583 // into the queue of types to emit.
5584 Idx = TypeIdx(NextTypeID++);
5585 DeclTypesToEmit.push(T);
5587 return Idx;
5591 TypeID ASTWriter::getTypeID(QualType T) const {
5592 assert(Context);
5593 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5594 if (T.isNull())
5595 return TypeIdx();
5596 assert(!T.getLocalFastQualifiers());
5598 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5599 assert(I != TypeIdxs.end() && "Type not emitted!");
5600 return I->second;
5604 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5605 Record.push_back(GetDeclRef(D));
5608 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5609 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5611 if (!D) {
5612 return 0;
5615 // If D comes from an AST file, its declaration ID is already known and
5616 // fixed.
5617 if (D->isFromASTFile())
5618 return D->getGlobalID();
5620 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5621 DeclID &ID = DeclIDs[D];
5622 if (ID == 0) {
5623 if (DoneWritingDeclsAndTypes) {
5624 assert(0 && "New decl seen after serializing all the decls to emit!");
5625 return 0;
5628 // We haven't seen this declaration before. Give it a new ID and
5629 // enqueue it in the list of declarations to emit.
5630 ID = NextDeclID++;
5631 DeclTypesToEmit.push(const_cast<Decl *>(D));
5634 return ID;
5637 DeclID ASTWriter::getDeclID(const Decl *D) {
5638 if (!D)
5639 return 0;
5641 // If D comes from an AST file, its declaration ID is already known and
5642 // fixed.
5643 if (D->isFromASTFile())
5644 return D->getGlobalID();
5646 assert(DeclIDs.contains(D) && "Declaration not emitted!");
5647 return DeclIDs[D];
5650 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5651 assert(ID);
5652 assert(D);
5654 SourceLocation Loc = D->getLocation();
5655 if (Loc.isInvalid())
5656 return;
5658 // We only keep track of the file-level declarations of each file.
5659 if (!D->getLexicalDeclContext()->isFileContext())
5660 return;
5661 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5662 // a function/objc method, should not have TU as lexical context.
5663 // TemplateTemplateParmDecls that are part of an alias template, should not
5664 // have TU as lexical context.
5665 if (isa<ParmVarDecl, TemplateTemplateParmDecl>(D))
5666 return;
5668 SourceManager &SM = Context->getSourceManager();
5669 SourceLocation FileLoc = SM.getFileLoc(Loc);
5670 assert(SM.isLocalSourceLocation(FileLoc));
5671 FileID FID;
5672 unsigned Offset;
5673 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5674 if (FID.isInvalid())
5675 return;
5676 assert(SM.getSLocEntry(FID).isFile());
5677 assert(IsSLocAffecting[FID.ID]);
5679 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5680 if (!Info)
5681 Info = std::make_unique<DeclIDInFileInfo>();
5683 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5684 LocDeclIDsTy &Decls = Info->DeclIDs;
5685 Decls.push_back(LocDecl);
5688 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5689 assert(needsAnonymousDeclarationNumber(D) &&
5690 "expected an anonymous declaration");
5692 // Number the anonymous declarations within this context, if we've not
5693 // already done so.
5694 auto It = AnonymousDeclarationNumbers.find(D);
5695 if (It == AnonymousDeclarationNumbers.end()) {
5696 auto *DC = D->getLexicalDeclContext();
5697 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5698 AnonymousDeclarationNumbers[ND] = Number;
5701 It = AnonymousDeclarationNumbers.find(D);
5702 assert(It != AnonymousDeclarationNumbers.end() &&
5703 "declaration not found within its lexical context");
5706 return It->second;
5709 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5710 DeclarationName Name) {
5711 switch (Name.getNameKind()) {
5712 case DeclarationName::CXXConstructorName:
5713 case DeclarationName::CXXDestructorName:
5714 case DeclarationName::CXXConversionFunctionName:
5715 AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
5716 break;
5718 case DeclarationName::CXXOperatorName:
5719 AddSourceRange(DNLoc.getCXXOperatorNameRange());
5720 break;
5722 case DeclarationName::CXXLiteralOperatorName:
5723 AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
5724 break;
5726 case DeclarationName::Identifier:
5727 case DeclarationName::ObjCZeroArgSelector:
5728 case DeclarationName::ObjCOneArgSelector:
5729 case DeclarationName::ObjCMultiArgSelector:
5730 case DeclarationName::CXXUsingDirective:
5731 case DeclarationName::CXXDeductionGuideName:
5732 break;
5736 void ASTRecordWriter::AddDeclarationNameInfo(
5737 const DeclarationNameInfo &NameInfo) {
5738 AddDeclarationName(NameInfo.getName());
5739 AddSourceLocation(NameInfo.getLoc());
5740 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5743 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5744 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5745 Record->push_back(Info.NumTemplParamLists);
5746 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5747 AddTemplateParameterList(Info.TemplParamLists[i]);
5750 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5751 // Nested name specifiers usually aren't too long. I think that 8 would
5752 // typically accommodate the vast majority.
5753 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5755 // Push each of the nested-name-specifiers's onto a stack for
5756 // serialization in reverse order.
5757 while (NNS) {
5758 NestedNames.push_back(NNS);
5759 NNS = NNS.getPrefix();
5762 Record->push_back(NestedNames.size());
5763 while(!NestedNames.empty()) {
5764 NNS = NestedNames.pop_back_val();
5765 NestedNameSpecifier::SpecifierKind Kind
5766 = NNS.getNestedNameSpecifier()->getKind();
5767 Record->push_back(Kind);
5768 switch (Kind) {
5769 case NestedNameSpecifier::Identifier:
5770 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5771 AddSourceRange(NNS.getLocalSourceRange());
5772 break;
5774 case NestedNameSpecifier::Namespace:
5775 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5776 AddSourceRange(NNS.getLocalSourceRange());
5777 break;
5779 case NestedNameSpecifier::NamespaceAlias:
5780 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5781 AddSourceRange(NNS.getLocalSourceRange());
5782 break;
5784 case NestedNameSpecifier::TypeSpec:
5785 case NestedNameSpecifier::TypeSpecWithTemplate:
5786 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5787 AddTypeRef(NNS.getTypeLoc().getType());
5788 AddTypeLoc(NNS.getTypeLoc());
5789 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5790 break;
5792 case NestedNameSpecifier::Global:
5793 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5794 break;
5796 case NestedNameSpecifier::Super:
5797 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5798 AddSourceRange(NNS.getLocalSourceRange());
5799 break;
5804 void ASTRecordWriter::AddTemplateParameterList(
5805 const TemplateParameterList *TemplateParams) {
5806 assert(TemplateParams && "No TemplateParams!");
5807 AddSourceLocation(TemplateParams->getTemplateLoc());
5808 AddSourceLocation(TemplateParams->getLAngleLoc());
5809 AddSourceLocation(TemplateParams->getRAngleLoc());
5811 Record->push_back(TemplateParams->size());
5812 for (const auto &P : *TemplateParams)
5813 AddDeclRef(P);
5814 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5815 Record->push_back(true);
5816 AddStmt(const_cast<Expr*>(RequiresClause));
5817 } else {
5818 Record->push_back(false);
5822 /// Emit a template argument list.
5823 void ASTRecordWriter::AddTemplateArgumentList(
5824 const TemplateArgumentList *TemplateArgs) {
5825 assert(TemplateArgs && "No TemplateArgs!");
5826 Record->push_back(TemplateArgs->size());
5827 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5828 AddTemplateArgument(TemplateArgs->get(i));
5831 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5832 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5833 assert(ASTTemplArgList && "No ASTTemplArgList!");
5834 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5835 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5836 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5837 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5838 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5839 AddTemplateArgumentLoc(TemplArgs[i]);
5842 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5843 Record->push_back(Set.size());
5844 for (ASTUnresolvedSet::const_iterator
5845 I = Set.begin(), E = Set.end(); I != E; ++I) {
5846 AddDeclRef(I.getDecl());
5847 Record->push_back(I.getAccess());
5851 // FIXME: Move this out of the main ASTRecordWriter interface.
5852 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5853 Record->push_back(Base.isVirtual());
5854 Record->push_back(Base.isBaseOfClass());
5855 Record->push_back(Base.getAccessSpecifierAsWritten());
5856 Record->push_back(Base.getInheritConstructors());
5857 AddTypeSourceInfo(Base.getTypeSourceInfo());
5858 AddSourceRange(Base.getSourceRange());
5859 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5860 : SourceLocation());
5863 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5864 ArrayRef<CXXBaseSpecifier> Bases) {
5865 ASTWriter::RecordData Record;
5866 ASTRecordWriter Writer(W, Record);
5867 Writer.push_back(Bases.size());
5869 for (auto &Base : Bases)
5870 Writer.AddCXXBaseSpecifier(Base);
5872 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5875 // FIXME: Move this out of the main ASTRecordWriter interface.
5876 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5877 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5880 static uint64_t
5881 EmitCXXCtorInitializers(ASTWriter &W,
5882 ArrayRef<CXXCtorInitializer *> CtorInits) {
5883 ASTWriter::RecordData Record;
5884 ASTRecordWriter Writer(W, Record);
5885 Writer.push_back(CtorInits.size());
5887 for (auto *Init : CtorInits) {
5888 if (Init->isBaseInitializer()) {
5889 Writer.push_back(CTOR_INITIALIZER_BASE);
5890 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5891 Writer.push_back(Init->isBaseVirtual());
5892 } else if (Init->isDelegatingInitializer()) {
5893 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5894 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5895 } else if (Init->isMemberInitializer()){
5896 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5897 Writer.AddDeclRef(Init->getMember());
5898 } else {
5899 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5900 Writer.AddDeclRef(Init->getIndirectMember());
5903 Writer.AddSourceLocation(Init->getMemberLocation());
5904 Writer.AddStmt(Init->getInit());
5905 Writer.AddSourceLocation(Init->getLParenLoc());
5906 Writer.AddSourceLocation(Init->getRParenLoc());
5907 Writer.push_back(Init->isWritten());
5908 if (Init->isWritten())
5909 Writer.push_back(Init->getSourceOrder());
5912 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5915 // FIXME: Move this out of the main ASTRecordWriter interface.
5916 void ASTRecordWriter::AddCXXCtorInitializers(
5917 ArrayRef<CXXCtorInitializer *> CtorInits) {
5918 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5921 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5922 auto &Data = D->data();
5923 Record->push_back(Data.IsLambda);
5925 #define FIELD(Name, Width, Merge) \
5926 Record->push_back(Data.Name);
5927 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
5929 // getODRHash will compute the ODRHash if it has not been previously computed.
5930 Record->push_back(D->getODRHash());
5932 bool ModulesDebugInfo =
5933 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
5934 Record->push_back(ModulesDebugInfo);
5935 if (ModulesDebugInfo)
5936 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5938 // IsLambda bit is already saved.
5940 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5941 Record->push_back(Data.ComputedVisibleConversions);
5942 if (Data.ComputedVisibleConversions)
5943 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5944 // Data.Definition is the owning decl, no need to write it.
5946 if (!Data.IsLambda) {
5947 Record->push_back(Data.NumBases);
5948 if (Data.NumBases > 0)
5949 AddCXXBaseSpecifiers(Data.bases());
5951 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5952 Record->push_back(Data.NumVBases);
5953 if (Data.NumVBases > 0)
5954 AddCXXBaseSpecifiers(Data.vbases());
5956 AddDeclRef(D->getFirstFriend());
5957 } else {
5958 auto &Lambda = D->getLambdaData();
5959 Record->push_back(Lambda.DependencyKind);
5960 Record->push_back(Lambda.IsGenericLambda);
5961 Record->push_back(Lambda.CaptureDefault);
5962 Record->push_back(Lambda.NumCaptures);
5963 Record->push_back(Lambda.NumExplicitCaptures);
5964 Record->push_back(Lambda.HasKnownInternalLinkage);
5965 Record->push_back(Lambda.ManglingNumber);
5966 Record->push_back(D->getDeviceLambdaManglingNumber());
5967 // The lambda context declaration and index within the context are provided
5968 // separately, so that they can be used for merging.
5969 AddTypeSourceInfo(Lambda.MethodTyInfo);
5970 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5971 const LambdaCapture &Capture = Lambda.Captures.front()[I];
5972 AddSourceLocation(Capture.getLocation());
5973 Record->push_back(Capture.isImplicit());
5974 Record->push_back(Capture.getCaptureKind());
5975 switch (Capture.getCaptureKind()) {
5976 case LCK_StarThis:
5977 case LCK_This:
5978 case LCK_VLAType:
5979 break;
5980 case LCK_ByCopy:
5981 case LCK_ByRef:
5982 ValueDecl *Var =
5983 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5984 AddDeclRef(Var);
5985 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5986 : SourceLocation());
5987 break;
5993 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
5994 const Expr *Init = VD->getInit();
5995 if (!Init) {
5996 push_back(0);
5997 return;
6000 uint64_t Val = 1;
6001 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
6002 Val |= (ES->HasConstantInitialization ? 2 : 0);
6003 Val |= (ES->HasConstantDestruction ? 4 : 0);
6004 APValue *Evaluated = VD->getEvaluatedValue();
6005 // If the evaluted result is constant, emit it.
6006 if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
6007 Val |= 8;
6009 push_back(Val);
6010 if (Val & 8) {
6011 AddAPValue(*VD->getEvaluatedValue());
6014 writeStmtRef(Init);
6017 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6018 assert(Reader && "Cannot remove chain");
6019 assert((!Chain || Chain == Reader) && "Cannot replace chain");
6020 assert(FirstDeclID == NextDeclID &&
6021 FirstTypeID == NextTypeID &&
6022 FirstIdentID == NextIdentID &&
6023 FirstMacroID == NextMacroID &&
6024 FirstSubmoduleID == NextSubmoduleID &&
6025 FirstSelectorID == NextSelectorID &&
6026 "Setting chain after writing has started.");
6028 Chain = Reader;
6030 // Note, this will get called multiple times, once one the reader starts up
6031 // and again each time it's done reading a PCH or module.
6032 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6033 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6034 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6035 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6036 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6037 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6038 NextDeclID = FirstDeclID;
6039 NextTypeID = FirstTypeID;
6040 NextIdentID = FirstIdentID;
6041 NextMacroID = FirstMacroID;
6042 NextSelectorID = FirstSelectorID;
6043 NextSubmoduleID = FirstSubmoduleID;
6046 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6047 // Always keep the highest ID. See \p TypeRead() for more information.
6048 IdentID &StoredID = IdentifierIDs[II];
6049 if (ID > StoredID)
6050 StoredID = ID;
6053 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6054 // Always keep the highest ID. See \p TypeRead() for more information.
6055 MacroID &StoredID = MacroIDs[MI];
6056 if (ID > StoredID)
6057 StoredID = ID;
6060 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6061 // Always take the highest-numbered type index. This copes with an interesting
6062 // case for chained AST writing where we schedule writing the type and then,
6063 // later, deserialize the type from another AST. In this case, we want to
6064 // keep the higher-numbered entry so that we can properly write it out to
6065 // the AST file.
6066 TypeIdx &StoredIdx = TypeIdxs[T];
6067 if (Idx.getIndex() >= StoredIdx.getIndex())
6068 StoredIdx = Idx;
6071 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6072 // Always keep the highest ID. See \p TypeRead() for more information.
6073 SelectorID &StoredID = SelectorIDs[S];
6074 if (ID > StoredID)
6075 StoredID = ID;
6078 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6079 MacroDefinitionRecord *MD) {
6080 assert(!MacroDefinitions.contains(MD));
6081 MacroDefinitions[MD] = ID;
6084 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6085 assert(!SubmoduleIDs.contains(Mod));
6086 SubmoduleIDs[Mod] = ID;
6089 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6090 if (Chain && Chain->isProcessingUpdateRecords()) return;
6091 assert(D->isCompleteDefinition());
6092 assert(!WritingAST && "Already writing the AST!");
6093 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6094 // We are interested when a PCH decl is modified.
6095 if (RD->isFromASTFile()) {
6096 // A forward reference was mutated into a definition. Rewrite it.
6097 // FIXME: This happens during template instantiation, should we
6098 // have created a new definition decl instead ?
6099 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6100 "completed a tag from another module but not by instantiation?");
6101 DeclUpdates[RD].push_back(
6102 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
6107 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6108 if (D->isFromASTFile())
6109 return true;
6111 // The predefined __va_list_tag struct is imported if we imported any decls.
6112 // FIXME: This is a gross hack.
6113 return D == D->getASTContext().getVaListTagDecl();
6116 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6117 if (Chain && Chain->isProcessingUpdateRecords()) return;
6118 assert(DC->isLookupContext() &&
6119 "Should not add lookup results to non-lookup contexts!");
6121 // TU is handled elsewhere.
6122 if (isa<TranslationUnitDecl>(DC))
6123 return;
6125 // Namespaces are handled elsewhere, except for template instantiations of
6126 // FunctionTemplateDecls in namespaces. We are interested in cases where the
6127 // local instantiations are added to an imported context. Only happens when
6128 // adding ADL lookup candidates, for example templated friends.
6129 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6130 !isa<FunctionTemplateDecl>(D))
6131 return;
6133 // We're only interested in cases where a local declaration is added to an
6134 // imported context.
6135 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6136 return;
6138 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6139 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6140 assert(!WritingAST && "Already writing the AST!");
6141 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6142 // We're adding a visible declaration to a predefined decl context. Ensure
6143 // that we write out all of its lookup results so we don't get a nasty
6144 // surprise when we try to emit its lookup table.
6145 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
6147 DeclsToEmitEvenIfUnreferenced.push_back(D);
6150 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6151 if (Chain && Chain->isProcessingUpdateRecords()) return;
6152 assert(D->isImplicit());
6154 // We're only interested in cases where a local declaration is added to an
6155 // imported context.
6156 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6157 return;
6159 if (!isa<CXXMethodDecl>(D))
6160 return;
6162 // A decl coming from PCH was modified.
6163 assert(RD->isCompleteDefinition());
6164 assert(!WritingAST && "Already writing the AST!");
6165 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6168 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6169 if (Chain && Chain->isProcessingUpdateRecords()) return;
6170 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6171 if (!Chain) return;
6172 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6173 // If we don't already know the exception specification for this redecl
6174 // chain, add an update record for it.
6175 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6176 ->getType()
6177 ->castAs<FunctionProtoType>()
6178 ->getExceptionSpecType()))
6179 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6183 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6184 if (Chain && Chain->isProcessingUpdateRecords()) return;
6185 assert(!WritingAST && "Already writing the AST!");
6186 if (!Chain) return;
6187 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6188 DeclUpdates[D].push_back(
6189 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6193 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6194 const FunctionDecl *Delete,
6195 Expr *ThisArg) {
6196 if (Chain && Chain->isProcessingUpdateRecords()) return;
6197 assert(!WritingAST && "Already writing the AST!");
6198 assert(Delete && "Not given an operator delete");
6199 if (!Chain) return;
6200 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6201 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6205 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6206 if (Chain && Chain->isProcessingUpdateRecords()) return;
6207 assert(!WritingAST && "Already writing the AST!");
6208 if (!D->isFromASTFile())
6209 return; // Declaration not imported from PCH.
6211 // Implicit function decl from a PCH was defined.
6212 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6215 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6216 if (Chain && Chain->isProcessingUpdateRecords()) return;
6217 assert(!WritingAST && "Already writing the AST!");
6218 if (!D->isFromASTFile())
6219 return;
6221 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6224 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6225 if (Chain && Chain->isProcessingUpdateRecords()) return;
6226 assert(!WritingAST && "Already writing the AST!");
6227 if (!D->isFromASTFile())
6228 return;
6230 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6233 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6234 if (Chain && Chain->isProcessingUpdateRecords()) return;
6235 assert(!WritingAST && "Already writing the AST!");
6236 if (!D->isFromASTFile())
6237 return;
6239 // Since the actual instantiation is delayed, this really means that we need
6240 // to update the instantiation location.
6241 SourceLocation POI;
6242 if (auto *VD = dyn_cast<VarDecl>(D))
6243 POI = VD->getPointOfInstantiation();
6244 else
6245 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6246 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6249 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6250 if (Chain && Chain->isProcessingUpdateRecords()) return;
6251 assert(!WritingAST && "Already writing the AST!");
6252 if (!D->isFromASTFile())
6253 return;
6255 DeclUpdates[D].push_back(
6256 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6259 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6260 assert(!WritingAST && "Already writing the AST!");
6261 if (!D->isFromASTFile())
6262 return;
6264 DeclUpdates[D].push_back(
6265 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6268 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6269 const ObjCInterfaceDecl *IFD) {
6270 if (Chain && Chain->isProcessingUpdateRecords()) return;
6271 assert(!WritingAST && "Already writing the AST!");
6272 if (!IFD->isFromASTFile())
6273 return; // Declaration not imported from PCH.
6275 assert(IFD->getDefinition() && "Category on a class without a definition?");
6276 ObjCClassesWithCategories.insert(
6277 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6280 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6281 if (Chain && Chain->isProcessingUpdateRecords()) return;
6282 assert(!WritingAST && "Already writing the AST!");
6284 // If there is *any* declaration of the entity that's not from an AST file,
6285 // we can skip writing the update record. We make sure that isUsed() triggers
6286 // completion of the redeclaration chain of the entity.
6287 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6288 if (IsLocalDecl(Prev))
6289 return;
6291 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6294 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6295 if (Chain && Chain->isProcessingUpdateRecords()) return;
6296 assert(!WritingAST && "Already writing the AST!");
6297 if (!D->isFromASTFile())
6298 return;
6300 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6303 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6304 if (Chain && Chain->isProcessingUpdateRecords()) return;
6305 assert(!WritingAST && "Already writing the AST!");
6306 if (!D->isFromASTFile())
6307 return;
6309 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6312 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6313 const Attr *Attr) {
6314 if (Chain && Chain->isProcessingUpdateRecords()) return;
6315 assert(!WritingAST && "Already writing the AST!");
6316 if (!D->isFromASTFile())
6317 return;
6319 DeclUpdates[D].push_back(
6320 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6323 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6324 if (Chain && Chain->isProcessingUpdateRecords()) return;
6325 assert(!WritingAST && "Already writing the AST!");
6326 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
6327 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6330 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6331 const RecordDecl *Record) {
6332 if (Chain && Chain->isProcessingUpdateRecords()) return;
6333 assert(!WritingAST && "Already writing the AST!");
6334 if (!Record->isFromASTFile())
6335 return;
6336 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6339 void ASTWriter::AddedCXXTemplateSpecialization(
6340 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6341 assert(!WritingAST && "Already writing the AST!");
6343 if (!TD->getFirstDecl()->isFromASTFile())
6344 return;
6345 if (Chain && Chain->isProcessingUpdateRecords())
6346 return;
6348 DeclsToEmitEvenIfUnreferenced.push_back(D);
6351 void ASTWriter::AddedCXXTemplateSpecialization(
6352 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6353 assert(!WritingAST && "Already writing the AST!");
6355 if (!TD->getFirstDecl()->isFromASTFile())
6356 return;
6357 if (Chain && Chain->isProcessingUpdateRecords())
6358 return;
6360 DeclsToEmitEvenIfUnreferenced.push_back(D);
6363 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6364 const FunctionDecl *D) {
6365 assert(!WritingAST && "Already writing the AST!");
6367 if (!TD->getFirstDecl()->isFromASTFile())
6368 return;
6369 if (Chain && Chain->isProcessingUpdateRecords())
6370 return;
6372 DeclsToEmitEvenIfUnreferenced.push_back(D);
6375 //===----------------------------------------------------------------------===//
6376 //// OMPClause Serialization
6377 ////===----------------------------------------------------------------------===//
6379 namespace {
6381 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6382 ASTRecordWriter &Record;
6384 public:
6385 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6386 #define GEN_CLANG_CLAUSE_CLASS
6387 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6388 #include "llvm/Frontend/OpenMP/OMP.inc"
6389 void writeClause(OMPClause *C);
6390 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6391 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6396 void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6397 OMPClauseWriter(*this).writeClause(C);
6400 void OMPClauseWriter::writeClause(OMPClause *C) {
6401 Record.push_back(unsigned(C->getClauseKind()));
6402 Visit(C);
6403 Record.AddSourceLocation(C->getBeginLoc());
6404 Record.AddSourceLocation(C->getEndLoc());
6407 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6408 Record.push_back(uint64_t(C->getCaptureRegion()));
6409 Record.AddStmt(C->getPreInitStmt());
6412 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6413 VisitOMPClauseWithPreInit(C);
6414 Record.AddStmt(C->getPostUpdateExpr());
6417 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6418 VisitOMPClauseWithPreInit(C);
6419 Record.push_back(uint64_t(C->getNameModifier()));
6420 Record.AddSourceLocation(C->getNameModifierLoc());
6421 Record.AddSourceLocation(C->getColonLoc());
6422 Record.AddStmt(C->getCondition());
6423 Record.AddSourceLocation(C->getLParenLoc());
6426 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6427 VisitOMPClauseWithPreInit(C);
6428 Record.AddStmt(C->getCondition());
6429 Record.AddSourceLocation(C->getLParenLoc());
6432 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6433 VisitOMPClauseWithPreInit(C);
6434 Record.AddStmt(C->getNumThreads());
6435 Record.AddSourceLocation(C->getLParenLoc());
6438 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6439 Record.AddStmt(C->getSafelen());
6440 Record.AddSourceLocation(C->getLParenLoc());
6443 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6444 Record.AddStmt(C->getSimdlen());
6445 Record.AddSourceLocation(C->getLParenLoc());
6448 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
6449 Record.push_back(C->getNumSizes());
6450 for (Expr *Size : C->getSizesRefs())
6451 Record.AddStmt(Size);
6452 Record.AddSourceLocation(C->getLParenLoc());
6455 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
6457 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
6458 Record.AddStmt(C->getFactor());
6459 Record.AddSourceLocation(C->getLParenLoc());
6462 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6463 Record.AddStmt(C->getAllocator());
6464 Record.AddSourceLocation(C->getLParenLoc());
6467 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6468 Record.AddStmt(C->getNumForLoops());
6469 Record.AddSourceLocation(C->getLParenLoc());
6472 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6473 Record.AddStmt(C->getEventHandler());
6474 Record.AddSourceLocation(C->getLParenLoc());
6477 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6478 Record.push_back(unsigned(C->getDefaultKind()));
6479 Record.AddSourceLocation(C->getLParenLoc());
6480 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6483 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6484 Record.push_back(unsigned(C->getProcBindKind()));
6485 Record.AddSourceLocation(C->getLParenLoc());
6486 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6489 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6490 VisitOMPClauseWithPreInit(C);
6491 Record.push_back(C->getScheduleKind());
6492 Record.push_back(C->getFirstScheduleModifier());
6493 Record.push_back(C->getSecondScheduleModifier());
6494 Record.AddStmt(C->getChunkSize());
6495 Record.AddSourceLocation(C->getLParenLoc());
6496 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6497 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6498 Record.AddSourceLocation(C->getScheduleKindLoc());
6499 Record.AddSourceLocation(C->getCommaLoc());
6502 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6503 Record.push_back(C->getLoopNumIterations().size());
6504 Record.AddStmt(C->getNumForLoops());
6505 for (Expr *NumIter : C->getLoopNumIterations())
6506 Record.AddStmt(NumIter);
6507 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6508 Record.AddStmt(C->getLoopCounter(I));
6509 Record.AddSourceLocation(C->getLParenLoc());
6512 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6514 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6516 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6518 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6520 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6522 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6523 Record.push_back(C->isExtended() ? 1 : 0);
6524 if (C->isExtended()) {
6525 Record.AddSourceLocation(C->getLParenLoc());
6526 Record.AddSourceLocation(C->getArgumentLoc());
6527 Record.writeEnum(C->getDependencyKind());
6531 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6533 void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
6535 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6537 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6539 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6541 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6543 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6545 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6547 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6549 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6551 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
6552 Record.push_back(C->varlist_size());
6553 for (Expr *VE : C->varlists())
6554 Record.AddStmt(VE);
6555 Record.writeBool(C->getIsTarget());
6556 Record.writeBool(C->getIsTargetSync());
6557 Record.AddSourceLocation(C->getLParenLoc());
6558 Record.AddSourceLocation(C->getVarLoc());
6561 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
6562 Record.AddStmt(C->getInteropVar());
6563 Record.AddSourceLocation(C->getLParenLoc());
6564 Record.AddSourceLocation(C->getVarLoc());
6567 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
6568 Record.AddStmt(C->getInteropVar());
6569 Record.AddSourceLocation(C->getLParenLoc());
6570 Record.AddSourceLocation(C->getVarLoc());
6573 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
6574 VisitOMPClauseWithPreInit(C);
6575 Record.AddStmt(C->getCondition());
6576 Record.AddSourceLocation(C->getLParenLoc());
6579 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
6580 VisitOMPClauseWithPreInit(C);
6581 Record.AddStmt(C->getCondition());
6582 Record.AddSourceLocation(C->getLParenLoc());
6585 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
6586 VisitOMPClauseWithPreInit(C);
6587 Record.AddStmt(C->getThreadID());
6588 Record.AddSourceLocation(C->getLParenLoc());
6591 void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
6592 Record.AddStmt(C->getAlignment());
6593 Record.AddSourceLocation(C->getLParenLoc());
6596 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6597 Record.push_back(C->varlist_size());
6598 Record.AddSourceLocation(C->getLParenLoc());
6599 for (auto *VE : C->varlists()) {
6600 Record.AddStmt(VE);
6602 for (auto *VE : C->private_copies()) {
6603 Record.AddStmt(VE);
6607 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6608 Record.push_back(C->varlist_size());
6609 VisitOMPClauseWithPreInit(C);
6610 Record.AddSourceLocation(C->getLParenLoc());
6611 for (auto *VE : C->varlists()) {
6612 Record.AddStmt(VE);
6614 for (auto *VE : C->private_copies()) {
6615 Record.AddStmt(VE);
6617 for (auto *VE : C->inits()) {
6618 Record.AddStmt(VE);
6622 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6623 Record.push_back(C->varlist_size());
6624 VisitOMPClauseWithPostUpdate(C);
6625 Record.AddSourceLocation(C->getLParenLoc());
6626 Record.writeEnum(C->getKind());
6627 Record.AddSourceLocation(C->getKindLoc());
6628 Record.AddSourceLocation(C->getColonLoc());
6629 for (auto *VE : C->varlists())
6630 Record.AddStmt(VE);
6631 for (auto *E : C->private_copies())
6632 Record.AddStmt(E);
6633 for (auto *E : C->source_exprs())
6634 Record.AddStmt(E);
6635 for (auto *E : C->destination_exprs())
6636 Record.AddStmt(E);
6637 for (auto *E : C->assignment_ops())
6638 Record.AddStmt(E);
6641 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6642 Record.push_back(C->varlist_size());
6643 Record.AddSourceLocation(C->getLParenLoc());
6644 for (auto *VE : C->varlists())
6645 Record.AddStmt(VE);
6648 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6649 Record.push_back(C->varlist_size());
6650 Record.writeEnum(C->getModifier());
6651 VisitOMPClauseWithPostUpdate(C);
6652 Record.AddSourceLocation(C->getLParenLoc());
6653 Record.AddSourceLocation(C->getModifierLoc());
6654 Record.AddSourceLocation(C->getColonLoc());
6655 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6656 Record.AddDeclarationNameInfo(C->getNameInfo());
6657 for (auto *VE : C->varlists())
6658 Record.AddStmt(VE);
6659 for (auto *VE : C->privates())
6660 Record.AddStmt(VE);
6661 for (auto *E : C->lhs_exprs())
6662 Record.AddStmt(E);
6663 for (auto *E : C->rhs_exprs())
6664 Record.AddStmt(E);
6665 for (auto *E : C->reduction_ops())
6666 Record.AddStmt(E);
6667 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
6668 for (auto *E : C->copy_ops())
6669 Record.AddStmt(E);
6670 for (auto *E : C->copy_array_temps())
6671 Record.AddStmt(E);
6672 for (auto *E : C->copy_array_elems())
6673 Record.AddStmt(E);
6677 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6678 Record.push_back(C->varlist_size());
6679 VisitOMPClauseWithPostUpdate(C);
6680 Record.AddSourceLocation(C->getLParenLoc());
6681 Record.AddSourceLocation(C->getColonLoc());
6682 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6683 Record.AddDeclarationNameInfo(C->getNameInfo());
6684 for (auto *VE : C->varlists())
6685 Record.AddStmt(VE);
6686 for (auto *VE : C->privates())
6687 Record.AddStmt(VE);
6688 for (auto *E : C->lhs_exprs())
6689 Record.AddStmt(E);
6690 for (auto *E : C->rhs_exprs())
6691 Record.AddStmt(E);
6692 for (auto *E : C->reduction_ops())
6693 Record.AddStmt(E);
6696 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6697 Record.push_back(C->varlist_size());
6698 VisitOMPClauseWithPostUpdate(C);
6699 Record.AddSourceLocation(C->getLParenLoc());
6700 Record.AddSourceLocation(C->getColonLoc());
6701 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6702 Record.AddDeclarationNameInfo(C->getNameInfo());
6703 for (auto *VE : C->varlists())
6704 Record.AddStmt(VE);
6705 for (auto *VE : C->privates())
6706 Record.AddStmt(VE);
6707 for (auto *E : C->lhs_exprs())
6708 Record.AddStmt(E);
6709 for (auto *E : C->rhs_exprs())
6710 Record.AddStmt(E);
6711 for (auto *E : C->reduction_ops())
6712 Record.AddStmt(E);
6713 for (auto *E : C->taskgroup_descriptors())
6714 Record.AddStmt(E);
6717 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6718 Record.push_back(C->varlist_size());
6719 VisitOMPClauseWithPostUpdate(C);
6720 Record.AddSourceLocation(C->getLParenLoc());
6721 Record.AddSourceLocation(C->getColonLoc());
6722 Record.push_back(C->getModifier());
6723 Record.AddSourceLocation(C->getModifierLoc());
6724 for (auto *VE : C->varlists()) {
6725 Record.AddStmt(VE);
6727 for (auto *VE : C->privates()) {
6728 Record.AddStmt(VE);
6730 for (auto *VE : C->inits()) {
6731 Record.AddStmt(VE);
6733 for (auto *VE : C->updates()) {
6734 Record.AddStmt(VE);
6736 for (auto *VE : C->finals()) {
6737 Record.AddStmt(VE);
6739 Record.AddStmt(C->getStep());
6740 Record.AddStmt(C->getCalcStep());
6741 for (auto *VE : C->used_expressions())
6742 Record.AddStmt(VE);
6745 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6746 Record.push_back(C->varlist_size());
6747 Record.AddSourceLocation(C->getLParenLoc());
6748 Record.AddSourceLocation(C->getColonLoc());
6749 for (auto *VE : C->varlists())
6750 Record.AddStmt(VE);
6751 Record.AddStmt(C->getAlignment());
6754 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6755 Record.push_back(C->varlist_size());
6756 Record.AddSourceLocation(C->getLParenLoc());
6757 for (auto *VE : C->varlists())
6758 Record.AddStmt(VE);
6759 for (auto *E : C->source_exprs())
6760 Record.AddStmt(E);
6761 for (auto *E : C->destination_exprs())
6762 Record.AddStmt(E);
6763 for (auto *E : C->assignment_ops())
6764 Record.AddStmt(E);
6767 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6768 Record.push_back(C->varlist_size());
6769 Record.AddSourceLocation(C->getLParenLoc());
6770 for (auto *VE : C->varlists())
6771 Record.AddStmt(VE);
6772 for (auto *E : C->source_exprs())
6773 Record.AddStmt(E);
6774 for (auto *E : C->destination_exprs())
6775 Record.AddStmt(E);
6776 for (auto *E : C->assignment_ops())
6777 Record.AddStmt(E);
6780 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6781 Record.push_back(C->varlist_size());
6782 Record.AddSourceLocation(C->getLParenLoc());
6783 for (auto *VE : C->varlists())
6784 Record.AddStmt(VE);
6787 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6788 Record.AddStmt(C->getDepobj());
6789 Record.AddSourceLocation(C->getLParenLoc());
6792 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6793 Record.push_back(C->varlist_size());
6794 Record.push_back(C->getNumLoops());
6795 Record.AddSourceLocation(C->getLParenLoc());
6796 Record.AddStmt(C->getModifier());
6797 Record.push_back(C->getDependencyKind());
6798 Record.AddSourceLocation(C->getDependencyLoc());
6799 Record.AddSourceLocation(C->getColonLoc());
6800 Record.AddSourceLocation(C->getOmpAllMemoryLoc());
6801 for (auto *VE : C->varlists())
6802 Record.AddStmt(VE);
6803 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6804 Record.AddStmt(C->getLoopData(I));
6807 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6808 VisitOMPClauseWithPreInit(C);
6809 Record.writeEnum(C->getModifier());
6810 Record.AddStmt(C->getDevice());
6811 Record.AddSourceLocation(C->getModifierLoc());
6812 Record.AddSourceLocation(C->getLParenLoc());
6815 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6816 Record.push_back(C->varlist_size());
6817 Record.push_back(C->getUniqueDeclarationsNum());
6818 Record.push_back(C->getTotalComponentListNum());
6819 Record.push_back(C->getTotalComponentsNum());
6820 Record.AddSourceLocation(C->getLParenLoc());
6821 bool HasIteratorModifier = false;
6822 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
6823 Record.push_back(C->getMapTypeModifier(I));
6824 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6825 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
6826 HasIteratorModifier = true;
6828 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6829 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6830 Record.push_back(C->getMapType());
6831 Record.AddSourceLocation(C->getMapLoc());
6832 Record.AddSourceLocation(C->getColonLoc());
6833 for (auto *E : C->varlists())
6834 Record.AddStmt(E);
6835 for (auto *E : C->mapperlists())
6836 Record.AddStmt(E);
6837 if (HasIteratorModifier)
6838 Record.AddStmt(C->getIteratorModifier());
6839 for (auto *D : C->all_decls())
6840 Record.AddDeclRef(D);
6841 for (auto N : C->all_num_lists())
6842 Record.push_back(N);
6843 for (auto N : C->all_lists_sizes())
6844 Record.push_back(N);
6845 for (auto &M : C->all_components()) {
6846 Record.AddStmt(M.getAssociatedExpression());
6847 Record.AddDeclRef(M.getAssociatedDeclaration());
6851 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6852 Record.push_back(C->varlist_size());
6853 Record.AddSourceLocation(C->getLParenLoc());
6854 Record.AddSourceLocation(C->getColonLoc());
6855 Record.AddStmt(C->getAllocator());
6856 for (auto *VE : C->varlists())
6857 Record.AddStmt(VE);
6860 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6861 VisitOMPClauseWithPreInit(C);
6862 Record.AddStmt(C->getNumTeams());
6863 Record.AddSourceLocation(C->getLParenLoc());
6866 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6867 VisitOMPClauseWithPreInit(C);
6868 Record.AddStmt(C->getThreadLimit());
6869 Record.AddSourceLocation(C->getLParenLoc());
6872 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6873 VisitOMPClauseWithPreInit(C);
6874 Record.AddStmt(C->getPriority());
6875 Record.AddSourceLocation(C->getLParenLoc());
6878 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6879 VisitOMPClauseWithPreInit(C);
6880 Record.writeEnum(C->getModifier());
6881 Record.AddStmt(C->getGrainsize());
6882 Record.AddSourceLocation(C->getModifierLoc());
6883 Record.AddSourceLocation(C->getLParenLoc());
6886 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6887 VisitOMPClauseWithPreInit(C);
6888 Record.writeEnum(C->getModifier());
6889 Record.AddStmt(C->getNumTasks());
6890 Record.AddSourceLocation(C->getModifierLoc());
6891 Record.AddSourceLocation(C->getLParenLoc());
6894 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6895 Record.AddStmt(C->getHint());
6896 Record.AddSourceLocation(C->getLParenLoc());
6899 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6900 VisitOMPClauseWithPreInit(C);
6901 Record.push_back(C->getDistScheduleKind());
6902 Record.AddStmt(C->getChunkSize());
6903 Record.AddSourceLocation(C->getLParenLoc());
6904 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6905 Record.AddSourceLocation(C->getCommaLoc());
6908 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6909 Record.push_back(C->getDefaultmapKind());
6910 Record.push_back(C->getDefaultmapModifier());
6911 Record.AddSourceLocation(C->getLParenLoc());
6912 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6913 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6916 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6917 Record.push_back(C->varlist_size());
6918 Record.push_back(C->getUniqueDeclarationsNum());
6919 Record.push_back(C->getTotalComponentListNum());
6920 Record.push_back(C->getTotalComponentsNum());
6921 Record.AddSourceLocation(C->getLParenLoc());
6922 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6923 Record.push_back(C->getMotionModifier(I));
6924 Record.AddSourceLocation(C->getMotionModifierLoc(I));
6926 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6927 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6928 Record.AddSourceLocation(C->getColonLoc());
6929 for (auto *E : C->varlists())
6930 Record.AddStmt(E);
6931 for (auto *E : C->mapperlists())
6932 Record.AddStmt(E);
6933 for (auto *D : C->all_decls())
6934 Record.AddDeclRef(D);
6935 for (auto N : C->all_num_lists())
6936 Record.push_back(N);
6937 for (auto N : C->all_lists_sizes())
6938 Record.push_back(N);
6939 for (auto &M : C->all_components()) {
6940 Record.AddStmt(M.getAssociatedExpression());
6941 Record.writeBool(M.isNonContiguous());
6942 Record.AddDeclRef(M.getAssociatedDeclaration());
6946 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6947 Record.push_back(C->varlist_size());
6948 Record.push_back(C->getUniqueDeclarationsNum());
6949 Record.push_back(C->getTotalComponentListNum());
6950 Record.push_back(C->getTotalComponentsNum());
6951 Record.AddSourceLocation(C->getLParenLoc());
6952 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6953 Record.push_back(C->getMotionModifier(I));
6954 Record.AddSourceLocation(C->getMotionModifierLoc(I));
6956 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6957 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6958 Record.AddSourceLocation(C->getColonLoc());
6959 for (auto *E : C->varlists())
6960 Record.AddStmt(E);
6961 for (auto *E : C->mapperlists())
6962 Record.AddStmt(E);
6963 for (auto *D : C->all_decls())
6964 Record.AddDeclRef(D);
6965 for (auto N : C->all_num_lists())
6966 Record.push_back(N);
6967 for (auto N : C->all_lists_sizes())
6968 Record.push_back(N);
6969 for (auto &M : C->all_components()) {
6970 Record.AddStmt(M.getAssociatedExpression());
6971 Record.writeBool(M.isNonContiguous());
6972 Record.AddDeclRef(M.getAssociatedDeclaration());
6976 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6977 Record.push_back(C->varlist_size());
6978 Record.push_back(C->getUniqueDeclarationsNum());
6979 Record.push_back(C->getTotalComponentListNum());
6980 Record.push_back(C->getTotalComponentsNum());
6981 Record.AddSourceLocation(C->getLParenLoc());
6982 for (auto *E : C->varlists())
6983 Record.AddStmt(E);
6984 for (auto *VE : C->private_copies())
6985 Record.AddStmt(VE);
6986 for (auto *VE : C->inits())
6987 Record.AddStmt(VE);
6988 for (auto *D : C->all_decls())
6989 Record.AddDeclRef(D);
6990 for (auto N : C->all_num_lists())
6991 Record.push_back(N);
6992 for (auto N : C->all_lists_sizes())
6993 Record.push_back(N);
6994 for (auto &M : C->all_components()) {
6995 Record.AddStmt(M.getAssociatedExpression());
6996 Record.AddDeclRef(M.getAssociatedDeclaration());
7000 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
7001 Record.push_back(C->varlist_size());
7002 Record.push_back(C->getUniqueDeclarationsNum());
7003 Record.push_back(C->getTotalComponentListNum());
7004 Record.push_back(C->getTotalComponentsNum());
7005 Record.AddSourceLocation(C->getLParenLoc());
7006 for (auto *E : C->varlists())
7007 Record.AddStmt(E);
7008 for (auto *D : C->all_decls())
7009 Record.AddDeclRef(D);
7010 for (auto N : C->all_num_lists())
7011 Record.push_back(N);
7012 for (auto N : C->all_lists_sizes())
7013 Record.push_back(N);
7014 for (auto &M : C->all_components()) {
7015 Record.AddStmt(M.getAssociatedExpression());
7016 Record.AddDeclRef(M.getAssociatedDeclaration());
7020 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
7021 Record.push_back(C->varlist_size());
7022 Record.push_back(C->getUniqueDeclarationsNum());
7023 Record.push_back(C->getTotalComponentListNum());
7024 Record.push_back(C->getTotalComponentsNum());
7025 Record.AddSourceLocation(C->getLParenLoc());
7026 for (auto *E : C->varlists())
7027 Record.AddStmt(E);
7028 for (auto *D : C->all_decls())
7029 Record.AddDeclRef(D);
7030 for (auto N : C->all_num_lists())
7031 Record.push_back(N);
7032 for (auto N : C->all_lists_sizes())
7033 Record.push_back(N);
7034 for (auto &M : C->all_components()) {
7035 Record.AddStmt(M.getAssociatedExpression());
7036 Record.AddDeclRef(M.getAssociatedDeclaration());
7040 void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
7041 Record.push_back(C->varlist_size());
7042 Record.push_back(C->getUniqueDeclarationsNum());
7043 Record.push_back(C->getTotalComponentListNum());
7044 Record.push_back(C->getTotalComponentsNum());
7045 Record.AddSourceLocation(C->getLParenLoc());
7046 for (auto *E : C->varlists())
7047 Record.AddStmt(E);
7048 for (auto *D : C->all_decls())
7049 Record.AddDeclRef(D);
7050 for (auto N : C->all_num_lists())
7051 Record.push_back(N);
7052 for (auto N : C->all_lists_sizes())
7053 Record.push_back(N);
7054 for (auto &M : C->all_components()) {
7055 Record.AddStmt(M.getAssociatedExpression());
7056 Record.AddDeclRef(M.getAssociatedDeclaration());
7060 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
7062 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
7063 OMPUnifiedSharedMemoryClause *) {}
7065 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
7067 void
7068 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
7071 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
7072 OMPAtomicDefaultMemOrderClause *C) {
7073 Record.push_back(C->getAtomicDefaultMemOrderKind());
7074 Record.AddSourceLocation(C->getLParenLoc());
7075 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
7078 void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
7079 Record.push_back(C->getAtKind());
7080 Record.AddSourceLocation(C->getLParenLoc());
7081 Record.AddSourceLocation(C->getAtKindKwLoc());
7084 void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
7085 Record.push_back(C->getSeverityKind());
7086 Record.AddSourceLocation(C->getLParenLoc());
7087 Record.AddSourceLocation(C->getSeverityKindKwLoc());
7090 void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
7091 Record.AddStmt(C->getMessageString());
7092 Record.AddSourceLocation(C->getLParenLoc());
7095 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
7096 Record.push_back(C->varlist_size());
7097 Record.AddSourceLocation(C->getLParenLoc());
7098 for (auto *VE : C->varlists())
7099 Record.AddStmt(VE);
7100 for (auto *E : C->private_refs())
7101 Record.AddStmt(E);
7104 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
7105 Record.push_back(C->varlist_size());
7106 Record.AddSourceLocation(C->getLParenLoc());
7107 for (auto *VE : C->varlists())
7108 Record.AddStmt(VE);
7111 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
7112 Record.push_back(C->varlist_size());
7113 Record.AddSourceLocation(C->getLParenLoc());
7114 for (auto *VE : C->varlists())
7115 Record.AddStmt(VE);
7118 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
7119 Record.writeEnum(C->getKind());
7120 Record.writeEnum(C->getModifier());
7121 Record.AddSourceLocation(C->getLParenLoc());
7122 Record.AddSourceLocation(C->getKindKwLoc());
7123 Record.AddSourceLocation(C->getModifierKwLoc());
7126 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
7127 Record.push_back(C->getNumberOfAllocators());
7128 Record.AddSourceLocation(C->getLParenLoc());
7129 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
7130 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
7131 Record.AddStmt(Data.Allocator);
7132 Record.AddStmt(Data.AllocatorTraits);
7133 Record.AddSourceLocation(Data.LParenLoc);
7134 Record.AddSourceLocation(Data.RParenLoc);
7138 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
7139 Record.push_back(C->varlist_size());
7140 Record.AddSourceLocation(C->getLParenLoc());
7141 Record.AddStmt(C->getModifier());
7142 Record.AddSourceLocation(C->getColonLoc());
7143 for (Expr *E : C->varlists())
7144 Record.AddStmt(E);
7147 void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
7148 Record.writeEnum(C->getBindKind());
7149 Record.AddSourceLocation(C->getLParenLoc());
7150 Record.AddSourceLocation(C->getBindKindLoc());
7153 void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
7154 VisitOMPClauseWithPreInit(C);
7155 Record.AddStmt(C->getSize());
7156 Record.AddSourceLocation(C->getLParenLoc());
7159 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
7160 writeUInt32(TI->Sets.size());
7161 for (const auto &Set : TI->Sets) {
7162 writeEnum(Set.Kind);
7163 writeUInt32(Set.Selectors.size());
7164 for (const auto &Selector : Set.Selectors) {
7165 writeEnum(Selector.Kind);
7166 writeBool(Selector.ScoreOrCondition);
7167 if (Selector.ScoreOrCondition)
7168 writeExprRef(Selector.ScoreOrCondition);
7169 writeUInt32(Selector.Properties.size());
7170 for (const auto &Property : Selector.Properties)
7171 writeEnum(Property.Kind);
7176 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
7177 if (!Data)
7178 return;
7179 writeUInt32(Data->getNumClauses());
7180 writeUInt32(Data->getNumChildren());
7181 writeBool(Data->hasAssociatedStmt());
7182 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
7183 writeOMPClause(Data->getClauses()[I]);
7184 if (Data->hasAssociatedStmt())
7185 AddStmt(Data->getAssociatedStmt());
7186 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
7187 AddStmt(Data->getChildren()[I]);